You can do (pre-Java 8):
List<Enum> enumValues = Arrays.asList(Enum.values());
or
List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));
Using Java 8 features, you can map each constant to its name:
List<String> enumNames = Stream.of(Enum.values())
.map(Enum::name)
.collect(Collectors.toList());
If your values are coming from the database, show selected values in that way.
<div class="form-group">
<label for="status">Status</label>
<select class="form-control" name="status" [(ngModel)]="category.status">
<option [value]="1" [selected]="category.status ==1">Active</option>
<option [value]="0" [selected]="category.status ==0">In Active</option>
</select>
</div>
function randomPassword(length) {
var chars = "abcdefghijklmnopqrstuvwxyz#$%ABCDEFGHIJKLMNOP1234567890";
var pass = "";
for (var x = 0; x < length; x++) {
var i = Math.floor(Math.random() * chars.length);
pass += chars.charAt(i);
}
var pattern = false;
var passwordpattern = new RegExp("[^a-zA-Z0-9+]+[0-9+]+[A-Z+]+[a-z+]");
pattern = passwordpattern.test(pass);
if (pattern == true)
{ alert(pass); }
else
{ randomPassword(length); }
}
try this to create the random password with atleast one special character
From ISO14882:2011(e) 5.6-4:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.
The rest is basic math:
(-7/3) => -2
-2 * 3 => -6
so a%b => -1
(7/-3) => -2
-2 * -3 => 6
so a%b => 1
Note that
If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
from ISO14882:2003(e) is no longer present in ISO14882:2011(e)
If your data is in wide format matplot
is made for this and often forgotten about:
dat <- matrix(runif(40,1,20),ncol=4) # make data
matplot(dat, type = c("b"),pch=1,col = 1:4) #plot
legend("topleft", legend = 1:4, col=1:4, pch=1) # optional legend
There is also the added bonus for those unfamiliar with things like ggplot
that most of the plotting paramters such as pch
etc. are the same using matplot()
as plot()
.
You can also do it this way.
Create the following named ranges:
nList = the list of original values
nRow = ROW(nList)-ROW(OFFSET(nList,0,0,1,1))+1
nUnique = IF(COUNTIF(OFFSET(nList,nRow,0),nList)=0,COUNTIF(nList, "<"&nList),"")
With these 3 named ranges you can generate the ordered list of unique values with the formula below. It will be sorted in ascending order.
IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-?),nUnique,0)),"")
You will need to substitute the row number of the cell just above the first element of your unique ordered list for the '?' character.
eg. If your unique ordered list begins in cell B5 then the formula will be:
IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-4),nUnique,0)),"")
I configured the app.config
with the tool for EntLib configuration and set up my LoggingConfiguration
block. Then I copied this into the DotNetConfig.xsd
. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.
<xs:element name="loggingConfiguration">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:attribute name="fileName" type="xs:string" use="required" />
<xs:attribute name="footer" type="xs:string" use="required" />
<xs:attribute name="formatter" type="xs:string" use="required" />
<xs:attribute name="header" type="xs:string" use="required" />
<xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
<xs:attribute name="rollInterval" type="xs:string" use="required" />
<xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
<xs:attribute name="timeStampPattern" type="xs:string" use="required" />
<xs:attribute name="listenerDataType" type="xs:string" use="required" />
<xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
<xs:attribute name="filter" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="formatters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="template" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="logFilters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="enabled" type="xs:boolean" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="categorySources">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="specialSources">
<xs:complexType>
<xs:sequence>
<xs:element name="allEvents">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="notProcessed">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="errors">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
<xs:attribute name="defaultCategory" type="xs:string" use="required" />
<xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
</xs:complexType>
</xs:element>
All error codes are on "CFNetwork Errors Codes References" on the documentation (link)
A small extraction for CFURL and CFURLConnection Errors:
kCFURLErrorUnknown = -998,
kCFURLErrorCancelled = -999,
kCFURLErrorBadURL = -1000,
kCFURLErrorTimedOut = -1001,
kCFURLErrorUnsupportedURL = -1002,
kCFURLErrorCannotFindHost = -1003,
kCFURLErrorCannotConnectToHost = -1004,
kCFURLErrorNetworkConnectionLost = -1005,
kCFURLErrorDNSLookupFailed = -1006,
kCFURLErrorHTTPTooManyRedirects = -1007,
kCFURLErrorResourceUnavailable = -1008,
kCFURLErrorNotConnectedToInternet = -1009,
kCFURLErrorRedirectToNonExistentLocation = -1010,
kCFURLErrorBadServerResponse = -1011,
kCFURLErrorUserCancelledAuthentication = -1012,
kCFURLErrorUserAuthenticationRequired = -1013,
kCFURLErrorZeroByteResource = -1014,
kCFURLErrorCannotDecodeRawData = -1015,
kCFURLErrorCannotDecodeContentData = -1016,
kCFURLErrorCannotParseResponse = -1017,
kCFURLErrorInternationalRoamingOff = -1018,
kCFURLErrorCallIsActive = -1019,
kCFURLErrorDataNotAllowed = -1020,
kCFURLErrorRequestBodyStreamExhausted = -1021,
kCFURLErrorFileDoesNotExist = -1100,
kCFURLErrorFileIsDirectory = -1101,
kCFURLErrorNoPermissionsToReadFile = -1102,
kCFURLErrorDataLengthExceedsMaximum = -1103,
You can use the -executable
test flag:
-executable
Matches files which are executable and directories which are
searchable (in a file name resolution sense).
Here is what you want. In this case you do not want the list items to be treated as blocks that can wrap.
li{display:inline}
ul{overflow:hidden}
A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting *
your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.
The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID
.
Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT *
is regarded as bad practice in production code: explicitly named columns are much safer.
This works for me:
RewriteCond %{HTTP_HOST} ^(?!www.domain.com).*$ [NC]
RewriteRule ^(.*)$ http://www.domain.com$1 [R=301,L]
I use the look-ahead pattern (?!www.domain.com)
to exclude the www
subdomain when redirecting all domains to the www
subdomain in order to avoid an infinite redirect loop in Apache.
You can use:
array_search()
in_array()
array_flip()
and array_key_exists()
new Date().getTime() is bugged.
Date date = new Date();
System.out.println(date);
System.out.println(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
long t1 = date.getTime();
System.out.println((t1 / 1000 / 60 / 60) % 24 + ":" + (t1 / 1000 / 60) % 60 + ":" + (t1 / 1000) % 60);
long t2 = System.currentTimeMillis();
System.out.println((t2 / 1000 / 60 / 60) % 24 + ":" + (t2 / 1000 / 60) % 60 + ":" + (t2 / 1000) % 60);
It returns me the wrong time millis. System.currentTimeMillis()
too. Since I ask the Date instance to tell me the corresponding time millis it must return the matching ones not others from a different time zone. Funny how deprecated methods are the only ones which return correct values.
docker pull
will fail if docker service
is not running. Make sure it is running by
:~$ ps aux | grep docker
root 18745 1.7 0.9 284104 13976 ? Ssl 21:19 0:01 /usr/bin/docker -d
If it is not running, you can start it by
sudo service docker start
For Ubuntu 15 and above use
sudo systemctl start docker
I would add that since version 3.6, we can use fstrings like the following
foo = "john"
bar = "smith"
print(f"My name is {foo} {bar}")
Which give
My name is john smith
Everything is converted to strings
mylist = ["foo", "bar"]
print(f"mylist = {mylist}")
Result:
mylist = ['foo', 'bar']
you can pass function, like in others formats method
print(f'Hello, here is the date : {time.strftime("%d/%m/%Y")}')
Giving for example
Hello, here is the date : 16/04/2018
Left Click on wamp go to apache> select http.config
change LISTEN:80 to what ever you want you can choose any value of 4 digit like 1311,8000,9999 etc
Based on your comment to Haim, is this a file on your own server? If so, you need to use the file system path, not url (e.g. file_exists( '/path/to/images/thumbnail.jpg' )
).
carlpett's find
-based answer (find . -maxdepth 1 -type f
) works in principle, but is not quite the same as using ls
: you get a potentially unsorted list of filenames all prefixed with ./
, and you lose the ability to apply ls
's many options;
also find
invariably finds hidden items too, whereas ls
' behavior depends on the presence or absence of the -a
or -A
options.
An improvement, suggested by Alex Hall in a comment on the question is to combine shell globbing with find
:
find * -maxdepth 0 -type f # find -L * ... includes symlinks to files
ls
's many other sorting / output-format options.Hans Roggeman's ls
+ grep
answer is pragmatic, but locks you into using long (-l
) output format.
To address these limitations I wrote the fls
(filtering ls) utility,
ls
while also providing type-filtering capability,f
for files, d
for directories, and l
for symlinks before a list of ls
arguments (run fls --help
or fls --man
to learn more).Examples:
fls f # list all files in current dir.
fls d -tA ~ # list dirs. in home dir., including hidden ones, most recent first
fls f^l /usr/local/bin/c* # List matches that are files, but not (^) symlinks (l)
Supported platforms
Note: Even if you don't use Node.js, its package manager, npm
, works across platforms and is easy to install; try
curl -L https://git.io/n-install | bash
With Node.js installed, install as follows:
[sudo] npm install fls -g
Note:
Whether you need sudo
depends on how you installed Node.js / io.js and whether you've changed permissions later; if you get an EACCES
error, try again with sudo
.
The -g
ensures global installation and is needed to put fls
in your system's $PATH
.
bash
script as fls
.chmod +x fls
.$PATH
, such as /usr/local/bin
(macOS) or /usr/bin
(Linux).You can also try the following project that aims to help use that api. It's here:https://github.com/MathiasSeguy-Android2EE/GDirectionsApiUtils
How it works, definitly simply:
public class MainActivity extends ActionBarActivity implements DCACallBack{
/**
* Get the Google Direction between mDevice location and the touched location using the Walk
* @param point
*/
private void getDirections(LatLng point) {
GDirectionsApiUtils.getDirection(this, mDeviceLatlong, point, GDirectionsApiUtils.MODE_WALKING);
}
/*
* The callback
* When the direction is built from the google server and parsed, this method is called and give you the expected direction
*/
@Override
public void onDirectionLoaded(List<GDirection> directions) {
// Display the direction or use the DirectionsApiUtils
for(GDirection direction:directions) {
Log.e("MainActivity", "onDirectionLoaded : Draw GDirections Called with path " + directions);
GDirectionsApiUtils.drawGDirection(direction, mMap);
}
}
With /^[a-zA-Z]/
you only check the first character:
^
: Assert position at the beginning of the string[a-zA-Z]
: Match a single character present in the list below:
a-z
: A character in the range between "a" and "z"A-Z
: A character in the range between "A" and "Z"If you want to check if all characters are letters, use this instead:
/^[a-zA-Z]+$/.test(str);
^
: Assert position at the beginning of the string[a-zA-Z]
: Match a single character present in the list below:
+
: Between one and unlimited times, as many as possible, giving back as needed (greedy)a-z
: A character in the range between "a" and "z"A-Z
: A character in the range between "A" and "Z"$
: Assert position at the end of the string (or before the line break at the end of the string, if any)Or, using the case-insensitive flag i
, you could simplify it to
/^[a-z]+$/i.test(str);
Or, since you only want to test
, and not match
, you could check for the opposite, and negate it:
!/[^a-z]/i.test(str);
To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the nonlocal
keyword to modify a closure variable.
def incrementer():
counter = 0
def increment():
nonlocal counter
counter += 1
return counter
return increment
increment = incrementer()
increment() # 1
increment() # 2
* The question origially asked about closures in Python.
You can give the <hr noshade>
tag and go to your css file and add :
hr {_x000D_
border-top:0;_x000D_
color: #123455;_x000D_
}
_x000D_
<hr noshade />_x000D_
This s a test_x000D_
<hr noshade />
_x000D_
I'd like to share my example related to security in addition to Daniel Fernández.
<div th:switch="${#authentication}? ${#authorization.expression('isAuthenticated()')} : ${false}">
<span th:case="${false}">User is not logged in</span>
<span th:case="${true}">Logged in user</span>
<span th:case="*">Should never happen, but who knows...</span>
</div>
Here is complex expression with mixed 'authentication' and 'authorization' utility objects which produces 'true/false' result for thymeleaf template code.
The 'authentication' and 'authorization' utility objects came from thymeleaf extras springsecurity3 library. When 'authentication' object is not available OR authorization.expression('isAuthenticated()') evaluates to 'false', expression returns ${false}, otherwise ${true}.
don't add header in xml add using code by inflating layout
View hView = navigationView.inflateHeaderView(R.layout.nav_header_main);
ImageView imgvw = (ImageView)hView.findViewById(R.id.imageView);
TextView tv = (TextView)hView.findViewById(R.id.textview);
imgvw .setImageResource();
tv.settext("new text");
If it's always the same one column, then you can create a view that doesn't have it in it.
Otherwise, no I don't think so.
The issue is shadow coming out the side of the containing div. In order to avoid this, the blur value must equal the absolute value of the spread value.
div {_x000D_
-webkit-box-shadow: 0 4px 6px -6px #222;_x000D_
-moz-box-shadow: 0 4px 6px -6px #222;_x000D_
box-shadow: 0 4px 6px -6px #222;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
covered in depth here
I faced the same problem and search everywhere for a solution, at last, I fount something which works for me for every browsers.
html {
height: 0;
}
use this css or Instead of css you can have this javascript
$("html").height(0);
Hope this will work for you as well.
One additional option, is use equals
of Ramda library:
const c = {a: 1, b: 2};
const d = {b: 2, a: 1};
R.equals(c, d); //=> true
Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.
If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.
For more info on these techniques, please click here to refer the article
Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.
Also based on your markup your selector is wrong. it should be #advisersDiv
function fadeIn() {
$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
setTimeout(fadeOut,1); //<-- Provide any delay here
};
function fadeOut() {
$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();
To create a new line, symbol is '\n'
var i;
for(i=10; i>=0; i= i-1){
var s;
for(s=0; s<i; s = s+1){
document.write("*");
}
//i want this to print a new line
document.write('\n');
}
If you are outputting to the page, you'll want to use "<br/>"
instead of '/n'
;
If you're okay with a shallow copy, the underscore.js library has a clone method.
y = _.clone(x);
or you can extend it like
copiedObject = _.extend({},originalObject);
One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.
Another alternative is to represent a 2D array as an std::vector<std::vector<int> >
. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.
I found a way. It's a bit hacky but works.
vm.$set("x",0);
vm.$delete("x");
Where vm
is your view-model object, and x
is a non-existent variable.
Vue.js will complain about this in the console log but it does trigger a refresh for all data. Tested with version 1.0.26.
Line breaks are considered as content to elements in FF.
<div>
</div>
<div></div>
Ex:
$("div:empty").text("Empty").css('background', '#ff0000');
In IE both divs are considered empty, in FF an Chrome only the last one is empty.
You can use the solution provided by @qwertymk
if(!/[\S]/.test($('#element').html())) { // for one element
alert('empty');
}
or
$('.elements').each(function(){ // for many elements
if(!/[\S]/.test($(this).html())) {
// is empty
}
})
You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.
The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.
With an appropriate predicate in hand, problem 1 simplifies to:
low_primes = {x for x in range(1, 100) if is_prime(x)}
And problem 2 simplifies to:
low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}
Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."
P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.
I'm really fond of SPL Library, they offer iterator's, including RecursiveDirectoryIterator.
Here is the code I've written in C based on DFS to find out whether a given graph is connected/cyclic or not. with some sample output at the end. Hope it'll be helpful :)
#include<stdio.h>
#include<stdlib.h>
/****Global Variables****/
int A[20][20],visited[20],v=0,count=0,n;
int seq[20],s=0,connected=1,acyclic=1;
/****DFS Function Declaration****/
void DFS();
/****DFSearch Function Declaration****/
void DFSearch(int cur);
/****Main Function****/
int main()
{
int i,j;
printf("\nEnter no of Vertices: ");
scanf("%d",&n);
printf("\nEnter the Adjacency Matrix(1/0):\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&A[i][j]);
printf("\nThe Depth First Search Traversal:\n");
DFS();
for(i=1;i<=n;i++)
printf("%c,%d\t",'a'+seq[i]-1,i);
if(connected && acyclic) printf("\n\nIt is a Connected, Acyclic Graph!");
if(!connected && acyclic) printf("\n\nIt is a Not-Connected, Acyclic Graph!");
if(connected && !acyclic) printf("\n\nGraph is a Connected, Cyclic Graph!");
if(!connected && !acyclic) printf("\n\nIt is a Not-Connected, Cyclic Graph!");
printf("\n\n");
return 0;
}
/****DFS Function Definition****/
void DFS()
{
int i;
for(i=1;i<=n;i++)
if(!visited[i])
{
if(i>1) connected=0;
DFSearch(i);
}
}
/****DFSearch Function Definition****/
void DFSearch(int cur)
{
int i,j;
visited[cur]=++count;
seq[count]=cur;
for(i=1;i<count-1;i++)
if(A[cur][seq[i]])
acyclic=0;
for(i=1;i<=n;i++)
if(A[cur][i] && !visited[i])
DFSearch(i);
}
/*Sample Output:
majid@majid-K53SC:~/Desktop$ gcc BFS.c
majid@majid-K53SC:~/Desktop$ ./a.out
************************************
Enter no of Vertices: 10
Enter the Adjacency Matrix(1/0):
0 0 1 1 1 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 1 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 1 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0 0 0
The Depdth First Search Traversal:
a,1 c,2 d,3 f,4 b,5 e,6 g,7 h,8 i,9 j,10
It is a Not-Connected, Cyclic Graph!
majid@majid-K53SC:~/Desktop$ ./a.out
************************************
Enter no of Vertices: 4
Enter the Adjacency Matrix(1/0):
0 0 1 1
0 0 1 0
1 1 0 0
0 0 0 1
The Depth First Search Traversal:
a,1 c,2 b,3 d,4
It is a Connected, Acyclic Graph!
majid@majid-K53SC:~/Desktop$ ./a.out
************************************
Enter no of Vertices: 5
Enter the Adjacency Matrix(1/0):
0 0 0 1 0
0 0 0 1 0
0 0 0 0 1
1 1 0 0 0
0 0 1 0 0
The Depth First Search Traversal:
a,1 d,2 b,3 c,4 e,5
It is a Not-Connected, Acyclic Graph!
*/
UPDATE: READONLY
doesn't work on checkboxes
You could use disabled="disabled"
but at this point checkbox's value will not appear into POST
values. One of the strategy is to add an hidden field holding checkbox's value within the same form and read value back from that field
Simply change disabled
to readonly
While I myself would be waiting here for an answer, I wonder if it can be done via CSS:
@media only screen and (orientation:portrait){
#wrapper {width:1024px}
}
@media only screen and (orientation:landscape){
#wrapper {width:1024px}
}
If people are using shared Linux hosting with cPanel (Godaddy, Reseller club, Hostgator or any Shared Hosting), try the following:
Under Software and Services tab -> Select PHP Version -> PHP Selectors | Extentions
Tick all MySQL related extensions, save it and you are done. Please check the attached image.
You should use monit, a standard unix tool that can monitor different things on the system and react accordingly.
From the docs: http://mmonit.com/monit/documentation/monit.html#pid_testing
check process checkqueue.py with pidfile /var/run/checkqueue.pid if changed pid then exec "checkqueue_restart.sh"
You can also configure monit to email you when it does do a restart.
Just complementing @yuchaozh answer above that helped me solve it. (I don't have rep to comment)
Run this to know which java version you have
ls /Library/Java/JavaVirtualMachines/
You'll get an output like:
jdk1.8.0_111.jdk
Replace with your Java version and run this command to export the correct path.
export JAVA_HOME="/Library/Java/JavaVirtualMachines/<YOUR_JAVA_VERSION>/Contents/Home"
The Main
method is static inside the Program
class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits()
method static as well.
given that you're a newbie, I'd say don't try to do this yet. it's definitely possible, but will needlessly complicate your Makefile. stick to the simple ways until you're more comfortable with make.
that said, one way to build in a directory different from the source directory is VPATH; i prefer pattern rules
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
SynchronizedMap
and ConcurrentHashMap
are both thread safe class and can be used in multithreaded application, the main difference between them is regarding how they achieve thread safety.
SynchronizedMap
acquires lock on the entire Map instance , while ConcurrentHashMap
divides the Map instance into multiple segments and locking is done on those.
Your svn merge
syntax is wrong.
You want to checkout a working copy of trunk
and then use the svn merge --reintegrate
option:
$ pwd
/home/user/project-trunk
$ svn update # (make sure the working copy is up to date)
At revision <N>.
$ svn merge --reintegrate ^/project/branches/branch_1
--- Merging differences between repository URLs into '.':
U foo.c
U bar.c
U .
$ # build, test, verify, ...
$ svn commit -m "Merge branch_1 back into trunk!"
Sending .
Sending foo.c
Sending bar.c
Transmitting file data ..
Committed revision <N+1>.
See the SVN book chapter on merging for more details.
Note that at the time it was written, this was the right answer (and was accepted), but things have moved on. See the answer of topek, and http://subversion.apache.org/docs/release-notes/1.8.html#auto-reintegrate
It depends on the size of the file! The solutions above tend to use convenient shorthands to copy the entire file into memory, which will work in many cases.
For very large files you may need to use a streaming design where read the file by line or in chucks, process the chunks, then discard them from memory.
See the answer on reading line by line with perl if that's what you need.
The draft CSS Selectors Level 4 proposes to add an of <other-selector>
grammar within the :nth-child
selector. This would allow you to pick out the nth child matching a given other selector:
:nth-child(1 of p.myclass)
Previous drafts used a new pseudo-class, :nth-match()
, so you may see that syntax in some discussions of the feature:
:nth-match(1 of p.myclass)
This has now been implemented in WebKit, and is thus available in Safari, but that appears to be the only browser that supports it. There are tickets filed for implementing it Blink (Chrome), Gecko (Firefox), and a request to implement it in Edge, but no apparent progress on any of these.
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
declare @date int
WITH CTE_DatesTable
AS
(
SELECT CAST('20000101' as date) AS [date]
UNION ALL
SELECT DATEADD(dd, 1, [date])
FROM CTE_DatesTable
WHERE DATEADD(dd, 1, [date]) <= '21001231'
)
SELECT [DWDateKey]=[date],[DayDate]=datepart(dd,[date]),[DayOfWeekName]=datename(dw,[date]),[WeekNumber]=DATEPART( WEEK , [date]),[MonthNumber]=DATEPART( MONTH , [date]),[MonthName]=DATENAME( MONTH , [date]),[MonthShortName]=substring(LTRIM( DATENAME(MONTH,[date])),0, 4),[Year]=DATEPART(YY,[date]),[QuarterNumber]=DATENAME(quarter, [date]),[QuarterName]=DATENAME(quarter, [date]) into DimDate FROM CTE_DatesTable
OPTION (MAXRECURSION 0);
The reason you got this error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/dbname
Is because you forgot to register your mysql jdbc driver with the java application.
This is what you wrote:
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
throw new RuntimeException(e);
}
Should be this:
Connection con = null;
try {
//registering the jdbc driver here, your string to use
//here depends on what driver you are using.
Class.forName("something.jdbc.driver.YourFubarDriver");
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
throw new RuntimeException(e);
}
You'll have to read the manual on your specific mysql jdbc driver to find the exact string to place inside the the Class.forName("...") parameter.
Class.forName not required with JDBC v.4
Starting with Java 6, Class.forName("something.jdbc.driver.YourFubarDriver")
is not necessary anymore if you use a recent (JDBC v.4) driver. For details read this: http://onjava.com/pub/a/onjava/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html
I like to use this clean code to pass one value only:
startActivity(new Intent(context, YourActivity.class).putExtra("key","value"));
This make more simple to write and understandable code.
You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.
Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)
follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html
Default value for char
is \u0000
public class DefaultValues {
char varChar;
public static void main(String...l)
{
DefaultValues ob =new DefaultValues();
System.out.println(ob.varChar=='\u0000');
}
}
This will return true
In case you want the difference recursively going deep into items of your list, I have written a package for python: https://github.com/erasmose/deepdiff
Install from PyPi:
pip install deepdiff
If you are Python3 you need to also install:
pip install future six
>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function
Same object returns empty
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> ddiff = DeepDiff(t1, t2)
>>> print (ddiff.changes)
{}
Type of an item has changed
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> ddiff = DeepDiff(t1, t2)
>>> print (ddiff.changes)
{'type_changes': ["root[2]: 2=<type 'int'> vs. 2=<type 'str'>"]}
Value of an item has changed
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> ddiff = DeepDiff(t1, t2)
>>> print (ddiff.changes)
{'values_changed': ['root[2]: 2 ====>> 4']}
Item added and/or removed
>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes)
{'dic_item_added': ['root[5, 6]'],
'dic_item_removed': ['root[4]'],
'values_changed': ['root[2]: 2 ====>> 4']}
String difference
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'values_changed': [ 'root[2]: 2 ====>> 4',
"root[4]['b']:\n--- \n+++ \n@@ -1 +1 @@\n-world\n+world!"]}
>>>
>>> print (ddiff.changes['values_changed'][1])
root[4]['b']:
---
+++
@@ -1 +1 @@
-world
+world!
String difference 2
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'values_changed': [ "root[4]['b']:\n--- \n+++ \n@@ -1,5 +1,4 @@\n-world!\n-Goodbye!\n+world\n 1\n 2\n End"]}
>>>
>>> print (ddiff.changes['values_changed'][0])
root[4]['b']:
---
+++
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
1
2
End
Type change
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'type_changes': [ "root[4]['b']: [1, 2, 3]=<type 'list'> vs. world\n\n\nEnd=<type 'str'>"]}
List difference
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'list_removed': ["root[4]['b']: [3]"]}
List difference 2: Note that it DOES NOT take order into account
>>> # Note that it DOES NOT take order into account
... t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ }
List that contains dictionary:
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
'values_changed': ["root[4]['b'][2][1]: 1 ====>> 3"]}
For me this error occurred because I had 2 web API actions that had the exact same signatures and both had the same verbs, HttpPost
, what I did was change one of the verbs (the one used for updating) to PUT and the error was removed. The following in my catch statement helped in getting to the root of the problem:
catch (WebException webex)
{
WebResponse errResp = webex.Response;
using (Stream respStream = errResp.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream);
string text = reader.ReadToEnd();
}
}
In typescript create a file named format.ts
and import it whatever you need to use formatting.
// contents of format.ts
interface String {
format(...args: any[]): string;
}
if (!String.prototype.format) {
String.prototype.format = function() {
let a = this;
let b: any;
// tslint:disable-next-line: forin
for (b in arguments) {
a = a.replace(/%[a-z]/, arguments[b]);
}
return a;
};
}
To format string use this code:
import './format';
console.log('Hello, %s!'.format('World'));
String.prototype.format = function() {_x000D_
let a = this;_x000D_
let b;_x000D_
for (b in arguments) {_x000D_
a = a.replace(/%[a-z]/, arguments[b]);_x000D_
}_x000D_
return a;_x000D_
};_x000D_
_x000D_
console.log('Hello, %s!'.format('World'));
_x000D_
Consider this as your select list:
<select onchange="var optionVal = $(this).find(':selected').val(); doSomething(optionVal)">
<option value="mostSeen">Most Seen</option>
<option value="newst">Newest</option>
<option value="mostSell">Most Sell</option>
<option value="mostCheap">Most Cheap</option>
<option value="mostExpensive">Most Expensive</option>
</select>
then you check selected option like this:
function doSomething(param) {
if ($(param.selected)) {
alert(param + ' is selected!');
}
}
If you want to trim the whitespace off just the beginning and end of the string, you can do something like this:
some_string = " Hello, world!\n "
new_string = some_string.strip()
# new_string is now "Hello, world!"
This works a lot like Qt's QString::trimmed() method, in that it removes leading and trailing whitespace, while leaving internal whitespace alone.
But if you'd like something like Qt's QString::simplified() method which not only removes leading and trailing whitespace, but also "squishes" all consecutive internal whitespace to one space character, you can use a combination of .split()
and " ".join
, like this:
some_string = "\t Hello, \n\t world!\n "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"
In this last example, each sequence of internal whitespace replaced with a single space, while still trimming the whitespace off the start and end of the string.
Alright, so I got it working by changing this
log4j.rootLogger=DebugAppender
to this
log4j.rootLogger=DEBUG, DebugAppender
Apparently you have to specify the logging level to the rootLogger
first? I apologize if I wasted anyone's time.
Also, I decided to answer my own question because this wasn't a classpath issue.
To convert seconds (as string) into datetime, this could also help. You get number of days and seconds. Seconds can be further converted into minutes and hours.
from datetime import datetime, timedelta
sec = timedelta(seconds=(int(input('Enter the number of seconds: '))))
time = str(sec)
if you're doing a lot of this kind of thing you should consider using numpy
.
In [56]: import random, numpy
In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
In [58]: a, b = 1, 3
In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
In response to Seanny123's question, I used this timing code:
import numpy, timeit, random
a, b = 1, 3
lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
def numpy_way():
numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
def list_comprehension():
[e for e in lst if 1 < e < 3][:10]
print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)
The numpy version is over 60 times faster.
In my case I was using invalid templateUrl.By correcting it problem solved.
@Component({
selector: 'app-edit-feather-object',
templateUrl: ''
})
While there is no iterator reset, the "itertools" module from python 2.6 (and later) has some utilities that can help there. One of then is the "tee" which can make multiple copies of an iterator, and cache the results of the one running ahead, so that these results are used on the copies. I will seve your purposes:
>>> def printiter(n):
... for i in xrange(n):
... print "iterating value %d" % i
... yield i
>>> from itertools import tee
>>> a, b = tee(printiter(5), 2)
>>> list(a)
iterating value 0
iterating value 1
iterating value 2
iterating value 3
iterating value 4
[0, 1, 2, 3, 4]
>>> list(b)
[0, 1, 2, 3, 4]
That's simple, if you reference them by index. If you want to hide the first column, you would:
Copy code
$('#thetable tr').find('td:nth-child(1),th:nth-child(1)').toggle();
The reason I first selected all table rows and then both td's and th's that were the n'th child is so that we wouldn't have to select the table and all table rows twice. This improves script execution speed. Keep in mind, nth-child()
is 1
based, not 0
.
When calling the callback function, we could use it like below:
consumingFunction(callbackFunctionName)
Example:
// Callback function only know the action,
// but don't know what's the data.
function callbackFunction(unknown) {
console.log(unknown);
}
// This is a consuming function.
function getInfo(thenCallback) {
// When we define the function we only know the data but not
// the action. The action will be deferred until excecuting.
var info = 'I know now';
if (typeof thenCallback === 'function') {
thenCallback(info);
}
}
// Start.
getInfo(callbackFunction); // I know now
This is the Codepend with full example.
It's been a while since the OP, but here's my solution for this using Bootstrap 3. In my use case, I was only targeting rows, but the same could be applied to the container, etc.
Just change .row to whatever you want.
jQuery(document).ready(function ($) {
var alterClass = function () {
var ww = document.body.clientWidth;
if (ww < 768) {
$('.row').addClass('is-xs').removeClass('is-sm').removeClass('is-lg').removeClass('is-md');
} else if (ww >= 768 && ww < 992) {
$('.row').addClass('is-sm').removeClass('is-xs').removeClass('is-lg').removeClass('is-md');
} else if (ww >= 992 && ww < 1200) {
$('.row').addClass('is-md').removeClass('is-xs').removeClass('is-lg').removeClass('is-sm');
} else if (ww >= 1200) {
$('.row').addClass('is-lg').removeClass('is-md').removeClass('is-sm').removeClass('is-xs');
};
};
// Make Changes when the window is resized
$(window).resize(function () {
alterClass();
});
// Fire when the page first loads
alterClass();
});
You can use CSS3 transitions or maybe CSS3 animations to slide in an element.
For browser support: http://caniuse.com/
I made two quick examples just to show you how I mean.
CSS transition (on hover)
Relevant Code
.wrapper:hover #slide {
transition: 1s;
left: 0;
}
In this case, Im just transitioning the position from left: -100px;
to 0;
with a 1s. duration. It's also possible to move the element using transform: translate();
CSS animation
#slide {
position: absolute;
left: -100px;
width: 100px;
height: 100px;
background: blue;
-webkit-animation: slide 0.5s forwards;
-webkit-animation-delay: 2s;
animation: slide 0.5s forwards;
animation-delay: 2s;
}
@-webkit-keyframes slide {
100% { left: 0; }
}
@keyframes slide {
100% { left: 0; }
}
Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode
to forwards
, which will persist the end state, keeping the div visible when the animation ends.
Like I said, two quick example to show you how it could be done.
EDIT: For details regarding CSS Animations and Transitions see:
Animations
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations
Transitions
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
Hope this helped.
I really don't understand some of the hoops the other answers are jumping through.
var myString = " this is my String ";
var newstring = myString.Trim(); // results in "this is my String"
var noSpaceString = myString.Replace(" ", ""); // results in "thisismyString";
It's not rocket science.
I've created a library that uses multipart uploads in the background to avoid buffering everything in memory and also doesn't write to disk: https://github.com/alexmojaki/s3-stream-upload
You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.
It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1
E.g.:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM
Where mF_9.B5f-4.1JqM is your OAuth access token.
why not simply eg
var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;
oh ... according to the documentation you can leave out the .Distinct()
This method excludes duplicates from the return set
enter code here
package in.my;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
private static final String DATABASE_NAME = "helper.db";
private static final int DATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
private static final String Table_Record =
"create table Student (_id integer primary key autoincrement, "
+ "Name text not null,rate integer, Phone text not null,Salary text not null,email text not null,address text not null,des text not null,qual text not null,doj text not null);";
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(Table_Record);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return DBAdapter.this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public long insertTitle(String name,String phone,String web,String des,String address,String doj,String qual,String sal,int rate)
{
ContentValues initialValues = new ContentValues();
initialValues.put("Name", name);
initialValues.put("Phone", phone);
initialValues.put("email", web);
initialValues.put("des", des);
initialValues.put("Salary", sal);
initialValues.put("qual", qual);
initialValues.put("address", address);
initialValues.put("doj", doj);
initialValues.put("rate", rate);
return db.insert("Student", null, initialValues);
}
public boolean deleteTitle(long rowId)
{
return db.delete("Student", KEY_ID +
"=" + rowId, null) > 0;
}
public boolean UpdateTitle(long id,String name,String phone,String web,String des,String address,String doj,String qual,String sal,int rate)
{
ContentValues initialValues = new ContentValues();
initialValues.put("Name", name);
initialValues.put("Phone", phone);
initialValues.put("email", web);
initialValues.put("des", des);
initialValues.put("qual", qual);
initialValues.put("Salary", sal);
initialValues.put("address", address);
initialValues.put("doj", doj);
initialValues.put("rate", rate);
return db.update("Student",initialValues, KEY_ID + "=" + id, null)>0;
//return db.insert("Student", null, initialValues);
}
public Cursor getAllRecords()
{
return db.query("Student", new String[] {
KEY_ID,
"Name",
"Phone",
"email",
"address",
"des",
"qual",
"doj",
"Salary",
"rate"
},
null,
null,
null,
null,
null);
}
}
If you are using python 3.6 or latest, f-string is the best and easy one
print(f"{your_varaible_name}")
Pyexcel works great with both Python2 and Python3 without troubles.
Fast installation with pip:
pip install pyexcel
After that, only 3 lines of code and the job is done:
import pyexcel
data = [['Me', 'You'], ['293', '219'], ['54', '13']]
pyexcel.save_as(array = data, dest_file_name = 'csv_file_name.csv')
An example of how you could do this:
Some notes:
LoggingHandler
intercepts the request before it handles it to HttpClientHandler
which finally writes to the wire.
PostAsJsonAsync
extension internally creates an ObjectContent
and when ReadAsStringAsync()
is called in the LoggingHandler
, it causes the formatter
inside ObjectContent
to serialize the object and that's the reason you are seeing the content in json.
Logging handler:
public class LoggingHandler : DelegatingHandler
{
public LoggingHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Console.WriteLine("Request:");
Console.WriteLine(request.ToString());
if (request.Content != null)
{
Console.WriteLine(await request.Content.ReadAsStringAsync());
}
Console.WriteLine();
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Console.WriteLine("Response:");
Console.WriteLine(response.ToString());
if (response.Content != null)
{
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
Console.WriteLine();
return response;
}
}
Chain the above LoggingHandler with HttpClient:
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;
Output:
Request:
Method: POST, RequestUri: 'http://kirandesktop:9095/api/values', Version: 1.1, Content: System.Net.Http.ObjectContent`1[
[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
Content-Type: application/json; charset=utf-8
}
"Hello, World!"
Response:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Fri, 20 Sep 2013 20:21:26 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 15
Content-Type: application/json; charset=utf-8
}
"Hello, World!"
You could use the SizeMode property of the PictureBox Control and set it to Center. This will match the center of your image to the center of your picture box.
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
Hope it could help.
Attach a String() string
method to any named type and enjoy any custom "ToString" functionality:
package main
import "fmt"
type bin int
func (b bin) String() string {
return fmt.Sprintf("%b", b)
}
func main() {
fmt.Println(bin(42))
}
Playground: http://play.golang.org/p/Azql7_pDAA
Output
101010
When the first characters in a script are #!
, that is called the shebang. If your file starts with
#!/path/to/something
the standard is to run something
and pass the rest of the file to that program as an input.
With that said, the difference between #!/bin/bash
, #!/bin/sh
, or even #!/bin/zsh
is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash
and sh
are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh
is a link to dash
, and on traditional Unix systems (Solaris, Irix, etc) bash
is usually a completely different program from sh
.
Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python
, #!/usr/bin/perl
, or even #!/usr/local/bin/my_own_scripting_language
.
import android.graphics.Color;
import java.util.Random;
public class ColorDiagram {
// Member variables (properties about the object)
public String[] mColors = {
"#39add1", // light blue
"#3079ab", // dark blue
"#c25975", // mauve
"#e15258", // red
"#f9845b", // orange
"#838cc7", // lavender
"#7d669e", // purple
"#53bbb4", // aqua
"#51b46d", // green
"#e0ab18", // mustard
"#637a91", // dark gray
"#f092b0", // pink
"#b7c0c7" // light gray
};
// Method (abilities: things the object can do)
public int getColor() {
String color = "";
// Randomly select a fact
Random randomGenerator = new Random(); // Construct a new Random number generator
int randomNumber = randomGenerator.nextInt(mColors.length);
color = mColors[randomNumber];
int colorAsInt = Color.parseColor(color);
return colorAsInt;
}
}
I see you try to set ylim
but you give bad values. This will change the scale of the plot (like a zoom). For example see this:
par(mfrow=c(2,1))
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN, col = rainbow(20),ylim=c(0,50),main='long y-axis')
r <- barplot(tN, col = rainbow(20),main='short y axis')
Another option is to plot without axes and set them manually using axis
and usr
:
require(grDevices) # for colours
par(mfrow=c(1,1))
r <- barplot(tN, col = rainbow(20),main='short y axis',ann=FALSE,axes=FALSE)
usr <- par("usr")
par(usr=c(usr[1:2], 0, 20))
axis(2,at=seq(0,20,5))
Contrary to what David Knight says, these two alternatives return the same response in MS SQL 2008:
SELECT CONVERT(VARCHAR(32),HashBytes('MD5', 'Hello World'),2)
SELECT UPPER(master.dbo.fn_varbintohexsubstring(0, HashBytes('MD5', 'Hello World'), 1, 0))
So it looks like the first one is a better choice, starting from version 2008.
Is there something that prevents you from merging all revisions on trunk since the last merge?
svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc
should work just fine. At least if you want to merge all changes on trunk to your branch.
You need to add overflow:auto
to your parent div for it to encompass the inner floated div:
<div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange;overflow:auto">
<div style="width:500px; height:200px; background-color:black; float:right">
</div>
</div>
If you only want to extract only positive integers, try the following:
>>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]
I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.
This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.
Yes, the value of any argument can be found using getArgs
@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {
Object[] signatureArgs = thisJoinPoint.getArgs();
for (Object signatureArg: signatureArgs) {
System.out.println("Arg: " + signatureArg);
...
}
}
The core thing you're going to want here is git add -p
(-p
is a synonym for --patch
). This provides an interactive way to check in content, letting you decide whether each hunk should go in, and even letting you manually edit the patch if necessary.
To use it in combination with cherry-pick:
git cherry-pick -n <commit> # get your patch, but don't commit (-n = --no-commit)
git reset # unstage the changes from the cherry-picked commit
git add -p # make all your choices (add the changes you do want)
git commit # make the commit!
(Thanks to Tim Henigan for reminding me that git-cherry-pick has a --no-commit option, and thanks to Felix Rabe for pointing out that you need to reset! If you only want to leave a few things out of the commit, you could use git reset <path>...
to unstage just those files.)
You can of course provide specific paths to add -p
if necessary. If you're starting with a patch you could replace the cherry-pick
with apply
.
If you really want a git cherry-pick -p <commit>
(that option does not exist), your can use
git checkout -p <commit>
That will diff the current commit against the commit you specify, and allow you to apply hunks from that diff individually. This option may be more useful if the commit you're pulling in has merge conflicts in part of the commit you're not interested in. (Note, however, that checkout
differs from cherry-pick
: checkout
tries to apply <commit>
's contents entirely, cherry-pick
applies the diff of the specified commit from it's parent. This means that checkout
can apply more than just that commit, which might be more than you want.)
Since my other answer was obviously not well understood, here's a second attempt:
There's two approaches to answer the question.
Forget about the :after
pseudo-selector, and go for something like
.pdflink {
min-height: 20px;
padding-right: 10px;
background-position: right bottom;
background-size: 10px 20px;
background-repeat: no-repeat;
}
The question is: Can you style generated content? The answer is: No, you can't. There's been a lengthy discussion on the W3C mailing list on this issue, but no solution so far.
Generated content is rendered into a generated box, and you can style that box, but not the content as such. Different browsers show very different behaviour
#foo {content: url("bar.jpg"); width: 42px; height:42px;} #foo::before {content: url("bar.jpg"); width: 42px; height:42px;}
Chrome resizes the first one, but uses the intrinsic dimensions of the image for the second
firefox and ie don't support the first, and use intrinsic dimensions for the second
opera uses intrinsic dimensions for both cases
(from http://lists.w3.org/Archives/Public/www-style/2011Nov/0451.html )
Similarly, browsers show very different results on things like http://jsfiddle.net/Nwupm/1/ , where more than one element is generated. Keep in mind that CSS3 is still in early development stage, and this issue has yet to be solved.
Would like to take credit for this but I found a solution here:
https://teamtreehouse.com/forum/how-do-you-make-a-svg-clickable
add the following to the css for the anchor:
a.svg {
position: relative;
display: inline-block;
}
a.svg:after {
content: "";
position: absolute;
top: 0;
right: 0;
bottom: 0;
left:0;
}
<a href="#" class="svg">
<object data="random.svg" type="image/svg+xml">
<img src="random.jpg" />
</object>
</a>
Link works on the svg and on the fallback.
You can create a trigger which updates NoofUses
column in Coupon
table whenever
couponid
is used in CouponUse
table
query :
CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end
In package manager console execute: Update-Package –reinstall Newtonsoft.Json
.
UPDATE
I originally posted this as a comment but as @OwenBlacker suggested I'll just put it here:
If you still get an error after doing this, then what worked for me eventually is that I deleted Json.Net's <dependentAssembly>
section from my .config
file. Reinstall brings it back if it's not there and apparently you need to delete it. Until there will be a normal solution in the package itself, I'm afraid this manual step is a must.
Note: Please read the comments below before doing this.
As per René's comment below BE AWARE that the command posted in the answer will reinstall the package in every project in your solution. So if you use the Newtonsoft.Json package in several projects and maybe use different versions, just executing the above command might have unwanted consequences.
By default node package is nodejs, so use
$ nodejs -v
or
$ nodejs --version
You can make a link using
$ sudo ln -s /usr/bin/nodejs /usr/bin/node
then u can use
$ node --version
or
$ node -v
I've had this sort of problem.....
The solve: cmd
/ powershell
run as ADMINISTRATOR! I always forget.
Notice: In powershell
, you need to put .\
for example:
.\httpd -k shutdown .\httpd -k stop .\httpd -k uninstall
Result: Removing the apache2.4
service The Apache2.4
service has been removed successfully.
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
You can use the CorFlags CLI tool (for instance, C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\CorFlags.exe) to determine the status of an assembly, based on its output and opening an assembly as a binary asset you should be able to determine where you need to seek to determine if the 32BIT flag is set to 1 (x86) or 0 (Any CPU or x64, depending on PE
):
Option | PE | 32BIT
----------|-------|---------
x86 | PE32 | 1
Any CPU | PE32 | 0
x64 | PE32+ | 0
The blog post x64 Development with .NET has some information about corflags
.
Even better, you can use Module.GetPEKind
to determine whether an assembly is PortableExecutableKinds
value PE32Plus
(64-bit), Required32Bit
(32-bit and WOW), or ILOnly
(any CPU) along with other attributes.
Here is one more solution but a single risk.
code:
#include <iostream>
#include <conio.h>
void main()
{
int a =10 , b =45;
*(&a+1 ) = a;
a =b;
b =*(&a +1);
}
any value at location a+1 will be overridden.
Use a seperate column to indicate the join condition
SELECT t.importid,
case
when t.importid = g.home
then 'home'
else 'away'
end as join_condition,
g.network,
g.date_start
FROM game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC
LIMIT 7
Got the same issues after two years. I think this post explains the reason I got (But may be not the reason in this question). Use subscribed developer account or static libraries could help. Like remove use_frameworks!
in your Podfile
.
I would like to update on this, because in .NET Core multi-dimensional arrays are faster than jagged arrays. I ran the tests from John Leidegren and these are the results on .NET Core 2.0 preview 2. I increased the dimension value to make any possible influences from background apps less visible.
Debug (code optimalization disabled)
Running jagged
187.232 200.585 219.927 227.765 225.334 222.745 224.036 222.396 219.912 222.737
Running multi-dimensional
130.732 151.398 131.763 129.740 129.572 159.948 145.464 131.930 133.117 129.342
Running single-dimensional
91.153 145.657 111.974 96.436 100.015 97.640 94.581 139.658 108.326 92.931
Release (code optimalization enabled)
Running jagged
108.503 95.409 128.187 121.877 119.295 118.201 102.321 116.393 125.499 116.459
Running multi-dimensional
62.292 60.627 60.611 60.883 61.167 60.923 62.083 60.932 61.444 62.974
Running single-dimensional
34.974 33.901 34.088 34.659 34.064 34.735 34.919 34.694 35.006 34.796
I looked into disassemblies and this is what I found
jagged[i][j][k] = i * j * k;
needed 34 instructions to execute
multi[i, j, k] = i * j * k;
needed 11 instructions to execute
single[i * dim * dim + j * dim + k] = i * j * k;
needed 23 instructions to execute
I wasn't able to identify why single-dimensional arrays were still faster than multi-dimensional but my guess is that it has to do with some optimalization made on the CPU
It's possible without jQuery too! :)
let countries = ['United States', 'Canada', 'Argentina', 'Armenia', 'Aruba'];_x000D_
_x000D_
// The <ul> that we will add <li> elements to:_x000D_
let myList = document.querySelector('ul.mylist');_x000D_
_x000D_
// Loop over the Array of country names:_x000D_
countries.forEach(function(value, index, array) {_x000D_
// Create an <li> element:_x000D_
let li = document.createElement('li');_x000D_
_x000D_
// Give it the desired classes & attributes:_x000D_
li.classList.add('ui-menu-item');_x000D_
li.setAttribute('role', 'menuitem');_x000D_
_x000D_
// Now create an <a> element:_x000D_
let a = document.createElement('a');_x000D_
_x000D_
// Give it the desired classes & attributes:_x000D_
a.classList.add('ui-all');_x000D_
a.tabIndex = -1;_x000D_
a.innerText = value; // <--- the country name from our Array_x000D_
a.href = "#"_x000D_
_x000D_
// Now add the <a> to the <li>, and add the <li> to the <ul>_x000D_
li.appendChild(a);_x000D_
myList.appendChild(li);_x000D_
});
_x000D_
<ul class="mylist"></ul>
_x000D_
If you use XCode
5 you should do it in a different way.
UIViewController
in UIStoryboard
Identity Inspector
on the right top paneUse Storyboard ID
checkboxStoryboard ID
fieldThen write your code.
// Override point for customization after application launch.
if (<your implementation>) {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"
bundle: nil];
YourViewController *yourController = (YourViewController *)[mainStoryboard
instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
self.window.rootViewController = yourController;
}
return YES;
In fact, it's normal that you have a 404 error when refreshing your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.
To fix the 404 error, you need to update your server to serve the index.html
file for each route path you defined.
If you want to switch to the HashBang approach, you need to use this configuration:
import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
import {MyApp} from './myapp';
bootstrap(MyApp, [
ROUTER_PROVIDERS,
{provide: LocationStrategy, useClass: HashLocationStrategy}
]);
In this case, when you refresh the page, it will be displayed again (but you will have a #
in your address).
This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.
Hope it helps you, Thierry
You can also specify the exact values for each gr
0 2,10,12,14,16,18,20 * * *
It stands for 2h00, 10h00, 12h00 and so on, till 20h00.
From the above answer, we have:
The comma, ",", means "and". If you are confused by the above line, remember that spaces are the field separators, not commas.
And from (Wikipedia page):
* * * * * command to be executed
- - - - -
¦ ¦ ¦ ¦ ¦
¦ ¦ ¦ ¦ ¦
¦ ¦ ¦ ¦ +----- day of week (0 - 7) (0 or 7 are Sunday, or use names)
¦ ¦ ¦ +---------- month (1 - 12)
¦ ¦ +--------------- day of month (1 - 31)
¦ +-------------------- hour (0 - 23)
+------------------------- min (0 - 59)
Hope it helps :)
--
EDIT:
try Escpos for PHP POS printing use https://github.com/mike42/escpos-php
This is best done in the MenuItemDataBound.
protected void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
if (!Page.User.IsInRole("Admin"))
{
if (e.Item.NavigateUrl.Equals("/admin"))
{
if (e.Item.Parent != null)
{
MenuItem menu = e.Item.Parent;
menu.ChildItems.Remove(e.Item);
}
else
{
Menu menu = (Menu)sender;
menu.Items.Remove(e.Item);
}
}
}
}
Because the example used the NavigateUrl it is not language specific and works on sites with localized site maps.
To create a unique file path if its exist, use random package to generate a new string name for file. You may refer below code for same.
import os
import random
import string
def getUniquePath(folder, filename):
path = os.path.join(folder, filename)
while os.path.exists(path):
path = path.split('.')[0] + ''.join(random.choice(string.ascii_lowercase) for i in range(10)) + '.' + path.split('.')[1]
return path
Now you can use this path to create file accordingly.
Change maxDate to current date
maxDate: new Date()
It will set current date as maximum value.
You're comparing apples to oranges here:
webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.
So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).
Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:
basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security
wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network
For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding
const style1 = {
backgroundColor: "#2196F3",
}
const style2 = {
color: "white",
}
const someComponent = () => {
return <div style={{ ...style1, ...style2 }}>This has 2 separate styles</div>
}
Note the double curly brackets. The spread operator is your friend.
Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use
c.set(year, month - 1, day, 0, 0);
Once you have the flattened DataFrame
obtained by the accepted answer, you can make the columns a MultiIndex
("fancy multiline header") like this:
df.columns = pd.MultiIndex.from_tuples([tuple(c.split('.')) for c in df.columns])
You can (should) declare it as extern
in a header file, and define it in exactly 1 .c file.
Note that that .c file should also use the header and that the standard pattern looks like:
// file.h
extern int x; // declaration
// file.c
#include "file.h"
int x = 1; // definition and re-declaration
If you want to ONLY count the documents with sent_at
defined with a value of null
(don't count the documents with sent_at
not set):
db.emails.count({sent_at: { $type: 10 }})
left: initial
This will also set left
back to the browser default.
But important to know property: initial
is not supported in IE.
But can I abort a Task (in .Net 4.0) in the same way not by cancellation mechanism. I want to kill the Task immediately.
Other answerers have told you not to do it. But yes, you can do it. You can supply Thread.Abort()
as the delegate to be called by the Task's cancellation mechanism. Here is how you could configure this:
class HardAborter
{
public bool WasAborted { get; private set; }
private CancellationTokenSource Canceller { get; set; }
private Task<object> Worker { get; set; }
public void Start(Func<object> DoFunc)
{
WasAborted = false;
// start a task with a means to do a hard abort (unsafe!)
Canceller = new CancellationTokenSource();
Worker = Task.Factory.StartNew(() =>
{
try
{
// specify this thread's Abort() as the cancel delegate
using (Canceller.Token.Register(Thread.CurrentThread.Abort))
{
return DoFunc();
}
}
catch (ThreadAbortException)
{
WasAborted = true;
return false;
}
}, Canceller.Token);
}
public void Abort()
{
Canceller.Cancel();
}
}
disclaimer: don't do this.
Here is an example of what not to do:
var doNotDoThis = new HardAborter();
// start a thread writing to the console
doNotDoThis.Start(() =>
{
while (true)
{
Thread.Sleep(100);
Console.Write(".");
}
return null;
});
// wait a second to see some output and show the WasAborted value as false
Thread.Sleep(1000);
Console.WriteLine("WasAborted: " + doNotDoThis.WasAborted);
// wait another second, abort, and print the time
Thread.Sleep(1000);
doNotDoThis.Abort();
Console.WriteLine("Abort triggered at " + DateTime.Now);
// wait until the abort finishes and print the time
while (!doNotDoThis.WasAborted) { Thread.CurrentThread.Join(0); }
Console.WriteLine("WasAborted: " + doNotDoThis.WasAborted + " at " + DateTime.Now);
Console.ReadKey();
UPDATE:
[o for d in [{}] for o in lst if o.name != "" or d.setdefault("", o) == o]
or using filter
and lambda
:
flag = {}
filter(lambda o: bool(o.name) or flag.setdefault("", o) == o, lst)
Previous Answer
OK, are you stuck on using filter and lambda?
It seems like this would be better served with a dictionary comprehension,
{o.name : o for o in input}.values()
I think the reason that Python doesn't allow assignment in a lambda is similar to why it doesn't allow assignment in a comprehension and that's got something to do with the fact that these things are evaluated on the C
side and thus can give us an increase in speed. At least that's my impression after reading one of Guido's essays.
My guess is this would also go against the philosophy of having one right way of doing any one thing in Python.
Adding to Andy's answer, there is additional utility to git rm
:
Safety: When doing git rm
instead of rm
, Git will block the removal if there is a discrepancy between the HEAD
version of a file and the staging index or working tree version. This block is a safety mechanism to prevent removal of in-progress changes.
Safeguarding: git rm --dry-run
. This option is a safeguard that will execute the git rm
command but not actually delete the files. Instead it will output which files it would have removed.
AES.
(I also am assuming you mean twofish not the much older and weaker blowfish)
Both (AES & twofish) are good algorithms. However even if they were equal or twofish was slightly ahead on technical merit I would STILL chose AES.
Why? Publicity. AES is THE standard for government encryption and thus millions of other entities also use it. A talented cryptanalyst simply gets more "bang for the buck" finding a flaw in AES then it does for the much less know and used twofish.
Obscurity provides no protection in encryption. More bodies looking, studying, probing, attacking an algorithm is always better. You want the most "vetted" algorithm possible and right now that is AES. If an algorithm isn't subject to intense and continual scrutiny you should place a lower confidence of it's strength. Sure twofish hasn't been compromised. Is that because of the strength of the cipher or simply because not enough people have taken a close look ..... YET
Just Try This :
textfield.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
if(textfield.getText().length()>=5&&!(evt.getKeyChar()==KeyEvent.VK_DELETE||evt.getKeyChar()==KeyEvent.VK_BACK_SPACE)) {
getToolkit().beep();
evt.consume();
}
}
});
My fix for this on Mountain Lion was: -
npm install -g grunt-cli
Saw it on http://gruntjs.com/getting-started
JPG does not support a transparent background, you can easily convert it to a PNG which does support a transparent background by opening it in near any photo editor and save it as a.PNG
If all images are of the same format:
import cv2
import glob
images = [cv2.imread(file) for file in glob.glob('path/to/files/*.jpg')]
For reading images of different formats:
import cv2
import glob
imdir = 'path/to/files/'
ext = ['png', 'jpg', 'gif'] # Add image formats here
files = []
[files.extend(glob.glob(imdir + '*.' + e)) for e in ext]
images = [cv2.imread(file) for file in files]
Here's another way:
NSDate *now = [NSDate date];
//maybe not 100% approved, but it works in English. You could localize if necessary
NSDate *midnight = [NSDate dateWithNaturalLanguageString:@"midnight tomorrow"];
//num of seconds between mid and now
NSTimeInterval timeInt = [midnight timeIntervalSinceDate:now];
int hours = (int) timeInt/3600;
int minutes = ((int) timeInt % 3600) / 60;
int seconds = (int) timeInt % 60;
You lose subsecond precision with the cast of the NSTimeInterval to an int, but that shouldn't matter.
Here is an easy and short method
document.getElementById('elementID').selectedOptions[0].innerHTML
Like it's written up there, you forget to type #include <sstream>
#include <sstream>
using namespace std;
QString Stats_Manager::convertInt(int num)
{
stringstream ss;
ss << num;
return ss.str();
}
You can also use some other ways to convert int
to string
, like
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
check this!
A few of the options are deprecated as of today. So watch out for those.
If you try <input onkeypress="blockSpecialCharacters(event)" />
, an IDE like WebStorm
will slash out event and tell you:
Deprecated symbol used, consults docs for better alternative
Then when you get to the JavaScript, console.log(e.keyCode)
will also give keyCode and say:
Deprecated symbol used, consults docs for better alternative
Anyways I did it using jQuery.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<input id="theInput" />
<script>
function blockSpecialCharacters(e) {
let key = e.key;
let keyCharCode = key.charCodeAt(0);
// 0-9
if(keyCharCode >= 48 && keyCharCode <= 57) {
return key;
}
// A-Z
if(keyCharCode >= 65 && keyCharCode <= 90) {
return key;
}
// a-z
if(keyCharCode >= 97 && keyCharCode <= 122) {
return key;
}
return false;
}
$('#theInput').keypress(function(e) {
blockSpecialCharacters(e);
});
</script>
I prefer to use ==
instead of equals
:
Other reason, in addition to the others already discussed here, is you could introduce a bug without realizing it. Suppose you have this enums which is exactly the same but in separated pacakges (it's not common, but it could happen):
First enum:
package first.pckg
public enum Category {
JAZZ,
ROCK,
POP,
POP_ROCK
}
Second enum:
package second.pckg
public enum Category {
JAZZ,
ROCK,
POP,
POP_ROCK
}
Then suppose you use the equals like next in item.category
which is first.pckg.Category
but you import the second enum (second.pckg.Category
) instead the first without realizing it:
import second.pckg.Category;
...
Category.JAZZ.equals(item.getCategory())
So you will get allways false
due is a different enum although you expect true because item.getCategory()
is JAZZ
. And it could be be a bit difficult to see.
So, if you instead use the operator ==
you will have a compilation error:
operator == cannot be applied to "second.pckg.Category", "first.pckg.Category"
import second.pckg.Category;
...
Category.JAZZ == item.getCategory()
There's no need to downgrade Chrome anymore, when you get this error only means it's time to run webdriver-manager update
again
The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not during processing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib
) <c:out>
tag or fn:escapeXml
function for this. E.g.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>
and
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">
That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).
If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. &
would become &amp;
instead of &
so that the enduser would literally see &
instead of &
in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.
json:
[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]
c# code: to take only a single value, for example the word "bike".
//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]
dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
string Text = stuff1[0].hws[2];
Console.WriteLine(Text);
output:
bike
Egypt Development Blog : Get value of checked item in CheckedListBox in vb.net
after bind CheckedListBox with data you can get value of checked items
For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(i), DataRowView)
Dim XDR As DataRow = XDRV.Row
Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
Dim XValueMember As String = XDR(CheckedListBox1.ValueMember).ToString()
MsgBox("DisplayMember : " & XDisplayMember & " - ValueMember : " & XValueMember )
Next
now you can use the value or Display of checked items in CheckedListBox from the 2 variable XDisplayMember And XValueMember in the loop
hope to be useful.
Page
is a special case handler.
Generic Web handler (*.ashx
, extension based processor) is the default HTTP handler for all Web handlers that do not have a UI and that include the @WebHandler
directive.
ASP.NET page handler (*.aspx
) is the default HTTP handler for all ASP.NET pages.
Among the built-in HTTP handlers there are also Web service handler (*.asmx
) and Trace handler (trace.axd
)
MSDN says:
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.
The image below illustrates this:
As to your second question:
Does ashx handle more connections than aspx?
Don't think so (but for sure, at least not less than).
I did it with an ajax post and then returned using a data url:
$(document).ready(function () {
var exportClick = function () {
$.ajax({
url: "/api/test.php",
type: "POST",
dataType: "text",
data: {
action: "getCSV",
filter: "name = 'smith'",
},
success: function(data) {
var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
w.focus();
},
error: function () {
alert('Problem getting data');
},
});
}
});
Here is an answer to your question that goes into detail: http://www.velocityreviews.com/forums/t372598-maximum-size-of-byte-array.html
You may want to mention which version of .NET you are using and your memory size.
You will be stuck to a 2G, for your application, limit though, so it depends on what is in your array.
git add .
git commit -m "initial commit"
git config --local credential.helper ""
git push https://github.com/youraccount/repo.git --all
After this push command, a username password prompt will be opened.
Try following css with addition of white-space
:
span {
display: block;
word-wrap:break-word;
width: 50px;
white-space: normal
}
After reading the answer from Gilles, I decided to see if the $BASH_COMMAND
var was also available (and the desired value) in an EXIT
trap - and it is!
So, the following bash script works as expected:
#!/bin/bash
exit_trap () {
local lc="$BASH_COMMAND" rc=$?
echo "Command [$lc] exited with code [$rc]"
}
trap exit_trap EXIT
set -e
echo "foo"
false 12345
echo "bar"
The output is
foo
Command [false 12345] exited with code [1]
bar
is never printed because set -e
causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345
passed to false
is just there to show that the arguments to the failed command are captured as well (the false
command ignores any arguments passed to it)
Even after doing all the method suggested, i was getting the same error. After trying hard, i got to know that hibernate's maven dependency was added in my pom.xml, as i removed it, application started successfully.
I removed this dependency:
<dependency> <groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
If no provider is enabled, "passive" is the best provider returned. See https://stackoverflow.com/a/4519414/621690
public boolean isLocationServiceEnabled() {
LocationManager lm = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
String provider = lm.getBestProvider(new Criteria(), true);
return (StringUtils.isNotBlank(provider) &&
!LocationManager.PASSIVE_PROVIDER.equals(provider));
}
You want $_SERVER['REQUEST_URI']
. From the docs:
'REQUEST_URI'
The URI which was given in order to access this page; for instance,
'/index.html'
.
The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:
DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '
SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT name
FROM sysobjects
WHERE xtype = 'PK'
AND parent_obj = OBJECT_ID('Student')))
EXEC (@SQL)
//You can convert DataView to Table. using DataView.ToTable();
foreach (DataRow drGroup in dtGroups.Rows)
{
dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";
if (dtForms.DefaultView.Count > 0)
{
foreach (DataRow drForm in dtForms.DefaultView.ToTable().Rows)
{
drNew = dtNew.NewRow();
drNew["FormId"] = drForm["FormId"];
drNew["FormCaption"] = drForm["FormCaption"];
drNew["GroupName"] = drGroup["GroupName"];
dtNew.Rows.Add(drNew);
}
}
}
// Or You Can Use
// 2.
dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";
DataTable DTFormFilter = dtForms.DefaultView.ToTable();
foreach (DataRow drFormFilter in DTFormFilter.Rows)
{
//Your logic goes here
}
I am not sure in your case. But as I know to run any jar file from cmd we can use following command:
Go up to the directory where your jar file is saved:
java -jar <jarfilename>.jar
But you can check following links. I hope it'll help you:
Run Netbeans maven project from command-line?
http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html
in the received page you can use:
parse_str($str, $array); var_dump($array);
void getFilesList(String filePath,String extension, vector<string> & returnFileName)
{
WIN32_FIND_DATA fileInfo;
HANDLE hFind;
String fullPath = filePath + extension;
hFind = FindFirstFile(fullPath.c_str(), &fileInfo);
if (hFind == INVALID_HANDLE_VALUE){return;}
else {
return FileName.push_back(filePath+fileInfo.cFileName);
while (FindNextFile(hFind, &fileInfo) != 0){
return FileName.push_back(filePath+fileInfo.cFileName);}
}
}
String optfileName ="";
String inputFolderPath ="";
String extension = "*.jpg*";
getFilesList(inputFolderPath,extension,filesPaths);
vector<string>::const_iterator it = filesPaths.begin();
while( it != filesPaths.end())
{
frame = imread(*it);//read file names
//doyourwork here ( frame );
sprintf(buf, "%s/Out/%d.jpg", optfileName.c_str(),it->c_str());
imwrite(buf,frame);
it++;
}
Put this code in your activity
if (id==R.id.uz)
{
LocaleHelper.setLocale(MainActivity.this, mLanguageCode);
//It is required to recreate the activity to reflect the change in UI.
recreate();
return true;
}
if (id == R.id.ru) {
LocaleHelper.setLocale(MainActivity.this, mLanguageCode);
//It is required to recreate the activity to reflect the change in UI.
recreate();
}
@Xeon06, nice but just as a fyi for those that read this thread and tried like me...
when returning the array from php => json_encode($theArray)
. converts to a string which to me isn't easy to manipulate esp for soft js users like myself.
Inside js, you are trying to get the array values and/or keys of the array u r better off using JSON.parse as in var jsArray = JSON.parse(data)
where data is return array from php. the json encoded string is converted to js object that can now be manipulated easily.
e.g. foo={one:1, two:2, three:3} - gotten after JSON.parse
for (key in foo){ console.log("foo["+ key +"]="+ foo[key]) }
- prints to ur firebug console. voila!
This will remove it - short and clean:
.btn {
outline: none !important;
}
This is an example of using the :checked
pseudo-class to make forms more accessible. The :checked
pseudo-class can be used with hidden inputs and their visible labels to build interactive widgets, such as image galleries. I created the snipped for the people that wanna test.
input[type=checkbox] + label {_x000D_
color: #ccc;_x000D_
font-style: italic;_x000D_
} _x000D_
input[type=checkbox]:checked + label {_x000D_
color: #f00;_x000D_
font-style: normal;_x000D_
}
_x000D_
<input type="checkbox" id="cb_name" name="cb_name"> _x000D_
<label for="cb_name">CSS is Awesome</label>
_x000D_
I was getting lazyLoading exceptions on my entity because I was trying to access a lazy loaded collection that was in session.
What I would do was in a separate request, retrieve the entity from session and then try to access a collection in my jsp page which was problematic.
To alleviate this, I updated the same entity in my controller and passed it to my jsp, although I imagine when I re-saved in session that it will also be accessible though SessionScope
and not throw a LazyLoadingException
, a modification of example 2:
The following has worked for me:
// scenario 2 MY WAY
// tran starts
e = new MyEntity();
e = em.merge(e); // re-assign to the same entity "e"
//access e from jsp and it will work dandy!!
Goes to the right and can be used the same way for the left
.yourComponent
{
float: right;
bottom: 0;
}
You can redirect output to a file and then read the file:
return = WshShell.Run("cmd /c C:\snmpset -c ... > c:\temp\output.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
text = file.ReadAll
file.Close
Here is how to build a function that returns a result set that can be queried as if it were a table:
SQL> create type emp_obj is object (empno number, ename varchar2(10));
2 /
Type created.
SQL> create type emp_tab is table of emp_obj;
2 /
Type created.
SQL> create or replace function all_emps return emp_tab
2 is
3 l_emp_tab emp_tab := emp_tab();
4 n integer := 0;
5 begin
6 for r in (select empno, ename from emp)
7 loop
8 l_emp_tab.extend;
9 n := n + 1;
10 l_emp_tab(n) := emp_obj(r.empno, r.ename);
11 end loop;
12 return l_emp_tab;
13 end;
14 /
Function created.
SQL> select * from table (all_emps);
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7902 FORD
7934 MILLER
I would recommend 422. It's not part of the main HTTP spec, but it is defined by a public standard (WebDAV) and it should be treated by browsers the same as any other 4xx status code.
From RFC 4918:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
this is for objective c add your segmented control name in place of mysegmentedcontrol
UIFont *font = [UIFont systemFontOfSize:11.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
forKey:UITextAttributeFont];
[mySegmentedcontrol setTitleTextAttributes:attributes forState:UIControlStateNormal];
hope it helps
Dimension a variable, basically you are telling the compiler that you are going to need a variable of this type at some point.
jQuery: Use this as a starting point - as inspiration. I solved it like this: (this is not a perfect solution, it just aborts the last instance and is WIP code)
var singleAjax = function singleAjax_constructor(url, params) {
// remember last jQuery's get request
if (this.lastInstance) {
this.lastInstance.abort(); // triggers .always() and .fail()
this.lastInstance = false;
}
// how to use Deferred : http://api.jquery.com/category/deferred-object/
var $def = new $.Deferred();
// pass the deferrer's request handlers into the get response handlers
this.lastInstance = $.get(url, params)
.fail($def.reject) // triggers .always() and .fail()
.success($def.resolve); // triggers .always() and .done()
// return the deferrer's "control object", the promise object
return $def.promise();
}
// initiate first call
singleAjax('/ajax.php', {a: 1, b: 2})
.always(function(a,b,c) {console && console.log(a,b,c);});
// second call kills first one
singleAjax('/ajax.php', {a: 1, b: 2})
.always(function(a,b,c) {console && console.log(a,b,c);});
// here you might use .always() .fail() .success() etc.
There is a solution:
<resources>
<item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>
In this way, your float number will be under @dimen. Notice that you can use other "format" and/or "type" modifiers, where format stands for:
Format = enclosing data type:
and type stands for:
Type = resource type (referenced with R.XXXXX.name):
To fetch resource from code, you should use this snippet:
TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();
I know that this is confusing (you'd expect call like getResources().getDimension(R.dimen.text_line_spacing)
), but Android dimensions
have special treatment and pure "float" number is not valid dimension.
Additionally, there is small "hack" to put float number into dimension, but be WARNED that this is really hack, and you are risking chance to lose float range and precision.
<resources>
<dimen name="text_line_spacing">2.025px</dimen>
</resources>
and from code, you can get that float by
float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);
in this case, value of lineSpacing
is 2.024993896484375
, and not 2.025
as you would expected.
There is a problem with every answer provided that can be summarized as "just add this magical incantation to the beginning of your script. See what you can do with just a line or two of code." They will not work in every possible situation!
For example, one such magical incantation uses __file__
. Unfortunately, if you package your script using cx_Freeze or you are using IDLE, this will result in an exception.
Another such magical incantation uses os.getcwd(). This will only work if you are running your script from the command prompt and the directory containing your script is the current working directory (that is you used the cd command to change into the directory prior to running the script). Eh gods! I hope I do not have to explain why this will not work if your Python script is in the PATH somewhere and you ran it by simply typing the name of your script file.
Fortunately, there is a magical incantation that will work in all the cases I have tested. Unfortunately, the magical incantation is more than just a line or two of code.
import inspect
import os
import sys
# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.
def GetScriptDirectory():
if hasattr(GetScriptDirectory, "dir"):
return GetScriptDirectory.dir
module_path = ""
try:
# The easy way. Just use __file__.
# Unfortunately, __file__ is not available when cx_Freeze is used or in IDLE.
module_path = __file__
except NameError:
if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
module_path = sys.argv[0]
else:
module_path = os.path.abspath(inspect.getfile(GetScriptDirectory))
if not os.path.exists(module_path):
# If cx_Freeze is used the value of the module_path variable at this point is in the following format.
# {PathToExeFile}\{NameOfPythonSourceFile}. This makes it necessary to strip off the file name to get the correct
# path.
module_path = os.path.dirname(module_path)
GetScriptDirectory.dir = os.path.dirname(module_path)
return GetScriptDirectory.dir
sys.path.append(os.path.join(GetScriptDirectory(), "lib"))
print(GetScriptDirectory())
print(sys.path)
As you can see, this is no easy task!
Start by Comparing the distance between latitudes. Each degree of latitude is approximately 69 miles (111 kilometers) apart. The range varies (due to the earth's slightly ellipsoid shape) from 68.703 miles (110.567 km) at the equator to 69.407 (111.699 km) at the poles. The distance between two locations will be equal or larger than the distance between their latitudes.
Note that this is not true for longitudes - the length of each degree of longitude is dependent on the latitude. However, if your data is bounded to some area (a single country for example) - you can calculate a minimal and maximal bounds for the longitudes as well.
Continue will a low-accuracy, fast distance calculation that assumes spherical earth:
The great circle distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by:
d = acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))
A mathematically equivalent formula, which is less subject to rounding error for short distances is:
d = 2*asin(sqrt((sin((lat1-lat2)/2))^2 +
cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
d is the distance in radians
distance_km ˜ radius_km * distance_radians ˜ 6371 * d
(6371 km is the average radius of the earth)
This method computational requirements are mimimal. However the result is very accurate for small distances.
Then, if it is in a given distance, more or less, use a more accurate method.
GeographicLib is the most accurate implementation I know, though Vincenty inverse formula may be used as well.
If you are using an RDBMS, set the latitude as the primary key and the longitude as a secondary key. Query for a latitude range, or for a latitude/longitude range, as described above, then calculate the exact distances for the result set.
Note that modern versions of all major RDBMSs support geographical data-types and queries natively.
This is made to assign a default value, in this case the value of y
, if the x
variable is falsy.
The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.
The Logical OR operator (||
) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.
For example:
"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"
Falsy values are those who coerce to false
when used in boolean context, and they are 0
, null
, undefined
, an empty string, NaN
and of course false
.
I had the same problem, except I have a table with 2 billion rows, so the log file would grow to no end if I did this, even with the recovery model set to Bulk-Logging:
insert into newtable select * from oldtable
So I operate on blocks of data. This way, if the transfer is interupted, you just restart it. Also, you don't need a log file as big as the table. You also seem to get less tempdb I/O, not sure why.
set identity_insert newtable on
DECLARE @StartID bigint, @LastID bigint, @EndID bigint
select @StartID = isNull(max(id),0) + 1
from newtable
select @LastID = max(ID)
from oldtable
while @StartID < @LastID
begin
set @EndID = @StartID + 1000000
insert into newtable (FIELDS,GO,HERE)
select FIELDS,GO,HERE from oldtable (NOLOCK)
where id BETWEEN @StartID AND @EndId
set @StartID = @EndID + 1
end
set identity_insert newtable off
go
You might need to change how you deal with IDs, this works best if your table is clustered by ID.
I found this query to be easy to use & quick.
select schema_name(tab.schema_id) + '.' + tab.name as [table],
cast(sum(spc.used_pages * 8)/1024.00 as numeric(36, 2)) as used_mb,
cast(sum(spc.total_pages * 8)/1024.00 as numeric(36, 2)) as allocated_mb
from sys.tables (nolock) tab
inner join sys.indexes (nolock) ind
on tab.object_id = ind.object_id
inner join sys.partitions (nolock) part
on ind.object_id = part.object_id and ind.index_id = part.index_id
inner join sys.allocation_units (nolock) spc
on part.partition_id = spc.container_id
group by schema_name(tab.schema_id) + '.' + tab.name
order by sum(spc.used_pages) desc
It's not relative to performance...
You set async to false, when you need that ajax request to be completed before the browser passes to other codes:
<script>
// ...
$.ajax(... async: false ...); // Hey browser! first complete this request,
// then go for other codes
$.ajax(...); // Executed after the completion of the previous async:false request.
</script>
FileNameOnly = Dir(.SelectedItems(1))
No nonsense script this:
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
EXEC sp_MSforeachtable 'DBCC CHECKIDENT ( ''?'', RESEED, 0)'
GO
Truncate will still not work if you have foreign keys in tables. This script will reset all identity columns as well.
Kotlin's way -
fun Context.bitMapFromImgUrl(imageUrl: String, callBack: (bitMap: Bitmap) -> Unit) {
GlideApp.with(this)
.asBitmap()
.load(imageUrl)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
callBack(resource)
}
override fun onLoadCleared(placeholder: Drawable?) {
// this is called when imageView is cleared on lifecycle call or for
// some other reason.
// if you are referencing the bitmap somewhere else too other than this imageView
// clear it here as you can no longer have the bitmap
}
})
}
The substitute of fcntl
on windows are win32api
calls. The usage is completely different. It is not some switch you can just flip.
In other words, porting a fcntl
-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl
call does and then find the equivalent win32api
code, if any.
There's also the possibility that some code using fcntl
has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.
If you provide more details about the fcntl
calls people can find windows equivalents.
The following worked for Laravel 7.x (and should probably work for any other version as well given the nature of the issue).
npm uninstall --save-dev cross-env
npm install -g cross-env
Just moving cross-env from being a local devDependency to a globally available package.
I had same issue while moving from AWS to Azure
For express & aws, you can already use, existing time() and timeEnd()
For Azure, use this: https://github.com/manoharreddyporeddy/my-nodejs-notes/blob/master/performance_timers_helper_nodejs_azure_aws.js
These time() and timeEnd() use the existing hrtime() function, which give high-resolution real time.
Hope this helps.
You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).
The answer that i am presenting is very simple, instead of using "px","em" or "%", i'll use "vw". In short it might look like this:- h1 {font-size: 5.9vw;} when used for heading purposes.
See this:Demo
For more details:Main tutorial
Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).
Without using a visual selection, gU<motion>
will make the characters in motion
uppercase, or use gu<motion>
for lowercase.
For more of these, see Section 3 in Vim's change.txt help file.
cURL > 7.18.0 has an option --data-urlencode
which solves this problem. Using this, I can simply send a POST request as
curl -d name=john --data-urlencode passwd=@31&3*J https://www.mysite.com
You need to modify your function as:
function toggleTable()
{
if (document.getElementById("loginTable").style.display == "table" ) {
document.getElementById("loginTable").style.display="none";
} else {
document.getElementById("loginTable").style.display="table";
}
currently it is checking based on the boolean
parameter, you don't have to pass the parameter with your function.
You need to modify your anchor tag as:
<a id="loginLink" onclick="toggleTable();" href="#">Login</a>
protocol CustomError : Error {
var localizedTitle: String
var localizedDescription: String
}
enum RequestError : Int, CustomError {
case badRequest = 400
case loginFailed = 401
case userDisabled = 403
case notFound = 404
case methodNotAllowed = 405
case serverError = 500
case noConnection = -1009
case timeOutError = -1001
}
func anything(errorCode: Int) -> CustomError? {
return RequestError(rawValue: errorCode)
}
HTML:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>
JS:
function clearField(input) {
if(input.value=="Name") { //Only clear if value is "Name"
input.value = "";
}
}
function fillField(input) {
if(input.value=="") {
input.value = "Name";
}
}
This problem is generally caused by the website/intranet URL being placed in one of:
On corporate networks, these compatibility view settings are often controlled centrally via group policy. In your case, Enterprise Mode appears to be the culprit.
Unfortunately setting META X-UA-Compatible
will not override this.
Sometimes the only way for end-users to override this is to press F12 and change the Document Mode under the Emulation Tab. However this setting is not permanent and may revert once Developer Tools is closed.
You can also try to exclude your site from the Intranet zone. But the list of domains which belong to the Intranet zone is usually also controlled by the group policy, so the chance of this working is slim.
To see the list of domains that belong to the Intranet zone, go to:
Tools -> Internet Options -> Security -> Sites -> Advanced
If the list contains your subdomain and is greyed out, then you will not be able to override compatibility view until your network admin allows it.
You really need to contact your network administrator to allow changing the compatibility view settings in the group policy.
Loading the website with Developer Tools open (F12) will often report the reason that IE is switching to an older mode.
All 3 settings mentioned above are generally controlled via Group Policy, although can sometimes be overridden on user machines.
If Enterprise Mode is the issue (as appears to be the case for the original poster), the following two articles might be helpful:
Are you using platform.system
?
system() Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. An empty string is returned if the value cannot be determined.
If that isn't working, maybe try platform.win32_ver
and if it doesn't raise an exception, you're on Windows; but I don't know if that's forward compatible to 64-bit, since it has 32 in the name.
win32_ver(release='', version='', csd='', ptype='') Get additional version information from the Windows Registry and return a tuple (version,csd,ptype) referring to version number, CSD level and OS type (multi/single processor).
But os.name
is probably the way to go, as others have mentioned.
if sys.platform == 'win32':
#---------
if os.environ.get('OS','') == 'Windows_NT':
#---------
try: import win32api
#---------
# Emulation using _winreg (added in Python 2.0) and
# sys.getwindowsversion() (added in Python 2.3)
import _winreg
GetVersionEx = sys.getwindowsversion
#----------
def system():
""" Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
An empty string is returned if the value cannot be determined.
"""
return uname()[0]
Make sure Apache didn't get Disabled in Services (Control panel, Admin Tools, Services). If it's Disabled then Set it to Manual and it should run. That was my case, I found Apache Disabled.
Let me give you a very plain Node.js style example of using a callback:
/**
* Function expects these arguments:
* 2 numbers and a callback function(err, result)
*/
var myTest = function(arg1, arg2, callback) {
if (typeof arg1 !== "number") {
return callback('Arg 1 is not a number!', null); // Args: 1)Error, 2)No result
}
if (typeof arg2 !== "number") {
return callback('Arg 2 is not a number!', null); // Args: 1)Error, 2)No result
}
if (arg1 === arg2) {
// Do somethign complex here..
callback(null, 'Actions ended, arg1 was equal to arg2'); // Args: 1)No error, 2)Result
} else if (arg1 > arg2) {
// Do somethign complex here..
callback(null, 'Actions ended, arg1 was > from arg2'); // Args: 1)No error, 2)Result
} else {
// Do somethign else complex here..
callback(null, 'Actions ended, arg1 was < from arg2'); // Args: 1)No error, 2)Result
}
};
/**
* Call it this way:
* Third argument is an anonymous function with 2 args for error and result
*/
myTest(3, 6, function(err, result) {
var resultElement = document.getElementById("my_result");
if (err) {
resultElement.innerHTML = 'Error! ' + err;
resultElement.style.color = "red";
//throw err; // if you want
} else {
resultElement.innerHTML = 'Result: ' + result;
resultElement.style.color = "green";
}
});
and the HTML that will render the result:
<div id="my_result">
Result will come here!
</div>
You can play with it here: https://jsfiddle.net/q8gnvcts/ - for example try to pass string instead of number: myTest('some string', 6, function(err, result).. and see the result.
I hope this example helps because it represents the very basic idea of callback functions.
This is a procedure to configure run release version
1- Change build variants to release version.
On Linux, see constant INET6_ADDRSTRLEN
(include <arpa/inet.h>
, see man inet_ntop
). On my system (header "in.h"):
#define INET6_ADDRSTRLEN 46
The last character is for terminating NULL, as I belive, so the max length is 45, as other answers.
If your request contains an object like this:
{
"year": 1900,
"month": 1,
"day": 20
}
Then you can use:
data class DateObject(
val day: Int,
val month: Int,
val year: Int
)
class LocalDateConverter : StdConverter<DateObject, LocalDate>() {
override fun convert(value: DateObject): LocalDate {
return value.run { LocalDate.of(year, month, day) }
}
}
Above the field:
@JsonDeserialize(converter = LocalDateConverter::class)
val dateOfBirth: LocalDate
The code is in Kotlin but this would work for Java too of course.
Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.
I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')
I'm basing this on somewhat reading between the lines of: Selecting a Credential Type
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Settings -> Advanced, add url to "Valid OAuth redirect URIs". This works for me.
From Wikipedia:
There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.
Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/
Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).
Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.
you also do something good:
text_empty = df['column name'].str.len() > -1
df.loc[text_empty].index
The results will be the rows which are empty & it's index number.
For whom want to install ext-dom on php 7.1 and up run this command:
sudo apt install php-xml
You can call setScale(newScale, roundingMode)
method three times with changing the newScale value from 4 to 3 to 2 like
First case
BigDecimal a = new BigDecimal("10.12345");
a = a.setScale(4, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.1235
a = a.setScale(3, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.124
a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.12
Second case
BigDecimal a = new BigDecimal("10.12556");
a = a.setScale(4, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.1256
a = a.setScale(3, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.126
a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.13
On this page you can test the performance of each method yourself :)
http://jsperf.com/cast-to-string/2
here, on all machines and browsers, ' "" + str ' is the fastest one, (String)str is the slowest