Basically all you need to do is add:
useLibrary 'org.apache.http.legacy'
To your build.gradle
file.
^
is the Python bitwise XOR operator. It is how you spell XOR
in python:
>>> 0 ^ 0
0
>>> 0 ^ 1
1
>>> 1 ^ 0
1
>>> 1 ^ 1
0
XOR stands for exclusive OR. It is used in cryptography because it let's you 'flip' the bits using a mask in a reversable operation:
>>> 10 ^ 5
15
>>> 15 ^ 5
10
where 5
is the mask; (input XOR mask) XOR mask gives you the input again.
add_header
works as well with proxy_pass
as without. I just today set up a configuration where I've used exactly that directive. I have to admit though that I've struggled as well setting this up without exactly recalling the reason, though.
Right now I have a working configuration and it contains the following (among others):
server {
server_name .myserver.com
location / {
proxy_pass http://mybackend;
add_header X-Upstream $upstream_addr;
}
}
Before nginx 1.7.5
add_header worked only on successful responses, in contrast to the HttpHeadersMoreModule mentioned by Sebastian Goodman in his answer.
Since nginx 1.7.5
you can use the keyword always
to include custom headers even in error responses. For example:
add_header X-Upstream $upstream_addr always;
Limitation: You cannot override the server
header value using add_header
.
I think there could be no form elements by name 'month' or 'op'. Can you verify if the HTML source (of the page which results in error when submitted) indeed has html elements by he above names
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length);
is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
Maven install plugin has command line usage to install a jar into the local repository, POM is optional but you will have to specify the GroupId, ArtifactId, Version and Packaging (all the POM stuff).
I had the same question as the OP, and none of those answers fitted my needs. I needed a simple condition, for a simple need.
Here's my answer:
if ($("#myoverflowingelement").prop('scrollWidth') > $("#myoverflowingelement").width() ) {
alert("this element is overflowing !!");
}
else {
alert("this element is not overflowing!!");
}
Also, you can change scrollWidth
by scrollHeight
if you need to test the either case.
DECIMAL_DIG
from <float.h>
should give at least a reasonable approximation of that. Since that deals with decimal digits, and it's really stored in binary, you can probably store something a little larger without losing precision, but exactly how much is hard to say. I suppose you should be able to figure it out from FLT_RADIX
and DBL_MANT_DIG
, but I'm not sure I'd completely trust the result.
Install sshpass, then launch the command:
sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname
If you have two []byte
, compare them using bytes.Equal. The Golang documentation says:
Equal returns a boolean reporting whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.
Usage:
package main
import (
"fmt"
"bytes"
)
func main() {
a := []byte {1,2,3}
b := []byte {1,2,3}
c := []byte {1,2,2}
fmt.Println(bytes.Equal(a, b))
fmt.Println(bytes.Equal(a, c))
}
This will print
true
false
Simple solution
<select ng-model='form.type' required><options>
<option ng-repeat="tp in typeOptions" ng-selected="
{{form.type==tp.value?true:false}}" value="{{tp.value}}">{{tp.name}}</option>
https://github.com/nodejs/node-gyp#on-windows
try
npm config set python D:\Library\Python\Python27\python.exe
Run it as a CGI-script via a simple http call, AJAX, whatever - with the coordinates you want to move the mouse to, eg:
http://localhost:9876/cgi/mousemover?x=200&y=450
PS: For any problem, there are hundreds of excuses as to why, and how - it can't, and shouldn't - be done.. But in this infinite universe, it's really just a matter of determination - as to whether YOU will make it happen.
The to_char()
function is there to format numbers:
select to_char(column_1, 'fm000') as column_2
from some_table;
The fm
prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000
simply defines the number of digits you want to have.
psql (9.3.5) Type "help" for help. postgres=> with sample_numbers (nr) as ( postgres(> values (1),(11),(100) postgres(> ) postgres-> select to_char(nr, 'fm000') postgres-> from sample_numbers; to_char --------- 001 011 100 (3 rows) postgres=>
For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html
A simple program's compilation workflow is simple, I can draw it as a small graph: source -> [compilation] -> object [linking] -> executable. There are files (source, object, executable) in this graph, and rules (make's terminology). That graph is definied in the Makefile.
When you launch make, it reads Makefile, and checks for changed files. If there's any, it triggers the rule, which depends on it. The rule may produce/update further files, which may trigger other rules and so on. If you create a good makefile, only the necessary rules (compiler/link commands) will run, which stands "to next" from the modified file in the dependency path.
Pick an example Makefile, read the manual for syntax (anyway, it's clear for first sight, w/o manual), and draw the graph. You have to understand compiler options in order to find out the names of the result files.
The make graph should be as complex just as you want. You can even do infinite loops (don't do)! You can tell make, which rule is your target, so only the left-standing files will be used as triggers.
Again: draw the graph!.
that’s just wrong: is not a wrapper. The element denotes a semantic section of your content to help construct a document outline. It should contain a heading. If you’re looking for a page wrapper element (for any flavour of HTML or XHTML), consider applying styles directly to the element as described by Kroc Camen. If you still need an additional element for styling, use a . As Dr Mike explains, div isn’t dead, and if there’s nothing else more appropriate, it’s probably where you really want to apply your CSS.
you can check this : http://html5doctor.com/avoiding-common-html5-mistakes/
I ran into the same problem. My fix was changing
<parameter value="v12.0" />
to
<parameter value="mssqllocaldb" />
into the "app.config" file.
If you are working with Web application you can try this.
StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")
const setTimeoutAsync = (cb, delay) =>
new Promise((resolve) => {
setTimeout(() => {
resolve(cb());
}, delay);
});
We can pass custom 'cb fxn' like this one
Here's the code for server side firebase cloud request from C# / Asp.net.
Please note that your client side should have same topic.
e.g.
FirebaseMessaging.getInstance().subscribeToTopic("news");
public String SendNotificationFromFirebaseCloud()
{
var result = "-1";
var webAddr = "https://fcm.googleapis.com/fcm/send";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization:key=" + YOUR_FIREBASE_SERVER_KEY);
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"to\": \"/topics/news\",\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\",}}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.
The HTML in your example will be:
<tr>
<td>TEST</td>
</tr>
Read the PHP documentation that explains it.
With question 3, this article states that RESTful Services are appropiate in this scenarios:
While SOAP is the way to go when:
Bootstrap has a wide range of responsive margin and padding utility classes. They work for all breakpoints:
xs (<=576px), sm (>=576px), md (>=768px), lg (>=992px) or xl (>=1200px))
The classes are used in the format:
{property}{sides}-{size} for xs & {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.
m - sets margin
p - sets padding
t - sets margin-top or padding-top
b - sets margin-bottom or padding-bottom
l - sets margin-left or padding-left
r - sets margin-right or padding-right
x - sets both padding-left and padding-right or margin-left and margin-right
y - sets both padding-top and padding-bottom or margin-top and margin-bottom
blank - sets a margin or padding on all 4 sides of the element
0 - sets margin or padding to 0
1 - sets margin or padding to .25rem (4px if font-size is 16px)
2 - sets margin or padding to .5rem (8px if font-size is 16px)
3 - sets margin or padding to 1rem (16px if font-size is 16px)
4 - sets margin or padding to 1.5rem (24px if font-size is 16px)
5 - sets margin or padding to 3rem (48px if font-size is 16px)
auto - sets margin to auto
See more at Bootstrap 4.5 - Spacing
Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/
// The connection URL
String url = "https://ajax.googleapis.com/ajax/" +
"services/search/web?v=1.0&q={query}";
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");
The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Example:
your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Output:
>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>
find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'
I find marking the property
as readonly
cleaner than the above answers. I believe vb14 is required.
Private _Name As String
Public ReadOnly Property Name() As String
Get
Return _Name
End Get
End Property
This can be condensed to
Public ReadOnly Property Name As String
https://msdn.microsoft.com/en-us/library/dd293589.aspx?f=255&MSPPError=-2147217396
Depending on your project, you might want to consider using EditorConfig (https://editorconfig.org/). There's a Notepad++ plugin which will load an .editorconfig where you can specify "lf" as the mandatory line ending.
I've only started using it, but it's nice so far, and open source projects I've worked on have included .editorconfig files for years. The "EOL Conversion" setting isn't changed, so it can be a bit confusing, but if you "View > Show Symbol > Show End of Line", you can see that it's adding LF instead of CRLF, even when "EOL Conversion" and the lower bottom corner shows something else (e.g. Windows (CR LF)).
You have to add to the source property an object with a property called "uri" where you can specify the path of your image as you can see in the following example:
<Image style={styles.image} source={{uri: "http://www.mysyte.com/myimage.jpg"}} />
remember then to set the width and height via the style property:
var styles = StyleSheet.create({
image:{
width: 360,
height: 40,
}
});
If you put sys.path.append('dir/to/path')
without check it is already added, you could generate a long list in sys.path
. For that, I recommend this:
import sys
import os # if you want this directory
try:
sys.path.index('/dir/path') # Or os.getcwd() for this directory
except ValueError:
sys.path.append('/dir/path') # Or os.getcwd() for this directory
One of the best solutions for this, you do not use multiple or more than 1,000 input fields. You can concatenate multiple inputs with any special character, for ex. @
.
See this:
<input type='text' name='hs1' id='hs1'>
<input type='text' name='hs2' id='hs2'>
<input type='text' name='hs3' id='hs3'>
<input type='text' name='hs4' id='hs4'>
<input type='text' name='hs5' id='hs5'>
<input type='hidden' name='hd' id='hd'>
Using any script (JavaScript or JScript),
document.getElementById("hd").value = document.getElementById("hs1").value+"@"+document.getElementById("hs2").value+"@"+document.getElementById("hs3").value+"@"+document.getElementById("hs4").value+"@"+document.getElementById("hs5").value
With this, you will bypass the max_input_vars
issue. If you increase max_input_vars
in the php.ini file, that is harmful to the server because it uses more server cache memory, and this can sometimes crash the server.
It is a pity that the chosen matrix, repeated here again, is either singular or badly conditioned:
A = matrix( [[1,2,3],[11,12,13],[21,22,23]])
By definition, the inverse of A when multiplied by the matrix A itself must give a unit matrix. The A chosen in the much praised explanation does not do that. In fact just looking at the inverse gives a clue that the inversion did not work correctly. Look at the magnitude of the individual terms - they are very, very big compared with the terms of the original A matrix...
It is remarkable that the humans when picking an example of a matrix so often manage to pick a singular matrix!
I did have a problem with the solution, so looked into it further. On the ubuntu-kubuntu platform, the debian package numpy does not have the matrix and the linalg sub-packages, so in addition to import of numpy, scipy needs to be imported also.
If the diagonal terms of A are multiplied by a large enough factor, say 2, the matrix will most likely cease to be singular or near singular. So
A = matrix( [[2,2,3],[11,24,13],[21,22,46]])
becomes neither singular nor nearly singular and the example gives meaningful results... When dealing with floating numbers one must be watchful for the effects of inavoidable round off errors.
Thanks for your contribution,
OldAl.
I think you are looking for qsort
.
qsort
function is the implementation of quicksort algorithm found in stdlib.h
in C/C++
.
Here is the syntax to call qsort
function:
void qsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *));
List of arguments:
base: pointer to the first element or base address of the array
nmemb: number of elements in the array
size: size in bytes of each element
compar: a function that compares two elements
Here is a code example which uses qsort
to sort an array:
#include <stdio.h>
#include <stdlib.h>
int arr[] = { 33, 12, 6, 2, 76 };
// compare function, compares two elements
int compare (const void * num1, const void * num2) {
if(*(int*)num1 > *(int*)num2)
return 1;
else
return -1;
}
int main () {
int i;
printf("Before sorting the array: \n");
for( i = 0 ; i < 5; i++ ) {
printf("%d ", arr[i]);
}
// calling qsort
qsort(arr, 5, sizeof(int), compare);
printf("\nAfter sorting the array: \n");
for( i = 0 ; i < 5; i++ ) {
printf("%d ", arr[i]);
}
return 0;
}
You can type man 3 qsort
in Linux/Mac terminal to get a detailed info about qsort
.
Link to qsort man page
I have face this issue in post request. I have changed like this in axios header. It works fine.
axios.post('http://localhost/M-Experience/resources/GETrends.php',
{
firstName: this.name
},
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Your update syntax is incorrect. Please check Update Syntax for the correct syntax.
$sql = "UPDATE `access_users` set `contact_first_name` = :firstname, `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";
I had a similar error, but I was using Redux for state management.
My Error:
Uncaught TypeError: this.props.user.map is not a function
What Fixed My Error:
I wrapped my response data in an array. Therefore, I can then map through the array. Below is my solution.
const ProfileAction = () => dispatch => {
dispatch({type: STARTFETCHING})
AxiosWithAuth()
.get(`http://localhost:3333/api/users/${id here}`)
.then((res) => {
// wrapping res.data in an array like below is what solved the error
dispatch({type: FETCHEDPROFILE, payload: [res.data]})
}) .catch((error) => {
dispatch({type: FAILDFETCH, error: error})
})
}
export default ProfileAction
In gradle-wrapper.properties I changed back from gradle-5.1.1 to distributionUrl=https://services.gradle.org/distributions/gradle-4.10.3-all.zip
cout << fixed << setprecision(2) << total;
setprecision
specifies the minimum precision. So
cout << setprecision (2) << 1.2;
will print 1.2
fixed
says that there will be a fixed number of decimal digits after the decimal point
cout << setprecision (2) << fixed << 1.2;
will print 1.20
An alternative approach with vue-cli
version 3 is to add a .env
file in the root project directory (along side package.json
) with the contents:
PORT=3000
Running npm run serve
will now indicate the app is running on port 3000.
It's been years since the question was asked and was answered.
For anyone who looks for a simple drawing canvas (eg, for taking the signature from the user/customer), here I am posting a more simplified jquery version of the currently accepted answer
$(document).ready(function() {_x000D_
var flag, dot_flag = false,_x000D_
prevX, prevY, currX, currY = 0,_x000D_
color = 'black', thickness = 2;_x000D_
var $canvas = $('#canvas');_x000D_
var ctx = $canvas[0].getContext('2d');_x000D_
_x000D_
$canvas.on('mousemove mousedown mouseup mouseout', function(e) {_x000D_
prevX = currX;_x000D_
prevY = currY;_x000D_
currX = e.clientX - $canvas.offset().left;_x000D_
currY = e.clientY - $canvas.offset().top;_x000D_
if (e.type == 'mousedown') {_x000D_
flag = true;_x000D_
}_x000D_
if (e.type == 'mouseup' || e.type == 'mouseout') {_x000D_
flag = false;_x000D_
}_x000D_
if (e.type == 'mousemove') {_x000D_
if (flag) {_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(prevX, prevY);_x000D_
ctx.lineTo(currX, currY);_x000D_
ctx.strokeStyle = color;_x000D_
ctx.lineWidth = thickness;_x000D_
ctx.stroke();_x000D_
ctx.closePath();_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
$('.canvas-clear').on('click', function(e) {_x000D_
c_width = $canvas.width();_x000D_
c_height = $canvas.height();_x000D_
ctx.clearRect(0, 0, c_width, c_height);_x000D_
$('#canvasimg').hide();_x000D_
});_x000D_
});
_x000D_
<html>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<body>_x000D_
<canvas id="canvas" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>_x000D_
<input type="button" value="Clear" class="canvas-clear" />_x000D_
</body>_x000D_
</html>
_x000D_
An object of a class cannot be set to NULL; however, you can set a pointer (which contains a memory address of an object) to NULL.
Example of what you can't do which you are asking:
Cat c;
c = NULL;//Compiling error
Example of what you can do:
Cat c;
//Set p to hold the memory address of the object c
Cat *p = &c;
//Set p to hold NULL
p = NULL;
Create an integer random between e.g. 1-11
and multiply it by 5
. Simple math.
import random
for x in range(20):
print random.randint(1,11)*5,
print
produces e.g.
5 40 50 55 5 15 40 45 15 20 25 40 15 50 25 40 20 15 50 10
If you are using the windows CMD you can use this command to create a database using sqlite3
C:\sqlite3.exe DBNAME.db ".read DBSCRIPT.sql"
If you haven't a database with that name sqlite3 will create one, and if you already have one, it will run it anyways but with the "TABLENAME already exists" error, I think you can also use this command to change an already existing database (but im not sure)
If someone is using @Sceduled this might work for you.
@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")
This worked for me.
Unfortunately, it's not in the .NET Framework itself. My wish is that you could integrate with FileZilla, but I don't think it exposes an interface. They do have scripting I think, but it won't be as clean obviously.
I've used CuteFTP in a project which does SFTP. It exposes a COM component which I created a .NET wrapper around. The catch, you'll find, is permissions. It runs beautifully under the Windows credentials which installed CuteFTP, but running under other credentials requires permissions to be set in DCOM.
background:url(directoryName/imageName.extention) bottom left no-repeat;
background-color: red;
This could be complicated way of doing
String newString = new String(oldString);
This shortens the String is the underlying char[] used is much longer.
However more specifically it will be checking that every character can be UTF-8 encoded.
There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?
Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'
String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));
prints
false
select * into mytable_backup from mytable
Makes a copy of table mytable, and every row in it, called mytable_backup.
I tried all the settings above but this fixed my problem.
You have to define nginx to check if the php file actually exists in that location. I found try_files $uri = 404;
solving that problem.
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
fastcgi_index index.php;
}
43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back. http://en.wikipedia.org/wiki/ASCII
You use ComponentScan to scan multiple packages using
@ComponentScan({"com.my.package.first","com.my.package.second"})
In Ruby IO module documentation, I suppose.
Mode | Meaning
-----+--------------------------------------------------------
"r" | Read-only, starts at beginning of file (default mode).
-----+--------------------------------------------------------
"r+" | Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w" | Write-only, truncates existing file
| to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" | Read-write, truncates existing file to zero length
| or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a" | Write-only, starts at end of file if file exists,
| otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" | Read-write, starts at end of file if file exists,
| otherwise creates a new file for reading and
| writing.
-----+--------------------------------------------------------
"b" | Binary file mode (may appear with
| any of the key letters listed above).
| Suppresses EOL <-> CRLF conversion on Windows. And
| sets external encoding to ASCII-8BIT unless explicitly
| specified.
-----+--------------------------------------------------------
"t" | Text file mode (may appear with
| any of the key letters listed above except "b").
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
You are getting that error because an application with a package name same as your application already exists. If you are sure that you have not installed the same application before, change the package name and try.
Else wise, here is what you can do:
Or for custom options
<%= f.select :desired_attribute, ['option1', 'option2']%>
thanks :
Kiwy
with AIX:
getPathByPid()
{
if [[ -e /proc/$1/object/a.out ]]; then
inode=`ls -i /proc/$1/object/a.out 2>/dev/null | awk '{print $1}'`
if [[ $? -eq 0 ]]; then
strnode=${inode}"$"
strNum=`ls -li /proc/$1/object/ 2>/dev/null | grep $strnode | awk '{print $NF}' | grep "[0-9]\{1,\}\.[0-9]\{1,\}\."`
if [[ $? -eq 0 ]]; then
# jfs2.10.6.5869
n1=`echo $strNum|awk -F"." '{print $2}'`
n2=`echo $strNum|awk -F"." '{print $3}'`
# brw-rw---- 1 root system 10, 6 Aug 23 2013 hd9var
strexp="^b.*"$n1,"[[:space:]]\{1,\}"$n2"[[:space:]]\{1,\}.*$" # "^b.*10, \{1,\}5 \{1,\}.*$"
strdf=`ls -l /dev/ | grep $strexp | awk '{print $NF}'`
if [[ $? -eq 0 ]]; then
strMpath=`df | grep $strdf | awk '{print $NF}'`
if [[ $? -eq 0 ]]; then
find $strMpath -inum $inode 2>/dev/null
if [[ $? -eq 0 ]]; then
return 0
fi
fi
fi
fi
fi
fi
return 1
}
This post is just an observation for Python behaviour I encountered. Maybe the advices you read above don't work for you if you made the same thing I did below.
Namely, I have a module which contains global/shared variables (as suggested above):
#sharedstuff.py
globaltimes_randomnode=[]
globalist_randomnode=[]
Then I had the main module which imports the shared stuff with:
import sharedstuff as shared
and some other modules that actually populated these arrays. These are called by the main module. When exiting these other modules I can clearly see that the arrays are populated. But when reading them back in the main module, they were empty. This was rather strange for me (well, I am new to Python). However, when I change the way I import the sharedstuff.py in the main module to:
from globals import *
it worked (the arrays were populated).
Just sayin'
This is because the shell script is formatted in windows we need to change to unix format. You can run the dos2unix command on any Linux system.
dos2unix your-file.sh
If you don’t have access to a Linux system, you may use the Git Bash for Windows which comes with a dos2unix.exe
dos2unix.exe your-file.sh
If you want to store the result in one file outside the container, in your local machine, you can do something like this.
RES_FILE=$(readlink -f /tmp/result.txt)
docker run --rm -v ${RES_FILE}:/result.txt img bash -c "cat /etc/passwd | grep root > /result.txt"
The result of your commands will be available in /tmp/result.txt
in your local machine.
yum -y remove php*
to remove all php packages then you can install the 5.6 ones.
The problem is that (as of 2016), for the password field, Firefox and Internet Explorer use the character "Black Circle" (?), which uses the Unicode code point 25CF
, but Chrome uses the character "Bullet" (•), which uses the Unicode code point 2022
.
As you can see, even in the StackOverflow font the two characters have different sizes.
The font you're using, "Lucida Sans Unicode", has an even greater disparity between the sizes of these two characters, leading to you noticing the difference.
The simple solution is to use a font in which both characters have similar sizes.
The fix could thus be to use a default font of the browser, which should render the characters in the password field just fine:
input[type="password"] {
font-family: caption;
}
The following sample looks recursively for your search string
in the *.xml
and *.js
files located somewhere inside the folders path1
, path2
and path3
.
grep -r --include=*.xml --include=*.js "your search string" path1 path2 path3
So you can search in a subset of the files for many directories, just providing the paths at the end.
Use setItem
and getItem
if you want to write simple strings to localStorage. Also you should be using text()
if it's the text you're after as you say, else you will get the full HTML as a string.
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// alert the value to check if we got it
alert(localStorage.getItem('test'));
JSFiddle: https://jsfiddle.net/f3zLa3zc/
// get html
var html = $('#test')[0].outerHTML;
// set localstorage
localStorage.setItem('htmltest', html);
// test if it works
alert(localStorage.getItem('htmltest'));
JSFiddle:
https://jsfiddle.net/psfL82q3/1/
A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable
and blur()
is used to change the contents of the div and overwrite the old localStorage
entry.
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// bind text to 'blur' event for div
$('#test').on('blur', function() {
// check the new text
var newText = $(this).text();
// overwrite the old text
localStorage.setItem('test', newText);
// test if it works
alert(localStorage.getItem('test'));
});
If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.
JSFiddle:
https://jsfiddle.net/g1b8m1fc/
I started building my app with create-react-app (see "Create a New App" tab). The README.md that comes with it gives this example:
import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;
This worked perfectly for me. Here's a link to the master doc for that README, which explains (excerpt):
...You can import a file right in a JavaScript module. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the src attribute of an image or the href of a link to a PDF.
To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a data URI instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png...
Pragma directives specify operating system or machine specific (x86 or x64 etc) compiler options. There are several options available. Details can be found in https://msdn.microsoft.com/en-us/library/d9x1s805.aspx
#pragma comment( comment-type [,"commentstring"] )
has this format.
Refer https://msdn.microsoft.com/en-us/library/7f0aews7.aspx for details about different comment-type.
#pragma comment(lib, "kernel32")
#pragma comment(lib, "user32")
The above lines of code includes the library names (or path) that need to be searched by the linker. These details are included as part of the library-search record in the object file.
So, in this case kernel.lib
and user32.lib
are searched by the linker and included in the final executable.
As also mentioned in the comments you need to abstract away the HttpClient
so as not to be coupled to it. I've done something similar in the past. I'll try to adapt what I did with what you are trying to do.
First look at the HttpClient
class and decided on what functionality it provided that would be needed.
Here is a possibility:
public interface IHttpClient {
System.Threading.Tasks.Task<T> DeleteAsync<T>(string uri) where T : class;
System.Threading.Tasks.Task<T> DeleteAsync<T>(Uri uri) where T : class;
System.Threading.Tasks.Task<T> GetAsync<T>(string uri) where T : class;
System.Threading.Tasks.Task<T> GetAsync<T>(Uri uri) where T : class;
System.Threading.Tasks.Task<T> PostAsync<T>(string uri, object package);
System.Threading.Tasks.Task<T> PostAsync<T>(Uri uri, object package);
System.Threading.Tasks.Task<T> PutAsync<T>(string uri, object package);
System.Threading.Tasks.Task<T> PutAsync<T>(Uri uri, object package);
}
Again as stated before this was for particular purposes. I completely abstracted away most dependencies to anything dealing with HttpClient
and focused on what I wanted returned. You should evaluate how you want to abstract the HttpClient
to provide only the necessary functionality you want.
This will now allow you to mock only what is needed to be tested.
I would even recommend doing away with IHttpHandler
completely and use the HttpClient
abstraction IHttpClient
. But I'm just not picking as you can replace the body of your handler interface with the members of the abstracted client.
An implementation of the IHttpClient
can then be used to wrapp/adapt a real/concrete HttpClient
or any other object for that matter, that can be used to make HTTP requests as what you really wanted was a service that provided that functionality as apposed to HttpClient
specifically. Using the abstraction is a clean (My opinion) and SOLID approach and can make your code more maintainable if you need to switch out the underlying client for something else as the framework changes.
Here is a snippet of how an implementation could be done.
/// <summary>
/// HTTP Client adaptor wraps a <see cref="System.Net.Http.HttpClient"/>
/// that contains a reference to <see cref="ConfigurableMessageHandler"/>
/// </summary>
public sealed class HttpClientAdaptor : IHttpClient {
HttpClient httpClient;
public HttpClientAdaptor(IHttpClientFactory httpClientFactory) {
httpClient = httpClientFactory.CreateHttpClient(**Custom configurations**);
}
//...other code
/// <summary>
/// Send a GET request to the specified Uri as an asynchronous operation.
/// </summary>
/// <typeparam name="T">Response type</typeparam>
/// <param name="uri">The Uri the request is sent to</param>
/// <returns></returns>
public async System.Threading.Tasks.Task<T> GetAsync<T>(Uri uri) where T : class {
var result = default(T);
//Try to get content as T
try {
//send request and get the response
var response = await httpClient.GetAsync(uri).ConfigureAwait(false);
//if there is content in response to deserialize
if (response.Content.Headers.ContentLength.GetValueOrDefault() > 0) {
//get the content
string responseBodyAsText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
//desrialize it
result = deserializeJsonToObject<T>(responseBodyAsText);
}
} catch (Exception ex) {
Log.Error(ex);
}
return result;
}
//...other code
}
As you can see in the above example, a lot of the heavy lifting usually associated with using HttpClient
is hidden behind the abstraction.
You connection class can then be inject with the abstracted client
public class Connection
{
private IHttpClient _httpClient;
public Connection(IHttpClient httpClient)
{
_httpClient = httpClient;
}
}
Your test can then mock what is needed for your SUT
private IHttpClient _httpClient;
[TestMethod]
public void TestMockConnection()
{
SomeModelObject model = new SomeModelObject();
var httpClientMock = new Mock<IHttpClient>();
httpClientMock.Setup(c => c.GetAsync<SomeModelObject>(It.IsAny<string>()))
.Returns(() => Task.FromResult(model));
_httpClient = httpClientMock.Object;
var client = new Connection(_httpClient);
// Assuming doSomething uses the client to make
// a request for a model of type SomeModelObject
client.doSomething();
}
The ports required will be different for your XMPP Server and any XMPP Clients. Most "modern" XMPP Servers follow the defined IANA Ports for Server-to-Server 5269 and for Client-to-Server 5222. Any additional ports depends on what features you enable on the Server, i.e. if you offer BOSH then you may need to open port 80.
File Transfer is highly dependent on both the Clients you use and the Server as to what port it will use, but most of them also negotiate the connect via your existing XMPP Client-to-Server link so the required port opening will be client side (or proxied via port 80.)
I keep looking for a built in solution to this problem like there is in AngularJS. But until then this solution works for me, It's simple, and preserves back button functionality.
app.component.html
<router-outlet (deactivate)="onDeactivate()"></router-outlet>
app.component.ts
onDeactivate() {
document.body.scrollTop = 0;
// Alternatively, you can scroll to top by using this other call:
// window.scrollTo(0, 0)
}
Answer from zurfyx original post
BULK INSERT TextData
FROM 'E:\filefromabove.txt'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = '|', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
ERRORFILE = 'E:\ErrorRows.csv',
TABLOCK
)
OpenOffice.org can view HTML tables. Simply use the open command on the HTML file, or select and copy the table in your browser and then Paste Special in OpenOffice.org. It will query you for the file type, one of which should be HTML. Select that and voila!
It is a dummy table with one element in it. It is useful because Oracle doesn't allow statements like
SELECT 3+4
You can work around this restriction by writing
SELECT 3+4 FROM DUAL
instead.
I would just not add it in the first place:
var sb = new StringBuilder();
bool first = true;
foreach (var foo in items) {
if (first)
first = false;
else
sb.Append('&');
// for example:
var escapedValue = System.Web.HttpUtility.UrlEncode(foo);
sb.Append(key).Append('=').Append(escapedValue);
}
var s = sb.ToString();
https://github.com/quartzjer/js0n
Ugliest interface possible, but does what you ask. Zero allocations.
http://zserge.com/jsmn.html Another zero-allocation approach.
The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.
Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.
And to answer your "writer" part of the question i doubt that you could beat an efficient
printf("{%s:%s}",name,value)
implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.
EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.
mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8
If the other solutions here do not work, make sure you are not in 'offline' mode. If enabled, android will not download the required files and you will get this error.
Yet another answer:
https://github.com/gcamp/GCPlaceholderTextView
Change Class of UITextView
in IB to GCPlaceholderTextView
and set the placeholder
property
Open the file in src->router->index.js
At the bottom of this file:
const router = new VueRouter({
mode: "history",
routes,
});
To sure, you should use function to check is null and empty as below:
string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}
Here's my Swifty solution for any future onlookers.
1) Create a protocol to handle both login and logout functions:
protocol LoginFlowHandler {
func handleLogin(withWindow window: UIWindow?)
func handleLogout(withWindow window: UIWindow?)
}
2) Extend said protocol and provide the functionality here for logging out:
extension LoginFlowHandler {
func handleLogin(withWindow window: UIWindow?) {
if let _ = AppState.shared.currentUserId {
//User has logged in before, cache and continue
self.showMainApp(withWindow: window)
} else {
//No user information, show login flow
self.showLogin(withWindow: window)
}
}
func handleLogout(withWindow window: UIWindow?) {
AppState.shared.signOut()
showLogin(withWindow: window)
}
func showLogin(withWindow window: UIWindow?) {
window?.subviews.forEach { $0.removeFromSuperview() }
window?.rootViewController = nil
window?.rootViewController = R.storyboard.login.instantiateInitialViewController()
window?.makeKeyAndVisible()
}
func showMainApp(withWindow window: UIWindow?) {
window?.rootViewController = nil
window?.rootViewController = R.storyboard.mainTabBar.instantiateInitialViewController()
window?.makeKeyAndVisible()
}
}
3) Then I can conform my AppDelegate to the LoginFlowHandler protocol, and call handleLogin
on startup:
class AppDelegate: UIResponder, UIApplicationDelegate, LoginFlowHandler {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow.init(frame: UIScreen.main.bounds)
initialiseServices()
handleLogin(withWindow: window)
return true
}
}
From here, my protocol extension will handle the logic or determining if the user if logged in/out, and then change the windows rootViewController accordingly!
SELECT *
FROM B
WHERE NOT EXISTS (SELECT 1
FROM A
WHERE A.ID = B.ID)
In Bootstrap 4:
class="font-weight-bold"
Or:
<strong>text</strong>
The TextWatcher
interface has 3 callbacks methods which are all called in the following order when a change occurred to the text:
beforeTextChanged(CharSequence s, int start, int count, int after)
s
parameter is the text before any change is applied.start
parameter is the position of the beginning of the changed part in the text.count
parameter is the length of the changed part in the s
sequence since the start
position.after
parameter is the length of the new sequence which will replace the part of the s
sequence from start
to start+count
.TextView
from this method (by using myTextView.setText(String newText)
).onTextChanged(CharSequence s, int start, int before, int count)`
beforeTextChanged
method but called after the text changes.s
parameter is the text after changes have been applied.start
parameter is the same as in the beforeTextChanged
method.count
parameter is the after
parameter in the beforeTextChanged method.before
parameter is the count
parameter in the beforeTextChanged method.TextView
from this method (by using myTextView.setText(String newText)
).afterTextChanged(Editable s)
TextView
from this method.TextView
, the TextWatcher
will be triggered again, starting an infinite loop. You should then add like a boolean _ignore
property which prevent the infinite loop.new TextWatcher() {
boolean _ignore = false; // indicates if the change was made by the TextWatcher itself.
@Override
public void afterTextChanged(Editable s) {
if (_ignore)
return;
_ignore = true; // prevent infinite loop
// Change your text here.
// myTextView.setText(myNewText);
_ignore = false; // release, so the TextWatcher start to listen again.
}
// Other methods...
}
TextViewListener
Personally, I made my custom text listener, which gives me the 4 parts in separate strings, which is, for me, much more intuitive to use.
/**
* Text view listener which splits the update text event in four parts:
* <ul>
* <li>The text placed <b>before</b> the updated part.</li>
* <li>The <b>old</b> text in the updated part.</li>
* <li>The <b>new</b> text in the updated part.</li>
* <li>The text placed <b>after</b> the updated part.</li>
* </ul>
* Created by Jeremy B.
*/
public abstract class TextViewListener implements TextWatcher {
/**
* Unchanged sequence which is placed before the updated sequence.
*/
private String _before;
/**
* Updated sequence before the update.
*/
private String _old;
/**
* Updated sequence after the update.
*/
private String _new;
/**
* Unchanged sequence which is placed after the updated sequence.
*/
private String _after;
/**
* Indicates when changes are made from within the listener, should be omitted.
*/
private boolean _ignore = false;
@Override
public void beforeTextChanged(CharSequence sequence, int start, int count, int after) {
_before = sequence.subSequence(0,start).toString();
_old = sequence.subSequence(start, start+count).toString();
_after = sequence.subSequence(start+count, sequence.length()).toString();
}
@Override
public void onTextChanged(CharSequence sequence, int start, int before, int count) {
_new = sequence.subSequence(start, start+count).toString();
}
@Override
public void afterTextChanged(Editable sequence) {
if (_ignore)
return;
onTextChanged(_before, _old, _new, _after);
}
/**
* Triggered method when the text in the text view has changed.
* <br/>
* You can apply changes to the text view from this method
* with the condition to call {@link #startUpdates()} before any update,
* and to call {@link #endUpdates()} after them.
*
* @param before Unchanged part of the text placed before the updated part.
* @param old Old updated part of the text.
* @param aNew New updated part of the text?
* @param after Unchanged part of the text placed after the updated part.
*/
protected abstract void onTextChanged(String before, String old, String aNew, String after);
/**
* Call this method when you start to update the text view, so it stops listening to it and then prevent an infinite loop.
* @see #endUpdates()
*/
protected void startUpdates(){
_ignore = true;
}
/**
* Call this method when you finished to update the text view in order to restart to listen to it.
* @see #startUpdates()
*/
protected void endUpdates(){
_ignore = false;
}
}
Example:
myEditText.addTextChangedListener(new TextViewListener() {
@Override
protected void onTextChanged(String before, String old, String aNew, String after) {
// intuitive use of parameters
String completeOldText = before + old + after;
String completeNewText = before + aNew + after;
// update TextView
startUpdates(); // to prevent infinite loop.
myEditText.setText(myNewText);
endUpdates();
}
}
i believe all the major opensource JS engines (JavaScriptCore, SpiderMonkey, V8, and KJS) provide embedding APIs. The only one I am actually directly familiar with is JavaScriptCore (which is name of the JS engine the SquirrelFish lives in) which provides a pure C API. If memory serves (it's been a while since i used .NET) .NET has fairly good support for linking in C API's.
I'm honestly not sure what the API's for the other engines are like, but I do know that they all provide them.
That said, depending on your purposes JScript.NET may be best, as all of these other engines will require you to include them with your app, as JSC is the only one that actually ships with an OS, but that OS is MacOS :D
try
IF(@Trans_type = 'subscr_signup')
BEGIN
set @tmpType = 'premium'
END
ELSE iF(@Trans_type = 'subscr_cancel')
begin
set @tmpType = 'basic'
END
<input type="text" disabled="disabled" />
is the valid markup.<input type="text" disabled />
is valid and used by W3C on their samples.'&' --> '&'
'<' --> '<'
'>' --> '>'
I used this and it worked out well for me. If your directory is
"repo" and your project is "hello" copy the project there
cd /path/to/my/repo
Initialize your directory
git init
Stage the project
git add hello
commit the project
git commit
Add configurations using the email and username you are using in Bitbucket
git config --global user.email
git config --global user.name
Add comment to the project
git commit -m 'comment'
push the project now
git push origin master
Check out of the master
git checkout master
Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.
Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.
Well now will be different after angular 5:
{{ number | currency :'GBP':'symbol':'1.2-2' }}
I know the question is aimed at the direct escaping of the apostrophe character but I assume that usually this is going to be triggered by some sort of program providing the input.
What I have done universally in the scripts and programs I have worked with is to substitute it with a ` character when processing the formatting of the text being input.
Now I know that in some cases, the backtick character may in fact be part of what you might be trying to save (such as on a forum like this) but if you're simply saving text input from users it's a possible solution.
Going into the SQL database
$newval=~s/\'/`/g;
Then, when coming back out for display, filtered again like this:
$showval=~s/`/\'/g;
This example was when PERL/CGI is being used but it can apply to PHP and other bases as well. I have found it works well because I think it helps prevent possible injection attempts, because all ' are removed prior to attempting an insertion of a record.
Program prints ab
, goes back one character and prints si
overwriting the b
resulting asi
.
Carriage return returns the caret to the first column of the current line. That means the ha
will be printed over as
and the result is hai
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
This worked for me on my VM instance of Ubuntu.
hdfs dfs -copyToLocal [hadoop directory] [local directory]
Try this one with retina display
/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
/* Styles */
}
/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
/* Styles */
}
/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
/* Styles */
}
/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
/* Styles */
}
/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
/* Styles */
}
/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
/* Styles */
}
/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
/* Styles */
}
U cant try this
for (WordList i : words) {
words.get(words.indexOf(i));
}
Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.
you have to add fulltext index on specific fields you want to search.
ALTER TABLE news ADD FULLTEXT(headline, story);
where "news" is your table and "headline, story" fields you wont to enable for fulltext search
It's got a number of names. Most likely you've heard it as either Card Security Code (CSC) or Card Verification Value (CVV).
date +%H:%M
Would be easier, I think :). If you really wanted to chop off the seconds, you could have done
date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'
You cannot do it because you are already looping on it.
Inorder to avoid this situation use Iterator,which guarentees you to remove the element from list safely ...
List<Object> objs;
Iterator<Object> i = objs.iterator();
while (i.hasNext()) {
Object o = i.next();
//some condition
i.remove();
}
I shared my experience of using two LEFT JOINS in a single SQL query.
I have 3 tables:
Table 1) Patient consists columns PatientID, PatientName
Table 2) Appointment consists columns AppointmentID, AppointmentDateTime, PatientID, DoctorID
Table 3) Doctor consists columns DoctorID, DoctorName
Query:
SELECT Patient.patientname, AppointmentDateTime, Doctor.doctorname
FROM Appointment
LEFT JOIN Doctor ON Appointment.doctorid = Doctor.doctorId //have doctorId column common
LEFT JOIN Patient ON Appointment.PatientId = Patient.PatientId //have patientid column common
WHERE Doctor.Doctorname LIKE 'varun%' // setting doctor name by using LIKE
AND Appointment.AppointmentDateTime BETWEEN '1/16/2001' AND '9/9/2014' //comparison b/w dates
ORDER BY AppointmentDateTime ASC; // getting data as ascending order
I wrote the solution to get date format like "mm/dd/yy" (under my name "VARUN TEJ REDDY")
Calling the isHTML()
method after the instance Body
property (I mean $mail->Body
) has been set solved the problem for me:
$mail->Subject = $Subject;
$mail->Body = $Body;
$mail->IsHTML(true); // <=== call IsHTML() after $mail->Body has been set.
I've only ever used Class.cast(Object)
to avoid warnings in "generics land". I often see methods doing things like this:
@SuppressWarnings("unchecked")
<T> T doSomething() {
Object o;
// snip
return (T) o;
}
It's often best to replace it by:
<T> T doSomething(Class<T> cls) {
Object o;
// snip
return cls.cast(o);
}
That's the only use case for Class.cast(Object)
I've ever come across.
Regarding compiler warnings: I suspect that Class.cast(Object)
isn't special to the compiler. It could be optimized when used statically (i.e. Foo.class.cast(o)
rather than cls.cast(o)
) but I've never seen anybody using it - which makes the effort of building this optimization into the compiler somewhat worthless.
Textarea resize control is available via the CSS3 resize property:
textarea { resize: both; } /* none|horizontal|vertical|both */
textarea.resize-vertical{ resize: vertical; }
textarea.resize-none { resize: none; }
Allowable values self-explanatory: none
(disables textarea resizing), both
, vertical
and horizontal
.
Notice that in Chrome, Firefox and Safari the default is both
.
If you want to constrain the width and height of the textarea element, that's not a problem: these browsers also respect max-height
, max-width
, min-height
, and min-width
CSS properties to provide resizing within certain proportions.
Code example:
#textarea-wrapper {_x000D_
padding: 10px;_x000D_
background-color: #f4f4f4;_x000D_
width: 300px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea {_x000D_
min-height:50px;_x000D_
max-height:120px;_x000D_
width: 290px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea.vertical { _x000D_
resize: vertical;_x000D_
}
_x000D_
<div id="textarea-wrapper">_x000D_
<label for="resize-default">Textarea (default):</label>_x000D_
<textarea name="resize-default" id="resize-default"></textarea>_x000D_
_x000D_
<label for="resize-vertical">Textarea (vertical):</label>_x000D_
<textarea name="resize-vertical" id="resize-vertical" class="vertical">Notice this allows only vertical resize!</textarea>_x000D_
</div>
_x000D_
you need to execute two queries:
One - to add the default value to the column required
ALTER TABLE 'Table_Name` ADD DEFAULT 'value' FOR 'Column_Name'
i want add default value to Column IsDeleted as below:
Example: ALTER TABLE [dbo].[Employees] ADD Default 0 for IsDeleted
Two - to alter the column value nullable to not null
ALTER TABLE 'table_name' ALTER COLUMN 'column_name' 'data_type' NOT NULL
i want to make the column IsDeleted as not null
ALTER TABLE [dbo].[Employees] Alter Column IsDeleted BIT NOT NULL
Here is code to do it directly with JavaScript. But, as previously mentioned, you'd be much better off with a JavaScript library. My favorite is jQuery.
In the case below, an ASPX page (that's servicing as a poor man's REST service) is being called to return a JavaScript JSON object.
var xmlHttp = null;
function GetCustomerInfo()
{
var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open( "GET", Url, true );
xmlHttp.send( null );
}
function ProcessRequest()
{
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
if ( xmlHttp.responseText == "Not found" )
{
document.getElementById( "TextBoxCustomerName" ).value = "Not found";
document.getElementById( "TextBoxCustomerAddress" ).value = "";
}
else
{
var info = eval ( "(" + xmlHttp.responseText + ")" );
// No parsing necessary with JSON!
document.getElementById( "TextBoxCustomerName" ).value = info.jsonData[ 0 ].cmname;
document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
}
}
}
Like the answer of @memical.
However I found some improvements. You can use the jQuery height()
function. But be aware of padding-top and padding-bottom pixels. Otherwise your textarea will grow too fast.
$(document).ready(function() {
$textarea = $("#my-textarea");
// There is some diff between scrollheight and height:
// padding-top and padding-bottom
var diff = $textarea.prop("scrollHeight") - $textarea.height();
$textarea.live("keyup", function() {
var height = $textarea.prop("scrollHeight") - diff;
$textarea.height(height);
});
});
Looking for answers to this problem, I stumbled upon this link
It seems that Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The @GeneratedValue
annotation is only used in conjunction with @Id
to create auto-numbers.
The @GeneratedValue
annotation just tells Hibernate that the database is generating this value itself.
The solution (or work-around) suggested in that forum is to create a separate entity with a generated Id, something like this:
@Entity public class GeneralSequenceNumber { @Id @GeneratedValue(...) private Long number; } @Entity public class MyEntity { @Id .. private Long id; @OneToOne(...) private GeneralSequnceNumber myVal; }
.circle {_x000D_
height: 20rem;_x000D_
width: 20rem;_x000D_
border-radius: 50%;_x000D_
background-color: #EF6A6A;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
EDIT: If the container is not the body CSS Tricks covers all of your options in Fitting Text to a Container.
If the container is the body, what you are looking for is Viewport-percentage lengths:
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist.
The values are:
vw
(% of the viewport width)vh
(% of the viewport height)vi
(1% of the viewport size in the direction of the root element's inline axis)vb
(1% of the viewport size in the direction of the root element's block axis)vmin
(the smaller of vw
or vh
)vmax
(the larger or vw
or vh
)1 v* is equal to 1% of the initial containing block.
Using it looks like this:
p {
font-size: 4vw;
}
As you can see, when the viewport width increases, so do the font-size
, without needing to use media queries.
These values are a sizing unit, just like px
or em
, so they can be used to size other elements as well, such as width, margin, or padding.
Browser support is pretty good, but you'll likely need a fallback, such as:
p {
font-size: 16px;
font-size: 4vw;
}
Check out the support statistics: http://caniuse.com/#feat=viewport-units.
Also, check out CSS-Tricks for a broader look: Viewport Sized Typography
Here's a nice article about setting minimum/maximum sizes and exercising a bit more control over the sizes: Precise control over responsive typography
And here's an article about setting your size using calc() so that the text fills the viewport: http://codepen.io/CrocoDillon/pen/fBJxu
Also, please view this article, which uses a technique dubbed 'molten leading' to adjust the line-height as well. Molten Leading in CSS
My understanding of the Android application framework is that this is specifically not permitted. An application is closed automatically when it contains no more current activities. Trying to create a "kill" button is apparently contrary to the intended design of the application system.
To get the sort of effect you want, you could initiate your various activities with startActivityForResult(), and have the exit button send back a result which tells the parent activity to finish(). That activity could then send the same result as part of its onDestroy(), which would cascade back to the main activity and result in no running activities, which should cause the app to close.
In May 2017 Google launched the official Google Maps URLs documentation. The Google Maps URLs introduces universal cross-platform syntax that you can use in your applications.
Have a look at the following document:
https://developers.google.com/maps/documentation/urls/guide
You can use URLs in search, directions, map and street view modes.
For example, to show the marker at specified position you can use the following URL:
https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324
For further details please read aforementioned documentation.
You can also file feature requests for this API in Google issue tracker.
Hope this helps!
Set the href
attribute with
$(selector).attr('href', 'url_goes_here');
and read it using
$(selector).attr('href');
Where "selector" is any valid jQuery selector for your <a>
element (".myClass" or "#myId" to name the most simple ones).
Hope this helps !
You seem to misunderstand the box model - in CSS you provide points for the top and left and then width and height - these are all that are needed for a box to be placed with exact measurements.
The width
property is what your C-D
is, but it is also what A-B
is. If you omit it, the div will not have a defined width and the width will be defined by its contents.
Update (following the comments on the question:
Add a border-bottom-style: none;
to your CSS to remove this style from the bottom only.
Faced with this issue when determining an environment, I came up with the following one-liner:
string ActiveEnvironment = localEnv.Contains("LIVE") ? "LIVE" : (localEnv.Contains("TEST") ? "TEST" : (localEnv.Contains("LOCAL") ? "LOCAL" : null));
That way, if it can't find anything in the provided string that matches the "switch" conditions, it gives up and returns null
. This could easily be amended to return a different value.
It's not strictly a switch, more a cascading if statement but it's neat and it worked.
If you are on a Mac, then Homebrew is the way to install stuff.
It seems that version 8 is no longer the most recent, so it isnt available using the default brew cask install java
.
Instead I managed by doing the following:
brew install homebrew/cask-versions/
If this fails, just try the next one directly:
brew install homebrew/cask-versions/adoptopenjdk8
Test with brew cask list
or java -version
package ExpressionCalculator.expressioncalculator;
import java.text.DecimalFormat;
import java.util.Scanner;
public class ExpressionCalculator {
private static String addSpaces(String exp){
//Add space padding to operands.
//https://regex101.com/r/sJ9gM7/73
exp = exp.replaceAll("(?<=[0-9()])[\\/]", " / ");
exp = exp.replaceAll("(?<=[0-9()])[\\^]", " ^ ");
exp = exp.replaceAll("(?<=[0-9()])[\\*]", " * ");
exp = exp.replaceAll("(?<=[0-9()])[+]", " + ");
exp = exp.replaceAll("(?<=[0-9()])[-]", " - ");
//Keep replacing double spaces with single spaces until your string is properly formatted
/*while(exp.indexOf(" ") != -1){
exp = exp.replace(" ", " ");
}*/
exp = exp.replaceAll(" {2,}", " ");
return exp;
}
public static Double evaluate(String expr){
DecimalFormat df = new DecimalFormat("#.####");
//Format the expression properly before performing operations
String expression = addSpaces(expr);
try {
//We will evaluate using rule BDMAS, i.e. brackets, division, power, multiplication, addition and
//subtraction will be processed in following order
int indexClose = expression.indexOf(")");
int indexOpen = -1;
if (indexClose != -1) {
String substring = expression.substring(0, indexClose);
indexOpen = substring.lastIndexOf("(");
substring = substring.substring(indexOpen + 1).trim();
if(indexOpen != -1 && indexClose != -1) {
Double result = evaluate(substring);
expression = expression.substring(0, indexOpen).trim() + " " + result + " " + expression.substring(indexClose + 1).trim();
return evaluate(expression.trim());
}
}
String operation = "";
if(expression.indexOf(" / ") != -1){
operation = "/";
}else if(expression.indexOf(" ^ ") != -1){
operation = "^";
} else if(expression.indexOf(" * ") != -1){
operation = "*";
} else if(expression.indexOf(" + ") != -1){
operation = "+";
} else if(expression.indexOf(" - ") != -1){ //Avoid negative numbers
operation = "-";
} else{
return Double.parseDouble(expression);
}
int index = expression.indexOf(operation);
if(index != -1){
indexOpen = expression.lastIndexOf(" ", index - 2);
indexOpen = (indexOpen == -1)?0:indexOpen;
indexClose = expression.indexOf(" ", index + 2);
indexClose = (indexClose == -1)?expression.length():indexClose;
if(indexOpen != -1 && indexClose != -1) {
Double lhs = Double.parseDouble(expression.substring(indexOpen, index));
Double rhs = Double.parseDouble(expression.substring(index + 2, indexClose));
Double result = null;
switch (operation){
case "/":
//Prevent divide by 0 exception.
if(rhs == 0){
return null;
}
result = lhs / rhs;
break;
case "^":
result = Math.pow(lhs, rhs);
break;
case "*":
result = lhs * rhs;
break;
case "-":
result = lhs - rhs;
break;
case "+":
result = lhs + rhs;
break;
default:
break;
}
if(indexClose == expression.length()){
expression = expression.substring(0, indexOpen) + " " + result + " " + expression.substring(indexClose);
}else{
expression = expression.substring(0, indexOpen) + " " + result + " " + expression.substring(indexClose + 1);
}
return Double.valueOf(df.format(evaluate(expression.trim())));
}
}
}catch(Exception exp){
exp.printStackTrace();
}
return 0.0;
}
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an Mathematical Expression to Evaluate: ");
String input = scanner.nextLine();
System.out.println(evaluate(input));
}
}
The problem is that System. currentTimeMillis();
returns the number of milliseconds from 1970-01-01T00:00:00Z, but new Date()
gives the current local time. Adding the ZONE_OFFSET and DST_OFFSET from the Calendar class gives you the time in UTC.
Calendar rightNow = Calendar.getInstance();
// offset to add since we're not UTC
long offset = rightNow.get(Calendar.ZONE_OFFSET) +
rightNow.get(Calendar.DST_OFFSET);
long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
(24 * 60 * 60 * 1000);
System.out.println(sinceMidnight + " milliseconds since midnight");
When you use jackson to map from string to your concrete class, especially if you work with generic type. then this issue may happen because of different class loader. i met it one time with below scenarior:
Project B depend on Library A
in Library A:
public class DocSearchResponse<T> {
private T data;
}
it has service to query data from external source, and use jackson to convert to concrete class
public class ServiceA<T>{
@Autowired
private ObjectMapper mapper;
@Autowired
private ClientDocSearch searchClient;
public DocSearchResponse<T> query(Criteria criteria){
String resultInString = searchClient.search(criteria);
return convertJson(resultInString)
}
}
public DocSearchResponse<T> convertJson(String result){
return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
}
}
in Project B:
public class Account{
private String name;
//come with other attributes
}
and i use ServiceA from library to make query and as well convert data
public class ServiceAImpl extends ServiceA<Account> {
}
and make use of that
public class MakingAccountService {
@Autowired
private ServiceA service;
public void execute(Criteria criteria){
DocSearchResponse<Account> result = service.query(criteria);
Account acc = result.getData(); // java.util.LinkedHashMap cannot be cast to com.testing.models.Account
}
}
it happen because from classloader of LibraryA, jackson can not load Account class, then just override method convertJson
in Project B to let jackson do its job
public class ServiceAImpl extends ServiceA<Account> {
@Override
public DocSearchResponse<T> convertJson(String result){
return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
}
}
}
regexObject.test( String ) is faster than string.match( RegExp ).
The MDN site describes the format for document.cookie, and has an example regex to grab a cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
). Based on that, I'd go for this:
/^(.*;)?\s*cookie1\s*=/.test(document.cookie);
The question seems to ask for a solution which returns false when the cookie is set, but empty. In that case:
/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);
Tests
function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));
Just did the test and it works with toEqual
please find my test:
describe('toEqual', function() {
it('passes if arrays are equal', function() {
var arr = [1, 2, 3];
expect(arr).toEqual([1, 2, 3]);
});
});
Just for information:
toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the other hand, makes sure that they're the exact same object.
If your set
command supports the /p
switch, then you can pipe input that way.
set /p VAR1=<test.txt
set /? |find "/P"
The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
This has the added benefit of working for un-registered file types (which the accepted answer does not).
May be you initialize pDialog globally, Then remove it and intialize your view or dialog locally.I have same issue, I have done this and my issue is resolved. Hope it will work for u.
You can put the condition after the WHEN
clause, like so:
SELECT
CASE
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
WHEN DS.DES = 'N' THEN 'Early Term'
WHEN DS.DES = 'Y' THEN 'Complete'
END
FROM
....
Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...
Html code
<div id="coloredBy">
Colored By Santa
</div>
javascript code
document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff
I think this is very easy to use
Change the h1.textContent
to h1.innerHTML
and use <br>
to go to the new line.
Without Using Arrays, you can store the Characters and concatenate them in reverse order.
public static String reverseString(String inpt) {
String sb = "";
for(int i = inpt.length()-1; i>=0; i--) {
sb = sb.concat(""+inpt.charAt(i));
}
return sb;
}
I didn't apply paging on my gridview and it extends to more than 600 records (with checkbox, buttons, etc.) and the value of 2001 didn't work. You may increase the value, say 10000 and test.
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="10000" />
</appSettings>
I'm not exactly sure what's causing this. You can try looking in your socket.py (mine is a different version, so line numbers from the trace don't match, and I'm afraid some other details might not match as well).
Anyway, it seems like a good practice to put your url fetching code in a try: ... except: ...
block, and handle this with a short pause and a retry. The URL you're trying to fetch may be down, or too loaded, and that's stuff you'll only be able to handle in with a retry anyway.
You can't. A redirect requires a webserver to accept the first request and send back the redirect. The "hosts" file just lets you set your own DNS records.
I prefer using Symfony for this. Their libraries are pretty nice.
Use the The DomCrawler Component
Example:
$browser = new HttpBrowser(HttpClient::create());
$crawler = $browser->request('GET', 'example.com');
$class = $crawler->filter('.class')->first();
I found the following command to run from command line:
vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt
List<string> values =new list<string>();
foreach(ListItem Item in ChkList.Item)
{
if(Item.Selected)
values.Add(item.Value);
}
UIButton
inherits from UIControl
. That has all of the methods to add/remove actions: UIControl Class Reference. Look at the section "Preparing and Sending Action Messages", which covers – sendAction:to:forEvent:
and – addTarget:action:forControlEvents:
.
DIM stands for Declaration In Memory DIM x As New Integer creates a space in memory where the variable x is stored
stopPropagation
will prevent any parent handlers from being executed stopImmediatePropagation
will prevent any parent handlers and also any other handlers from executing
Quick example from the jquery documentation:
$("p").click(function(event) {_x000D_
event.stopImmediatePropagation();_x000D_
});_x000D_
_x000D_
$("p").click(function(event) {_x000D_
// This function won't be executed_x000D_
$(this).css("background-color", "#f00");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>example</p>
_x000D_
Note that the order of the event binding is important here!
$("p").click(function(event) {_x000D_
// This function will now trigger_x000D_
$(this).css("background-color", "#f00");_x000D_
});_x000D_
_x000D_
$("p").click(function(event) {_x000D_
event.stopImmediatePropagation();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>example</p>
_x000D_
Especially for the older Git versions, most of the suggestions won't work that well. If that's the case, I'd put a separate .gitignore in the directory where I want the content to be included regardless of other settings and allow there what is needed.
For example: /.gitignore
# ignore all .dll files
*.dll
/dependency_files/.gitignore
# include everything
!*
So everything in /dependency_files (even .dll files) are included just fine.
Following is working for me... put all of your IPs you want to telnet in IP_sheet.txt
while true
read a
do
{
sleep 3
echo df -kh
sleep 3
echo exit
} | telnet $a
done<IP_sheet.txt
It is really easy to write text on a canvas. It was not clear if you want someone to enter text in the HTML page and then have that text appear on the canvas, or if you were going to use JavaScript to write the information to the screen.
The following code will write some text in different fonts and formats to your canvas. You can modify this as you wish to test other aspects of writing onto a canvas.
<canvas id="YourCanvasNameHere" width="500" height="500">Canvas not supported</canvas>
var c = document.getElementById('YourCanvasNameHere');
var context = c.getContext('2d'); //returns drawing functions to allow the user to draw on the canvas with graphic tools.
You can either place the canvas ID tag in the HTML and then reference the name or you can create the canvas in the JavaScript code. I think that for the most part I see the <canvas>
tag in the HTML code and on occasion see it created dynamically in the JavaScript code itself.
Code:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.font = 'bold 10pt Calibri';
context.fillText('Hello World!', 150, 100);
context.font = 'italic 40pt Times Roman';
context.fillStyle = 'blue';
context.fillText('Hello World!', 200, 150);
context.font = '60pt Calibri';
context.lineWidth = 4;
context.strokeStyle = 'blue';
context.strokeText('Hello World!', 70, 70);
As far as I know that only works in Internet Explorer.
See also Dynamic Tools - JavaScript Copy To Clipboard, but it requires the user to change the configuration first and even then it doesn't seems to work.
You've returned a pointer to a local variable. That's bad even if threads aren't involved.
The usual way to do this, when the thread that starts is the same thread that joins, would be to pass a pointer to an int, in a location managed by the caller, as the 4th parameter of pthread_create. This then becomes the (only) parameter to the thread's entry-point. You can (if you like) use the thread exit value to indicate success:
#include <pthread.h>
#include <stdio.h>
int something_worked(void) {
/* thread operation might fail, so here's a silly example */
void *p = malloc(10);
free(p);
return p ? 1 : 0;
}
void *myThread(void *result)
{
if (something_worked()) {
*((int*)result) = 42;
pthread_exit(result);
} else {
pthread_exit(0);
}
}
int main()
{
pthread_t tid;
void *status = 0;
int result;
pthread_create(&tid, NULL, myThread, &result);
pthread_join(tid, &status);
if (status != 0) {
printf("%d\n",result);
} else {
printf("thread failed\n");
}
return 0;
}
If you absolutely have to use the thread exit value for a structure, then you'll have to dynamically allocate it (and make sure that whoever joins the thread frees it). That's not ideal, though.
Java command line parameters
-Xms: initial heap size
-Xmx: Maximum heap size
if you are using Tomcat. Update CATALINA_OPTS
environment variable
export CATALINA_OPTS=-Xms16m -Xmx256m;
Service: startservice can cause side affects,best way to use messenger and pass data.
private CallBackHandler mServiceHandler= new CallBackHandler(this);
private Messenger mServiceMessenger=null;
//flag with which the activity sends the data to service
private static final int DO_SOMETHING=1;
private static class CallBackHandler extends android.os.Handler {
private final WeakReference<Service> mService;
public CallBackHandler(Service service) {
mService= new WeakReference<Service>(service);
}
public void handleMessage(Message msg) {
//Log.d("CallBackHandler","Msg::"+msg);
if(DO_SOMETHING==msg.arg1)
mSoftKeyService.get().dosomthing()
}
}
Activity:Get Messenger from Intent fill it pass data and pass the message back to service
private Messenger mServiceMessenger;
@Override
protected void onCreate(Bundle savedInstanceState) {
mServiceMessenger = (Messenger)extras.getParcelable("myHandler");
}
private void sendDatatoService(String data){
Intent serviceIntent= new
Intent(BaseActivity.this,Service.class);
Message msg = Message.obtain();
msg.obj =data;
msg.arg1=Service.DO_SOMETHING;
mServiceMessenger.send(msg);
}
This means that you are doing a foreach on something that is not an array.
Check out all your foreach statements, and look if the thing before the as
, to make sure it is actually an array. Use var_dump
to dump it.
Then fix the one where it isn't an array.
How to reproduce this error:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //the warning happens on this line.
print "ok";
}
?>
Make sure $skipper
is an array.
If nothing worked for you, make sure the file is not open in another program. I was trying to import an xlsx file and Excel was blocking me from doing so.
This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage
public void checkAlert() {
try {
WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (Exception e) {
//exception handling
}
}
do you work with a 3d tool such as maya? for maya you can look at http://www.inka3d.com
Easier still you can just do
for i in {00001..99999}; do
echo $i
done
I used some of the solutions indicated above plus solutions from other postings to come up with a working solution for a dynamic table containing input fields. I'm doing this because it might help someone who finds this thread after searching for the same things that led me to it, and also because the accepted answer (and associated jsfiddle) doesn't actually work! That is, it doesn't index the table rows correctly after a number of inserts/deletes. The key issue is how to uniquely index the dynamic row data, which is possible with a bit of jquery:
<form id=frmLines>
<table id=tabLines>
<tr>
<td>img src='/some/suitable/graphic' onclick='removeLine(this);'/></td>
<td><input type='text' name='field1' /></td>
<td><input type='text' name='field2' /></td>
<td><input type='text' name='field3' /></td>
</tr>
<tr>
<td><img src='/some/suitable/graphic' onclick='addLine();' /></td>
<td colspan=3> </td>
</tr>
</table>
</form>
Note the form and table have id's for direct DOM referencing, but you can't use id's on the input fields as to make them unique you'd need to introduce an index which would massively complicate the code - and its easy enough to access them by name when the form is processed (see below)
Then the javascript to control adding and removing lines is like this:
function addLine() {
var tabLines = document.getElementById("tabLines");
var tabLinesRow = tabLines.insertRow(tabLines.rows.length-1);
var col1html = "<img src='/some/suitable/graphic' onclick='removeLine(this);'>";
var col2html = "<input type='text' name='field1' />";
var col3html = "<input type='text' name='field2' />";
var col4html = "<input type='text' name='field3' />";
var col1 = tabLinesRow.insertCell(0); col1.innerHTML=col1html;
var col2 = tabLinesRow.insertCell(1); col2.innerHTML=col2html;
var col3 = tabLinesRow.insertCell(2); col3.innerHTML=col3html;
var col4 = tabLinesRow.insertCell(3); col4.innerHTML=col4html;
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
Then the final part of the jigsaw - the javascript to process the form data when its submitted. The key jquery function here is .eq() - which allows you to access the field names in the order they appear in the form - i.e. in table row order.
var frmData = {}; // an object to contain all form data
var arrLines = new Array(); // array to contain the dynamic lines
var tabLines = document.getElementById("tabLines").rows.length-1;
for (i=0;i<tabLines;i++) {
arrLines[i] = {};
arrLines[i]['no'] = i+1;
arrLines[i]['field1'] = $("#frmLines input[name=field1]").eq(i).val();
arrLines[i]['field2'] = $("#frmLines input[name=field2]").eq(i).val();
arrLines[i]['field3'] = $("#frmLines input[name=field3]").eq(i).val();
}
frmData['lines'] = arrLines;
frmData['another_field'] = $('#frmLines input[name=another_field]").val();
var jsonData = JSON.stringify(frmData);
// lines of data now in a JSON structure as indexed array
// (plus other fields in the JSON as required)
// ready to post via ajax etc
I hope this helps someone, either directly or indirectly. There are a couple of subtle techniques being used which aren't that complicated but took me 3-4 hours to piece together.
When we used to work in MSSQL 2000, we did what we called the "triple-flip":
EDITED
DECLARE @InnerPageSize int
DECLARE @OuterPageSize int
DECLARE @Count int
SELECT @Count = COUNT(<column>) FROM <TABLE>
SET @InnerPageSize = @PageNum * @PageSize
SET @OuterPageSize = @Count - ((@PageNum - 1) * @PageSize)
IF (@OuterPageSize < 0)
SET @OuterPageSize = 0
ELSE IF (@OuterPageSize > @PageSize)
SET @OuterPageSize = @PageSize
DECLARE @sql NVARCHAR(8000)
SET @sql = 'SELECT * FROM
(
SELECT TOP ' + CAST(@OuterPageSize AS nvarchar(5)) + ' * FROM
(
SELECT TOP ' + CAST(@InnerPageSize AS nvarchar(5)) + ' * FROM <TABLE> ORDER BY <column> ASC
) AS t1 ORDER BY <column> DESC
) AS t2 ORDER BY <column> ASC'
PRINT @sql
EXECUTE sp_executesql @sql
It wasn't elegant, and it wasn't fast, but it worked.
Check this source code out. All commented code – used to create a console in a Windows app. Uncommented – to hide the console in a console app. From here. (Previously here.) Project reg2run
.
// Copyright (C) 2005-2015 Alexander Batishchev (abatishchev at gmail.com)
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Reg2Run
{
static class ManualConsole
{
#region DllImport
/*
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();
*/
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
/*
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)]string fileName, [MarshalAs(UnmanagedType.I4)]int desiredAccess, [MarshalAs(UnmanagedType.I4)]int shareMode, IntPtr securityAttributes, [MarshalAs(UnmanagedType.I4)]int creationDisposition, [MarshalAs(UnmanagedType.I4)]int flagsAndAttributes, IntPtr templateFile);
*/
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern IntPtr GetStdHandle([MarshalAs(UnmanagedType.I4)]int nStdHandle);
/*
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetStdHandle(int nStdHandle, IntPtr handle);
*/
#endregion
#region Methods
/*
public static void Create()
{
var ptr = GetStdHandle(-11);
if (!AllocConsole())
{
throw new Win32Exception("AllocConsole");
}
ptr = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (!SetStdHandle(-11, ptr))
{
throw new Win32Exception("SetStdHandle");
}
var newOut = new StreamWriter(Console.OpenStandardOutput());
newOut.AutoFlush = true;
Console.SetOut(newOut);
Console.SetError(newOut);
}
*/
public static void Hide()
{
var ptr = GetStdHandle(-11);
if (!CloseHandle(ptr))
{
throw new Win32Exception();
}
ptr = IntPtr.Zero;
if (!FreeConsole())
{
throw new Win32Exception();
}
}
#endregion
}
}
Well the above answers have give a good explanations to half of the question. For the other half.
Why don't just hide the scroll bar itself. This way it will look more appealing as most of the people ( including me ) hate the scroll bar. You can use this code
::-webkit-scrollbar {
width: 0px; /* Remove scrollbar space */
background: transparent; /* Optional: just make scrollbar invisible */
}
You are doing it right; every time you need to add a row, simply so new TableRow()
, etc. It might be easier for you to inflate
the new row from XML
though.
The method based on list comprehension and groupby
- Which stores all the split dataframe in list variable and can be accessed using the index.
Example
ans = [pd.DataFrame(y) for x, y in DF.groupby('column_name', as_index=False)]
ans[0]
ans[0].column_name
Here are my findings. I also faced this problem today's morning. I just added my current user to application pool on which application was running.
Steps:
Open IIS
Click on application pool
Select your application pool on which you are getting problem
Right Click -> advanced settings
Click on three dot icon beside the identiy
Now select custom account
Give your PC user name and Password
Save
Refresh your application.. and it will start working. There was some security issue for accessing dll.
Your original example works just fine for me:
<html>
<head>
</head>
<body>
<script>
var widthRange = new Array();
widthRange[46] = { sel:46, min:0, max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };
var i = 1;
for (var key in widthRange)
{
document.write("Key #" + i + " = " + key + "; min/max = " + widthRange[key].min + "/" + widthRange[key].max + "<br />");
i++;
}
</script>
</html>
Results in the browser (Firefox 3.6.2 on Windows XP):
Key #1 = 46; min/max = 0/52
Key #2 = 66; min/max = 52/70
Key #3 = 90; min/max = 70/94
A (partial) practical work-around is to put things into a throw-away function.
Pasting
x = 1
x += 1
print(x)
results in
>>> x = 1
x += 1
print(x)
File "<stdin>", line 1
x += 1
print(x)
^
SyntaxError: multiple statements found while compiling a single statement
>>>
However, pasting
def abc():
x = 1
x += 1
print(x)
works:
>>> def abc():
x = 1
x += 1
print(x)
>>> abc()
2
>>>
Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython
/ jupyter qtconsole
is probably the next simplest option.
"What's the use of using join()?" you say. Really, it's the same answer as "what's the use of closing files, since python and the OS will close my file for me when my program exits?".
It's simply a matter of good programming. You should join() your threads at the point in the code that the thread should not be running anymore, either because you positively have to ensure the thread is not running to interfere with your own code, or that you want to behave correctly in a larger system.
You might say "I don't want my code to delay giving an answer" just because of the additional time that the join() might require. This may be perfectly valid in some scenarios, but you now need to take into account that your code is "leaving cruft around for python and the OS to clean up". If you do this for performance reasons, I strongly encourage you to document that behavior. This is especially true if you're building a library/package that others are expected to utilize.
There's no reason to not join(), other than performance reasons, and I would argue that your code does not need to perform that well.
Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this
value.
In the Laravel 6 application the make:auth
command no longer exists.
Laravel UI is a new first-party package that extracts the UI portion of a Laravel project into a separate laravel/ui package. The separate package enables the Laravel team to iterate on the UI package separately from the main Laravel codebase.
You can install the laravel/ui
package via composer:
composer require laravel/ui
ui:auth
CommandBesides the new ui command, the laravel/ui
package comes with another command for generating the auth scaffolding:
php artisan ui:auth
If you run the ui:auth
command, it will generate the auth routes, a HomeController, auth views, and a app.blade.php layout file.
If you want to generate the views alone, type the following command instead:
php artisan ui:auth --views
If you want to generate the auth scaffolding at the same time:
php artisan ui vue --auth
php artisan ui react --auth
php artisan ui vue --auth
command will create all of the views you need for authentication and place them in the resources/views/auth
directory
The ui
command will also create a resources/views/layouts
directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.
More detail follow. laravel-news & documentation
composer require laravel/ui
php artisan ui:auth
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
In my scenario I had a slightly different message, where the line and position were not zero.
E. Path 'job[0].name', line 1, position 12.
This was the top Google answer for the message I quoted.
This came about because I had called a program from the Windows command line, passing JSON as a parameter.
When I reviewed the args in my program, all the double quotes got stripped. You have to reconstitute them.
I posted a solution here. Though it could probably be enhanced with a Regex.
Try this , there is no need to set its a CLOB
public static void main(String[] args)
{
try{
System.out.println("Opening db");
Class.forName("oracle.jdbc.driver.OracleDriver");
if(con==null)
con=DriverManager.getConnection("jdbc:oracle:thin:@192.9.200.103:1521: orcl","sas","sas");
if(stmt==null)
stmt=con.createStatement();
int res=9;
String usersSql = "{call Esme_Insertsmscdata(?,?,?,?,?)}";
CallableStatement stmt = con.prepareCall(usersSql);
// THIS THE CLOB DATA
stmt.setString(1,"SS¶5268771¶00058711¶04192018¶SS¶5268771¶00058712¶04192018¶SS¶5268772¶00058713¶04192018¶SS¶5268772¶00058714¶04192018¶SS¶5268773¶00058715¶04192018¶SS¶5268773¶00058716¶04192018¶SS¶5268774¶00058717¶04192018¶SS¶5268774¶00058718¶04192018¶SS¶5268775¶00058719¶04192018¶SS¶5268775¶00058720¶04192018¶");
stmt.setString(2, "bcvbcvb");
stmt.setString(3, String.valueOf("4522"));
stmt.setString(4, "42.25.632.25");
stmt.registerOutParameter(5,OracleTypes.NUMBER);
stmt.execute();
res=stmt.getInt(5);
stmt.close();
System.out.println(res);
}
catch(Exception e)
{
try
{
con.close();
} catch (SQLException e1) {
}
}
}
}
String.format("%1$,.2f", myDouble);
String.format
automatically uses the default locale.
With CSS3 we can easily adjust an image. But remember this does not change the image. It only displays the adjusted image.
See the following code for more details.
To make an image gray:
img {
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
}
To give a sepia look:
img {
-webkit-filter: sepia(100%);
-moz-filter: sepia(100%);
}
To adjust brightness:
img {
-webkit-filter: brightness(50%);
-moz-filter: brightness(50%);
}
To adjust contrast:
img {
-webkit-filter: contrast(200%);
-moz-filter: contrast(200%);
}
To Blur an image:
img {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
}
Here's a gist I discovered for real-time charts in ChartJS:
https://gist.github.com/arisetyo/5985848
ChartJS looks like it's simple to use and looks nice.
Also there's FusionCharts, a more sophisticated library for enterprise use, with a demo of real time here:
http://www.fusioncharts.com/explore/real-time-charts
EDIT I also started using Rickshaw for real time graphs and it's easy to use and pretty customizable: http://code.shutterstock.com/rickshaw/
Here is a Python function that splits a Pandas dataframe into train, validation, and test dataframes with stratified sampling. It performs this split by calling scikit-learn's function train_test_split()
twice.
import pandas as pd
from sklearn.model_selection import train_test_split
def split_stratified_into_train_val_test(df_input, stratify_colname='y',
frac_train=0.6, frac_val=0.15, frac_test=0.25,
random_state=None):
'''
Splits a Pandas dataframe into three subsets (train, val, and test)
following fractional ratios provided by the user, where each subset is
stratified by the values in a specific column (that is, each subset has
the same relative frequency of the values in the column). It performs this
splitting by running train_test_split() twice.
Parameters
----------
df_input : Pandas dataframe
Input dataframe to be split.
stratify_colname : str
The name of the column that will be used for stratification. Usually
this column would be for the label.
frac_train : float
frac_val : float
frac_test : float
The ratios with which the dataframe will be split into train, val, and
test data. The values should be expressed as float fractions and should
sum to 1.0.
random_state : int, None, or RandomStateInstance
Value to be passed to train_test_split().
Returns
-------
df_train, df_val, df_test :
Dataframes containing the three splits.
'''
if frac_train + frac_val + frac_test != 1.0:
raise ValueError('fractions %f, %f, %f do not add up to 1.0' % \
(frac_train, frac_val, frac_test))
if stratify_colname not in df_input.columns:
raise ValueError('%s is not a column in the dataframe' % (stratify_colname))
X = df_input # Contains all columns.
y = df_input[[stratify_colname]] # Dataframe of just the column on which to stratify.
# Split original dataframe into train and temp dataframes.
df_train, df_temp, y_train, y_temp = train_test_split(X,
y,
stratify=y,
test_size=(1.0 - frac_train),
random_state=random_state)
# Split the temp dataframe into val and test dataframes.
relative_frac_test = frac_test / (frac_val + frac_test)
df_val, df_test, y_val, y_test = train_test_split(df_temp,
y_temp,
stratify=y_temp,
test_size=relative_frac_test,
random_state=random_state)
assert len(df_input) == len(df_train) + len(df_val) + len(df_test)
return df_train, df_val, df_test
Below is a complete working example.
Consider a dataset that has a label upon which you want to perform the stratification. This label has its own distribution in the original dataset, say 75% foo
, 15% bar
and 10% baz
. Now let's split the dataset into train, validation, and test into subsets using a 60/20/20 ratio, where each split retains the same distribution of the labels. See the illustration below:
Here is the example dataset:
df = pd.DataFrame( { 'A': list(range(0, 100)),
'B': list(range(100, 0, -1)),
'label': ['foo'] * 75 + ['bar'] * 15 + ['baz'] * 10 } )
df.head()
# A B label
# 0 0 100 foo
# 1 1 99 foo
# 2 2 98 foo
# 3 3 97 foo
# 4 4 96 foo
df.shape
# (100, 3)
df.label.value_counts()
# foo 75
# bar 15
# baz 10
# Name: label, dtype: int64
Now, let's call the split_stratified_into_train_val_test()
function from above to get train, validation, and test dataframes following a 60/20/20 ratio.
df_train, df_val, df_test = \
split_stratified_into_train_val_test(df, stratify_colname='label', frac_train=0.60, frac_val=0.20, frac_test=0.20)
The three dataframes df_train
, df_val
, and df_test
contain all the original rows but their sizes will follow the above ratio.
df_train.shape
#(60, 3)
df_val.shape
#(20, 3)
df_test.shape
#(20, 3)
Further, each of the three splits will have the same distribution of the label, namely 75% foo
, 15% bar
and 10% baz
.
df_train.label.value_counts()
# foo 45
# bar 9
# baz 6
# Name: label, dtype: int64
df_val.label.value_counts()
# foo 15
# bar 3
# baz 2
# Name: label, dtype: int64
df_test.label.value_counts()
# foo 15
# bar 3
# baz 2
# Name: label, dtype: int64
You can also use Chocolatey.
Having it installed, just run:
choco install make
When it finishes, it is installed and available in Git for Bash / MinGW.
#some example data
set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))
#calculate mean, min and max for each x-value
library(plyr)
df2 <- ddply(df,.(x),function(df) c(mean=mean(df$y),min=min(df$y),max=max(df$y)))
#plot error bars
library(Hmisc)
with(df2,errbar(x,mean,max,min))
grid(nx=NA,ny=NULL)
Maybe too late :))) but there is another solution that you can find the key and value of structs and iterate over that
package main
import (
"fmt"
"reflect"
)
type person struct {
firsName string
lastName string
iceCream []string
}
func main() {
u := struct {
myMap map[int]int
mySlice []string
myPerson person
}{
myMap: map[int]int{1: 10, 2: 20},
mySlice: []string{"red", "green"},
myPerson: person{
firsName: "Esmaeil",
lastName: "Abedi",
iceCream: []string{"Vanilla", "chocolate"},
},
}
v := reflect.ValueOf(u)
for i := 0; i < v.NumField(); i++ {
fmt.Println(v.Type().Field(i).Name)
fmt.Println("\t", v.Field(i))
}
}
and there is no *panic* for v.Field(i)
To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.
I found a way:
This for JavaScript:
function callPHP(expression, objs, afterHandler) {
expression = expression.trim();
var si = expression.indexOf("(");
if (si == -1)
expression += "()";
else if (Object.keys(objs).length > 0) {
var sfrom = expression.substring(si + 1);
var se = sfrom.indexOf(")");
var result = sfrom.substring(0, se).trim();
if (result.length > 0) {
var params = result.split(",");
var theend = expression.substring(expression.length - sfrom.length + se);
expression = expression.substring(0, si + 1);
for (var i = 0; i < params.length; i++) {
var param = params[i].trim();
if (param in objs) {
var value = objs[param];
if (typeof value == "string")
value = "'" + value + "'";
if (typeof value != "undefined")
expression += value + ",";
}
}
expression = expression.substring(0, expression.length - 1) + theend;
}
}
var doc = document.location;
var phpFile = "URL of your PHP file";
var php =
"$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
"$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
"set_include_path($folder);include $fileName;" + expression + ";";
var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
$.ajax({
type: 'GET',
url: url,
complete: function(resp){
var response = resp.responseText;
afterHandler(response);
}
});
}
This for a PHP file which isn't your PHP file, but another, which path is written in url
variable of JS function callPHP
, and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:
<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
eval(trim($line, " ") . ";");
?>
So, your PHP code remain equals except return values, which will be echoed:
<?php
function add($a,$b){
$c=$a+$b;
echo $c;
}
function mult($a,$b){
$c=$a*$b;
echo $c;
}
function divide($a,$b){
$c=$a/$b;
echo $c;
}
?>
I suggest you to remember that jQuery is required:
Download it from Google CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
or from Microsoft CDN: "I prefer Google! :)"
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster! The choice is to you!
Now you finished! I just tell you how to use callPHP
function. This is the JavaScript to call PHP:
//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
'num1' : 1,
'num2' : 2
},
function(output) {
alert(output); //This to display the output of the PHP file.
});
It seems that your configuration is using the print
option for numpy.seterr
:
>>> import numpy as np
>>> np.array([1])/0 #'warn' mode
__main__:1: RuntimeWarning: divide by zero encountered in divide
array([0])
>>> np.seterr(all='print')
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'}
>>> np.array([1])/0 #'print' mode
Warning: divide by zero encountered in divide
array([0])
This means that the warning you see is not a real warning, but it's just some characters printed to stdout
(see the documentation for seterr
). If you want to catch it you can:
numpy.seterr(all='raise')
which will directly raise the exception. This however changes the behaviour of all the operations, so it's a pretty big change in behaviour.numpy.seterr(all='warn')
, which will transform the printed warning in a real warning and you'll be able to use the above solution to localize this change in behaviour.Once you actually have a warning, you can use the warnings
module to control how the warnings should be treated:
>>> import warnings
>>>
>>> warnings.filterwarnings('error')
>>>
>>> try:
... warnings.warn(Warning())
... except Warning:
... print 'Warning was raised as an exception!'
...
Warning was raised as an exception!
Read carefully the documentation for filterwarnings
since it allows you to filter only the warning you want and has other options. I'd also consider looking at catch_warnings
which is a context manager which automatically resets the original filterwarnings
function:
>>> import warnings
>>> with warnings.catch_warnings():
... warnings.filterwarnings('error')
... try:
... warnings.warn(Warning())
... except Warning: print 'Raised!'
...
Raised!
>>> try:
... warnings.warn(Warning())
... except Warning: print 'Not raised!'
...
__main__:2: Warning:
No. "In scope" variables are determined by the "scope chain", which is not accessible programmatically.
For detail (quite a lot of it), check out the ECMAScript (JavaScript) specification. Here's a link to the official page where you can download the canonical spec (a PDF), and here's one to the official, linkable HTML version.
Update based on your comment to Camsoft
The variables in scope for your event function are determined by where you define your event function, not how they call it. But, you may find useful information about what's available to your function via this
and arguments by doing something along the lines of what KennyTM pointed out (for (var propName in ____)
) since that will tell you what's available on various objects provided to you (this
and arguments; if you're not sure what arguments they give you, you can find out via the arguments
variable that's implicitly defined for every function).
So in addition to whatever's in-scope because of where you define your function, you can find out what else is available by other means by doing:
var n, arg, name;
alert("typeof this = " + typeof this);
for (name in this) {
alert("this[" + name + "]=" + this[name]);
}
for (n = 0; n < arguments.length; ++n) {
arg = arguments[n];
alert("typeof arguments[" + n + "] = " + typeof arg);
for (name in arg) {
alert("arguments[" + n + "][" + name + "]=" + arg[name]);
}
}
(You can expand on that to get more useful information.)
Instead of that, though, I'd probably use a debugger like Chrome's dev tools (even if you don't normally use Chrome for development) or Firebug (even if you don't normally use Firefox for development), or Dragonfly on Opera, or "F12 Developer Tools" on IE. And read through whatever JavaScript files they provide you. And beat them over the head for proper docs. :-)
In VS 2013, try to install the UPDATE 1(RC1) and the problem is resolved.
You can also add a middleware to add CORS headers, something like this would work:
/**
* Adds CORS headers to the response
*
* {@link https://en.wikipedia.org/wiki/Cross-origin_resource_sharing}
* {@link http://expressjs.com/en/4x/api.html#res.set}
* @param {object} request the Request object
* @param {object} response the Response object
* @param {function} next function to continue execution
* @returns {void}
* @example
* <code>
* const express = require('express');
* const corsHeaders = require('./middleware/cors-headers');
*
* const app = express();
* app.use(corsHeaders);
* </code>
*/
module.exports = (request, response, next) => {
// http://expressjs.com/en/4x/api.html#res.set
response.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE,GET,PATCH,POST,PUT',
'Access-Control-Allow-Headers': 'Content-Type,Authorization'
});
// intercept OPTIONS method
if(request.method === 'OPTIONS') {
response.send(200);
} else {
next();
}
};
var strDateValidate = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let firstDate = dateFormatter.date(from:lblStartTime.text!)
let secondDate = dateFormatter.date(from:lblEndTime.text!)
if firstDate?.compare(secondDate!) == .orderedSame || firstDate?.compare(secondDate!) == .orderedAscending {
print("Both dates are same or first is less than scecond")
strDateValidate = "yes"
}
else
{
//second date is bigger than first
strDateValidate = "no"
}
if strDateValidate == "no"
{
alertView(message: "Start date and end date for a booking must be equal or Start date must be smaller than the end date", controller: self)
}
use below code
server.mappath()
in asp.net
application.startuppath
in c# windows application
How about plain JavaScript? More about Array.prototype.filter()
.
var myArray = [{'id': '73', 'name': 'john'}, {'id': '45', 'name': 'Jass'}]_x000D_
_x000D_
var item73 = myArray.filter(function(item) {_x000D_
return item.id === '73';_x000D_
})[0];_x000D_
_x000D_
// even nicer with ES6 arrow functions:_x000D_
// var item73 = myArray.filter(i => i.id === '73')[0];_x000D_
_x000D_
console.log(item73); // {"id": "73", "name": "john"}
_x000D_
You can enable Jetifier
on your project, which will basically exchange the Android Support Library
dependencies in your project dependencies with AndroidX
-ones. (e.g. Your Lottie dependencies will be changed from Support to AnroidX)
From the Android Studio Documentation (https://developer.android.com/studio/preview/features/):
The Android Gradle plugin provides the following global flags that you can set in your gradle.properties file:
- android.useAndroidX: When set to true, this flag indicates that you want to start using AndroidX from now on. If the flag is absent, Android Studio behaves as if the flag were set to false.
- android.enableJetifier: When set to true, this flag indicates that you want to have tool support (from the Android Gradle plugin) to automatically convert existing third-party libraries as if they were written for AndroidX. If the flag is absent, Android Studio behaves as if the flag were set to false.
Precondition for Jetifier:
Android Studio 3.2
To enable jetifier, add those two lines to your gradle.properties
file:
android.useAndroidX=true
android.enableJetifier=true
Finally, please check the release notes of AndroidX, because jetifier
has still some problems with some libraries (e.g. Dagger Android): https://developer.android.com/topic/libraries/support-library/androidx-rn
We have had success with Perfect Address.
Their database has all the US street names and street number ranges. Also acts as a pretty decent parser for free-form address fields, if you are lucky enough to have that kind of data.
Another variation: Define two functions in the trait, a protected one that performs the actual task, and a public one which in turn calls the protected one.
This just saves classes from having to mess with the 'use' statement if they want to override the function, since they can still call the protected function internally.
trait A {
protected function traitcalc($v) {
return $v+1;
}
function calc($v) {
return $this->traitcalc($v);
}
}
class MyClass {
use A;
function calc($v) {
$v++;
return $this->traitcalc($v);
}
}
class MyOtherClass {
use A;
}
print (new MyClass())->calc(2); // will print 4
print (new MyOtherClass())->calc(2); // will print 3
With Spring Boot
its not necessary to have any config file like persistence.xml
. You can configure with annotations
Just configure your DB config for JPA in the
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass
spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true
Then you can use CrudRepository
provided by Spring where you have standard CRUD
transaction methods. There you can also implement your own SQL's
like JPQL
.
@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}
And if you still need to use the Entity Manager
you can create another class.
public class ObjectRepositoryImpl implements ObjectCustomMethods{
@PersistenceContext
private EntityManager em;
}
This should be in your pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>
A couple of examples:
infix fun Double.f(fmt: String) = "%$fmt".format(this)
infix fun Double.f(fmt: Float) = "%${if (fmt < 1) fmt + 1 else fmt}f".format(this)
val pi = 3.14159265358979323
println("""pi = ${pi f ".2f"}""")
println("pi = ${pi f .2f}")
You can upload it into Google Docs, and embed the Google Spreadsheet as detailed here: http://support.google.com/docs/bin/answer.py?hl=en&answer=55244
There are Linq extension methods for DataTable.
Add reference to: System.Data.DataSetExtensions.dll
Then include the namespace: using System.Data.DataSetExtensions
Finally you can use Linq extensions on DataSet and DataTables:
var matches = myDataSet.Tables.First().Where(dr=>dr.Field<int>("id") == 1);
On .Net 2.0 you can still add generic method:
public static List<T> ConvertRowsToList<T>( DataTable input, Convert<DataRow, T> conversion) {
List<T> retval = new List<T>()
foreach(DataRow dr in input.Rows)
retval.Add( conversion(dr) );
return retval;
}
According to Apple's Data Formatting Guide
Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable
And while I agree with @Leon that this should be failable initializer, when you enter seed data, we could have one that isn't failable (just like there is UIImage(imageLiteralResourceName:)
).
So here's my approach:
extension DateFormatter {
static let yyyyMMdd: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
extension Date {
init?(yyyyMMdd: String) {
guard let date = DateFormatter.yyyyMMdd.date(from: yyyyMMdd) else { return nil }
self.init(timeInterval: 0, since: date)
}
init(dateLiteralString yyyyMMdd: String) {
let date = DateFormatter.yyyyMMdd.date(from: yyyyMMdd)!
self.init(timeInterval: 0, since: date)
}
}
And now enjoy simply calling:
// For seed data
Date(dateLiteralString: "2020-03-30")
// When parsing data
guard let date = Date(yyyyMMdd: "2020-03-30") else { return nil }
The simplest in my opinion is just this:
it = iter([1,2,3,4,5,6])
for x, y in zip(it, it):
print x, y
Out: 1 2
3 4
5 6
No extra imports or anything. And very elegant, in my opinion.
PIL (Python Imaging Library) and Numpy work well together.
I use the following functions.
from PIL import Image
import numpy as np
def load_image( infilename ) :
img = Image.open( infilename )
img.load()
data = np.asarray( img, dtype="int32" )
return data
def save_image( npdata, outfilename ) :
img = Image.fromarray( np.asarray( np.clip(npdata,0,255), dtype="uint8"), "L" )
img.save( outfilename )
The 'Image.fromarray' is a little ugly because I clip incoming data to [0,255], convert to bytes, then create a grayscale image. I mostly work in gray.
An RGB image would be something like:
outimg = Image.fromarray( ycc_uint8, "RGB" )
outimg.save( "ycc.tif" )
As stated in the relevant RxJS documentation, the .subscribe()
method can take a third argument that is called on completion if there are no errors.
For reference:
[onNext]
(Function
): Function to invoke for each element in the observable sequence.[onError]
(Function
): Function to invoke upon exceptional termination of the observable sequence.[onCompleted]
(Function
): Function to invoke upon graceful termination of the observable sequence.
Therefore you can handle your routing logic in the onCompleted
callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).
this.httpService.makeRequest()
.subscribe(
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// 'onCompleted' callback.
// No errors, route to new page here
}
);
As a side note, there is also a .finally()
method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).
Rx.Observable.prototype.finally(action)
Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
For instance, here is a basic example:
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';
// ...
this.httpService.getRequest()
.finally(() => {
// Execute after graceful or exceptionally termination
console.log('Handle logging logic...');
})
.subscribe (
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// No errors, route to new page
}
);
To do it without any import:
>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3
Looking this up in my handy Harbison & Steele....
Determine the maximum width of fields.
int max_width, value_to_print;
max_width = 8;
value_to_print = 1000;
printf("%*d\n", max_width, value_to_print);
Bear in mind that max_width must be of type int
to work with the asterisk, and you'll have to calculate it based on how much space you're going to want to have. In your case, you'll have to calculate the maximum width of the largest number, and add 4.
In the command prompt, type the command below and press Enter.
bcdedit /enum
Under the Windows Boot Loader sections, make note of the identifier value.
To start in safe mode from command prompt :
bcdedit /set {identifier} safeboot minimal
Then enter the command line to reboot your computer.
Here is some code that show how it works.
class Test
{
public static void main(String args[])
{
System.out.println(Test.test());
}
public static String test()
{
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
return "return";
} finally {
System.out.println("finally");
return "return in finally";
}
}
}
The results is:
try
catch
finally
return in finally
Adding these two lines fixed this problem for me
"responsive": true,
"bAutoWidth": true
There is now a responsive plugin available: https://datatables.net/extensions/responsive/. However, in my experience I have found that there are still a few bugs. It's still the best solution I've found so far.
Try this, but I don't think it will work because you're not supposed to be able to change this
Put this line in an htaccess file in the directory you want the setting to be enabled:
php_value allow_url_fopen On
Note that this setting will only apply to PHP file's in the same directory as the htaccess file.
As an alternative to using url_fopen, try using curl.
Something a little shorter in syntax but taking what the others have already stated.
int num1, num2 = num1 = 1;
If you are on a Mac or BSD or something else without the --date option, you can use:
date -r `expr \`date +%s\` - 86400` '+%a %d/%m/%Y'
Update: or perhaps...
date -r $((`date +%s` - 86400)) '+%a %d/%m/%Y'
Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc
. To find spaces I use the libc function strpbrk
.
int print_words(const char *string, FILE *f)
{
static const char space_characters[] = " \t";
const char *next_space;
// Find the next space in the string
//
while ((next_space = strpbrk(string, space_characters)))
{
const char *p;
// If there are non-space characters between what we found
// and what we started from, print them.
//
if (next_space != string)
{
for (p=string; p<next_space; p++)
{
if(fputc(*p, f) == EOF)
{
return -1;
}
}
// Print a newline
//
if (fputc('\n', f) == EOF)
{
return -1;
}
}
// Advance next_space until we hit a non-space character
//
while (*next_space && strchr(space_characters, *next_space))
{
next_space++;
}
// Advance the string
//
string = next_space;
}
// Handle the case where there are no spaces left in the string
//
if (*string)
{
if (fprintf(f, "%s\n", string) < 0)
{
return -1;
}
}
return 0;
}