Because of your initialization wrong.
Don't do like this,
MethodName _methodName;
Do like this,
MethodName _methodName = MethodName();
Add this to your code:
.child { width: 100%; }
We know that a block-level child is supposed to occupy the full width of the parent.
Chrome understands this.
IE11, for whatever reason, wants an explicit request.
Using flex-basis: 100%
or flex: 1
also works.
.parent {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
width: 400px;_x000D_
border: 1px solid red;_x000D_
align-items: center;_x000D_
}_x000D_
.child {_x000D_
border: 1px solid blue;_x000D_
width: calc(100% - 2px); /* NEW; used calc to adjust for parent borders */_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry_x000D_
</div>_x000D_
<div class="child">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry_x000D_
</div>_x000D_
</div>
_x000D_
Note: Sometimes it will be necessary to sort through the various levels of the HTML structure to pinpoint which container gets the width: 100%
. CSS wrap text not working in IE
1.Right click to Gitbash shortcut choose Properties
2.Choose "Shortcut" tab
3.Type your starting directory to "Start in" field
4.Remove "--cd-to-home" part from "Target" field
Edit as of 2016
As of 2016, you can now copy text to the clipboard in most browsers because most browsers have the ability to programmatically copy a selection of text to the clipboard using document.execCommand("copy")
that works off a selection.
As with some other actions in a browser (like opening a new window), the copy to clipboard can only be done via a specific user action (like a mouse click). For example, it cannot be done via a timer.
Here's a code example:
document.getElementById("copyButton").addEventListener("click", function() {_x000D_
copyToClipboard(document.getElementById("copyTarget"));_x000D_
});_x000D_
_x000D_
function copyToClipboard(elem) {_x000D_
// create hidden text element, if it doesn't already exist_x000D_
var targetId = "_hiddenCopyText_";_x000D_
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";_x000D_
var origSelectionStart, origSelectionEnd;_x000D_
if (isInput) {_x000D_
// can just use the original source element for the selection and copy_x000D_
target = elem;_x000D_
origSelectionStart = elem.selectionStart;_x000D_
origSelectionEnd = elem.selectionEnd;_x000D_
} else {_x000D_
// must use a temporary form element for the selection and copy_x000D_
target = document.getElementById(targetId);_x000D_
if (!target) {_x000D_
var target = document.createElement("textarea");_x000D_
target.style.position = "absolute";_x000D_
target.style.left = "-9999px";_x000D_
target.style.top = "0";_x000D_
target.id = targetId;_x000D_
document.body.appendChild(target);_x000D_
}_x000D_
target.textContent = elem.textContent;_x000D_
}_x000D_
// select the content_x000D_
var currentFocus = document.activeElement;_x000D_
target.focus();_x000D_
target.setSelectionRange(0, target.value.length);_x000D_
_x000D_
// copy the selection_x000D_
var succeed;_x000D_
try {_x000D_
succeed = document.execCommand("copy");_x000D_
} catch(e) {_x000D_
succeed = false;_x000D_
}_x000D_
// restore original focus_x000D_
if (currentFocus && typeof currentFocus.focus === "function") {_x000D_
currentFocus.focus();_x000D_
}_x000D_
_x000D_
if (isInput) {_x000D_
// restore prior selection_x000D_
elem.setSelectionRange(origSelectionStart, origSelectionEnd);_x000D_
} else {_x000D_
// clear temporary content_x000D_
target.textContent = "";_x000D_
}_x000D_
return succeed;_x000D_
}
_x000D_
input {_x000D_
width: 400px;_x000D_
}
_x000D_
<input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br>_x000D_
<input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">
_x000D_
Here's a little more advanced demo: https://jsfiddle.net/jfriend00/v9g1x0o6/
And, you can also get a pre-built library that does this for you with clipboard.js.
Old, historical part of answer
Directly copying to the clipboard via JavaScript is not permitted by any modern browser for security reasons. The most common workaround is to use a Flash capability for copying to the clipboard that can only be triggered by a direct user click.
As mentioned already, ZeroClipboard is a popular set of code for managing the Flash object to do the copy. I've used it. If Flash is installed on the browsing device (which rules out mobile or tablet), it works.
The next most common work-around is to just place the clipboard-bound text into an input field, move the focus to that field and advise the user to press Ctrl + C to copy the text.
Other discussions of the issue and possible work-arounds can be found in these prior Stack Overflow posts:
These questions asking for a modern alternative to using Flash have received lots of question upvotes and no answers with a solution (probably because none exist):
Internet Explorer and Firefox used to have non-standard APIs for accessing the clipboard, but their more modern versions have deprecated those methods (probably for security reasons).
There is a nascent standards effort to try to come up with a "safe" way to solve the most common clipboard problems (probably requiring a specific user action like the Flash solution requires), and it looks like it may be partially implemented in the latest versions of Firefox and Chrome, but I haven't confirmed that yet.
To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.
Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.
From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:
E:first-child
, E:hover
, E > F
(Child combinator), E + F
(Adjacent sibling combinator), E ~ F
(General sibling combinator). This unfortunately means resorting to workarounds like inline styles.white-space
won't work.background-image
property won't work.height
, width
, and the max-
versions are either not usable or have bugs for certain elements.display
, float
s and position
are all out).In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.
PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top
" where you probably meant to use vertical-align
. Also: cell-padding
for td
s doesn't exist.
Just add an iframe styled like either option below. I hope this solves the problem.
1st option:
<iframe src="https://www.skyhub.ca/featured-listing" style="position: absolute; visibility: hidden;" onload="this.style.position='static'; this.style.visibility='visible';" scrolling="no" frameborder="0" marginheight="0px" marginwidth="0px" height="400px" width="1200px" allowfullscreen></iframe>
2nd option:
<iframe src="https://www.skyhub.ca/featured-listing" style="display: none;" onload="this.style.display='block';" scrolling="no" frameborder="0" marginheight="0px" marginwidth="0px" height="400px" width="1200px" allowfullscreen></iframe>
Oh, be careful now! All that glitters is NOT gold! All of the “stats” dm views and functions have a problem for this type of thing. They only work against what is in cache and the lifetime of what is in cache can be measure in minutes. If you were to use such a thing to determine which SPs are candidates for being dropped, you could be in for a world of hurt when you delete SPs that were used just minutes ago.
The following excerpts are from Books Online for the given dm views…
sys.dm_exec_procedure_stats Returns aggregate performance statistics for cached stored procedures. The view contains one row per stored procedure, and the lifetime of the row is as long as the stored procedure remains cached. When a stored procedure is removed from the cache, the corresponding row is eliminated from this view.
sys.dm_exec_query_stats The view contains one row per query statement within the cached plan, and the lifetime of the rows are tied to the plan itself. When a plan is removed from the cache, the corresponding rows are eliminated from this view.
This is really more of a serverfault-type question, but you can use netstat.
something like:
# netstat -lpnt | grep 6000 | grep ssh
This will tell you if there's an ssh process listening on the specified port. it will also tell you the PID of the process.
If you really want to double-check that the ssh process was started with the right options, you can then look up the process by PID in something like
# ps aux | grep PID
I had to use the **/* syntax to exclude the files in a folder:
"linterOptions": {
"exclude": [
"src/auto-generated/**/*",
"src/app/auto-generated/**/*"
]
},
if (isset($argv) && is_array($argv)) {
$param = array();
for ($x=1; $x<sizeof($argv);$x++) {
$pattern = '#\/(.+)=(.+)#i';
if (preg_match($pattern, $argv[$x])) {
$key = preg_replace($pattern, '$1', $argv[$x]);
$val = preg_replace($pattern, '$2', $argv[$x]);
$_REQUEST[$key] = $val;
$$key = $val;
}
}
}
I put parameters in $_REQUEST:
$_REQUEST[$key] = $val;
And it is also usable directly:
$$key=$val
Use it like this:
myFile.php /key=val
This should happen automatically, so long as cms, admin and chart are all parts of the repository.
A likely issue is that each of these plugins is a git submodule.
Run git help submodule
for more information.
EDIT
For doing this in bash:
cd plugins
for f in cms admin chart
do
cd $f && git pull origin master && cd ..
done
Your problem is that you have 64-bit eclipse
running but you have 32 bit JRE
.So please download JRE
for 64 bit windows
and let it install on the default location.
Finally add that path till bin in your PATH variable.
Try it should work.
You have two choices, either correct your markup so that it uses correct elements and utilizes the Bootstrap grid system:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<div class="imgAbt">_x000D_
<img width="220" height="220" src="img/me.jpg" />_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-8">_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Or, if you wish the text to closely wrap the image, change your markup to:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<img style='float:left;width:200px;height:200px; margin-right:10px;' src="img/me.jpg" />_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>
_x000D_
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(dBytes);
If you need an empty folder you can loop until you get an empty folder
QString folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
while(QDir(folder).exists())
{
folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
}
QDir().mkdir(folder);
This case you will get a folder name with a number .
Use the object syntax.
v-bind:class="{'fa-checkbox-marked': content['cravings'], 'fa-checkbox-blank-outline': !content['cravings']}"
When the object gets more complicated, extract it into a method.
v-bind:class="getClass()"
methods:{
getClass(){
return {
'fa-checkbox-marked': this.content['cravings'],
'fa-checkbox-blank-outline': !this.content['cravings']}
}
}
Finally, you could make this work for any content property like this.
v-bind:class="getClass('cravings')"
methods:{
getClass(property){
return {
'fa-checkbox-marked': this.content[property],
'fa-checkbox-blank-outline': !this.content[property]
}
}
}
First run your IDE or CMD as Administrator and run the following:
pip install pipwin
pipwin install pyaudio
Here is my working solution :
// --------------------------
// SOAP Message creation
// --------------------------
SOAPMessage sm = MessageFactory.newInstance().createMessage();
sm.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
sm.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
SOAPPart sp = sm.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
se.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
se.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
SOAPBody sb = sm.getSOAPBody();
//
// Add all input fields here ...
//
SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
// -----------------------------------
// URL creation with TimeOut connexion
// -----------------------------------
URL endpoint = new URL(null,
"http://myDomain/myWebService.php",
new URLStreamHandler() { // Anonymous (inline) class
@Override
protected URLConnection openConnection(URL url) throws IOException {
URL clone_url = new URL(url.toString());
HttpURLConnection clone_urlconnection = (HttpURLConnection) clone_url.openConnection();
// TimeOut settings
clone_urlconnection.setConnectTimeout(10000);
clone_urlconnection.setReadTimeout(10000);
return(clone_urlconnection);
}
});
try {
// -----------------
// Send SOAP message
// -----------------
SOAPMessage retour = connection.call(sm, endpoint);
}
catch(Exception e) {
if ((e instanceof com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl) && (e.getCause()!=null) && (e.getCause().getCause()!=null) && (e.getCause().getCause().getCause()!=null)) {
System.err.println("[" + e + "] Error sending SOAP message. Initial error cause = " + e.getCause().getCause().getCause());
}
else {
System.err.println("[" + e + "] Error sending SOAP message.");
}
}
Uninstall Java 8 and clean your JDK_HOME and your JAVA_HOME enviromental paths. Then install 64bit JAVA 6 or 7 JDK of your preference.
I just resolved the same problem.
Dependency Walker is misleading in this case and caused me to lose time. So, the list of "missing" DLL files from the first post is not helpful, and you can probably ignore it.
The solution is to find which references your project is calling and check if they are really installed on the server.
@Ben Brammer, it is not important which three .ocx files are missing, because they are missing only for Leo T Abraham's project. Your project probably calls other DLL files.
In my case, it was not three .ocx files, but missing MySQL connector DLL file. After installing of MySQL Connector for .NET on server, the problem disappeared.
So, in short, the solution is: check if all your project references are there.
R interpreter has a duck-typing memory allocation system. There is no builtin method to tell you the datatype of your pointer to memory. Duck typing is done for speed, but turned out to be a bad idea because now statements such as: print(is.integer(5))
returns FALSE and is.integer(as.integer(5))
returns TRUE. Go figure.
The R-manual on basic types: https://cran.r-project.org/doc/manuals/R-lang.html#Basic-types
The best you can hope for is to write your own function to probe your pointer to memory, then use process of elimination to decide if it is suitable for your needs.
Your object()
needs to be penetrated with get(...)
before you can see inside. Example:
a <- 10
myGlobals <- objects()
for(i in myGlobals){
typeof(i) #prints character
typeof(get(i)) #prints integer
}
The R function typeof
has a bias to give you the type at maximum depth, for example.
library(tibble)
#expression notes type
#----------------------- -------------------------------------- ----------
typeof(TRUE) #a single boolean: logical
typeof(1L) #a single numeric with L postfixed: integer
typeof("foobar") #A single string in double quotes: character
typeof(1) #a single numeric: double
typeof(list(5,6,7)) #a list of numeric: list
typeof(2i) #an imaginary number complex
typeof(5 + 5L) #double + integer is coerced: double
typeof(c()) #an empty vector has no type: NULL
typeof(!5) #a bang before a double: logical
typeof(Inf) #infinity has a type: double
typeof(c(5,6,7)) #a vector containing only doubles: double
typeof(c(c(TRUE))) #a vector of vector of logicals: logical
typeof(matrix(1:10)) #a matrix of doubles has a type: list
typeof(substr("abc",2,2))#a string at index 2 which is 'b' is: character
typeof(c(5L,6L,7L)) #a vector containing only integers: integer
typeof(c(NA,NA,NA)) #a vector containing only NA: logical
typeof(data.frame()) #a data.frame with nothing in it: list
typeof(data.frame(c(3))) #a data.frame with a double in it: list
typeof(c("foobar")) #a vector containing only strings: character
typeof(pi) #builtin expression for pi: double
typeof(1.66) #a single numeric with mantissa: double
typeof(1.66L) #a double with L postfixed double
typeof(c("foobar")) #a vector containing only strings: character
typeof(c(5L, 6L)) #a vector containing only integers: integer
typeof(c(1.5, 2.5)) #a vector containing only doubles: double
typeof(c(1.5, 2.5)) #a vector containing only doubles: double
typeof(c(TRUE, FALSE)) #a vector containing only logicals: logical
typeof(factor()) #an empty factor has default type: integer
typeof(factor(3.14)) #a factor containing doubles: integer
typeof(factor(T, F)) #a factor containing logicals: integer
typeof(Sys.Date()) #builtin R dates: double
typeof(hms::hms(3600)) #hour minute second timestamp double
typeof(c(T, F)) #T and F are builtins: logical
typeof(1:10) #a builtin sequence of numerics: integer
typeof(NA) #The builtin value not available: logical
typeof(c(list(T))) #a vector of lists of logical: list
typeof(list(c(T))) #a list of vectors of logical: list
typeof(c(T, 3.14)) #a vector of logicals and doubles: double
typeof(c(3.14, "foo")) #a vector of doubles and characters: character
typeof(c("foo",list(T))) #a vector of strings and lists: list
typeof(list("foo",c(T))) #a list of strings and vectors: list
typeof(TRUE + 5L) #a logical plus an integer: integer
typeof(c(TRUE, 5L)[1]) #The true is coerced to 1 integer
typeof(c(c(2i), TRUE)[1])#logical coerced to complex: complex
typeof(c(NaN, 'batman')) #NaN's in a vector don't dominate: character
typeof(5 && 4) #doubles are coerced by order of && logical
typeof(8 < 'foobar') #string and double is coerced logical
typeof(list(4, T)[[1]]) #a list retains type at every index: double
typeof(list(4, T)[[2]]) #a list retains type at every index: logical
typeof(2 ** 5) #result of exponentiation double
typeof(0E0) #exponential lol notation double
typeof(0x3fade) #hexidecimal double
typeof(paste(3, '3')) #paste promotes types to string character
typeof(3 + ?) #R pukes on unicode error
typeof(iconv("a", "latin1", "UTF-8")) #UTF-8 characters character
typeof(5 == 5) #result of a comparison: logical
The R function class
has a bias to give you the type of container or structure encapsulating your types, for example.
library(tibble)
#expression notes class
#--------------------- ---------------------------------------- ---------
class(matrix(1:10)) #a matrix of doubles has a class: matrix
class(factor("hi")) #factor of items is: factor
class(TRUE) #a single boolean: logical
class(1L) #a single numeric with L postfixed: integer
class("foobar") #A single string in double quotes: character
class(1) #a single numeric: numeric
class(list(5,6,7)) #a list of numeric: list
class(2i) #an imaginary complex
class(data.frame()) #a data.frame with nothing in it: data.frame
class(Sys.Date()) #builtin R dates: Date
class(sapply) #a function is function
class(charToRaw("hi")) #convert string to raw: raw
class(array("hi")) #array of items is: array
class(5 + 5L) #double + integer is coerced: numeric
class(c()) #an empty vector has no class: NULL
class(!5) #a bang before a double: logical
class(Inf) #infinity has a class: numeric
class(c(5,6,7)) #a vector containing only doubles: numeric
class(c(c(TRUE))) #a vector of vector of logicals: logical
class(substr("abc",2,2))#a string at index 2 which is 'b' is: character
class(c(5L,6L,7L)) #a vector containing only integers: integer
class(c(NA,NA,NA)) #a vector containing only NA: logical
class(data.frame(c(3))) #a data.frame with a double in it: data.frame
class(c("foobar")) #a vector containing only strings: character
class(pi) #builtin expression for pi: numeric
class(1.66) #a single numeric with mantissa: numeric
class(1.66L) #a double with L postfixed numeric
class(c("foobar")) #a vector containing only strings: character
class(c(5L, 6L)) #a vector containing only integers: integer
class(c(1.5, 2.5)) #a vector containing only doubles: numeric
class(c(TRUE, FALSE)) #a vector containing only logicals: logical
class(factor()) #an empty factor has default class: factor
class(factor(3.14)) #a factor containing doubles: factor
class(factor(T, F)) #a factor containing logicals: factor
class(hms::hms(3600)) #hour minute second timestamp hms difftime
class(c(T, F)) #T and F are builtins: logical
class(1:10) #a builtin sequence of numerics: integer
class(NA) #The builtin value not available: logical
class(c(list(T))) #a vector of lists of logical: list
class(list(c(T))) #a list of vectors of logical: list
class(c(T, 3.14)) #a vector of logicals and doubles: numeric
class(c(3.14, "foo")) #a vector of doubles and characters: character
class(c("foo",list(T))) #a vector of strings and lists: list
class(list("foo",c(T))) #a list of strings and vectors: list
class(TRUE + 5L) #a logical plus an integer: integer
class(c(TRUE, 5L)[1]) #The true is coerced to 1 integer
class(c(c(2i), TRUE)[1])#logical coerced to complex: complex
class(c(NaN, 'batman')) #NaN's in a vector don't dominate: character
class(5 && 4) #doubles are coerced by order of && logical
class(8 < 'foobar') #string and double is coerced logical
class(list(4, T)[[1]]) #a list retains class at every index: numeric
class(list(4, T)[[2]]) #a list retains class at every index: logical
class(2 ** 5) #result of exponentiation numeric
class(0E0) #exponential lol notation numeric
class(0x3fade) #hexidecimal numeric
class(paste(3, '3')) #paste promotes class to string character
class(3 + ?) #R pukes on unicode error
class(iconv("a", "latin1", "UTF-8")) #UTF-8 characters character
class(5 == 5) #result of a comparison: logical
storage.mode
of your variable:When an R variable is written to disk, the data layout changes again, and is called the data's storage.mode
. The function storage.mode(...)
reveals this low level information: see Mode, Class, and Type of R objects. You shouldn't need to worry about R's storage.mode unless you are trying to understand delays caused by round trip casts/coercions that occur when assigning and reading data to and from disk.
gettype(your_variable)
:Run this R code then adapt it for your purposes, it'll make a pretty good guess as to what type it is.
get_type <- function(variable){
sz <- as.integer(length(variable)) #length of your variable
tof <- typeof(variable) #typeof your variable
cls <- class(variable) #class of your variable
isc <- is.character(variable) #what is.character() has to say about it.
d <- dim(variable) #dimensions of your variable
isv <- is.vector(variable)
if (is.matrix(variable)){
d <- dim(t(variable)) #dimensions of your matrix
}
#observations ----> datatype
if (sz>=1 && tof == "logical" && cls == "logical" && isv == TRUE){ return("vector of logical") }
if (sz>=1 && tof == "integer" && cls == "integer" ){ return("vector of integer") }
if (sz==1 && tof == "double" && cls == "Date" ){ return("Date") }
if (sz>=1 && tof == "raw" && cls == "raw" ){ return("vector of raw") }
if (sz>=1 && tof == "double" && cls == "numeric" ){ return("vector of double") }
if (sz>=1 && tof == "double" && cls == "array" ){ return("vector of array of double") }
if (sz>=1 && tof == "character" && cls == "array" ){ return("vector of array of character") }
if (sz>=0 && tof == "list" && cls == "data.frame" ){ return("data.frame") }
if (sz>=1 && isc == TRUE && isv == TRUE){ return("vector of character") }
if (sz>=1 && tof == "complex" && cls == "complex" ){ return("vector of complex") }
if (sz==0 && tof == "NULL" && cls == "NULL" ){ return("NULL") }
if (sz>=0 && tof == "integer" && cls == "factor" ){ return("factor") }
if (sz>=1 && tof == "double" && cls == "numeric" && isv == TRUE){ return("vector of double") }
if (sz>=1 && tof == "double" && cls == "matrix"){ return("matrix of double") }
if (sz>=1 && tof == "character" && cls == "matrix"){ return("matrix of character") }
if (sz>=1 && tof == "list" && cls == "list" && isv == TRUE){ return("vector of list") }
if (sz>=1 && tof == "closure" && cls == "function" && isv == FALSE){ return("closure/function") }
return("it's pointer to memory, bruh")
}
assert <- function(a, b){
if (a == b){
cat("P")
}
else{
cat("\nFAIL!!! Sniff test:\n")
sz <- as.integer(length(variable)) #length of your variable
tof <- typeof(variable) #typeof your variable
cls <- class(variable) #class of your variable
isc <- is.character(variable) #what is.character() has to say about it.
d <- dim(variable) #dimensions of your variable
isv <- is.vector(variable)
if (is.matrix(variable)){
d <- dim(t(variable)) #dimensions of your variable
}
if (!is.function(variable)){
print(paste("value: '", variable, "'"))
}
print(paste("get_type said: '", a, "'"))
print(paste("supposed to be: '", b, "'"))
cat("\nYour pointer to memory has properties:\n")
print(paste("sz: '", sz, "'"))
print(paste("tof: '", tof, "'"))
print(paste("cls: '", cls, "'"))
print(paste("d: '", d, "'"))
print(paste("isc: '", isc, "'"))
print(paste("isv: '", isv, "'"))
quit()
}
}
#these asserts give a sample for exercising the code.
assert(get_type(TRUE), "vector of logical") #everything is a vector in R by default.
assert(get_type(c(TRUE)), "vector of logical") #c() just casts to vector
assert(get_type(c(c(TRUE))),"vector of logical") #casting vector multiple times does nothing
assert(get_type(!5), "vector of logical") #bang inflicts 'not truth-like'
assert(get_type(1L), "vector of integer") #naked integers are still vectors of 1
assert(get_type(c(1L, 2L)), "vector of integer") #Longs are not doubles
assert(get_type(c(1L, c(2L, 3L))),"vector of integer") #nested vectors of integers
assert(get_type(c(1L, c(TRUE))), "vector of integer") #logicals coerced to integer
assert(get_type(c(FALSE, c(1L))), "vector of integer") #logicals coerced to integer
assert(get_type("foobar"), "vector of character") #character here means 'string'
assert(get_type(c(1L, "foobar")), "vector of character") #integers are coerced to string
assert(get_type(5), "vector of double")
assert(get_type(5 + 5L), "vector of double")
assert(get_type(Inf), "vector of double")
assert(get_type(c(5,6,7)), "vector of double")
assert(get_type(NaN), "vector of double")
assert(get_type(list(5)), "vector of list") #your list is in a vector.
assert(get_type(list(5,6,7)), "vector of list")
assert(get_type(c(list(5,6,7))),"vector of list")
assert(get_type(list(c(5,6),T)),"vector of list") #vector of list of vector and logical
assert(get_type(list(5,6,7)), "vector of list")
assert(get_type(2i), "vector of complex")
assert(get_type(c(2i, 3i, 4i)), "vector of complex")
assert(get_type(c()), "NULL")
assert(get_type(data.frame()), "data.frame")
assert(get_type(data.frame(4,5)),"data.frame")
assert(get_type(Sys.Date()), "Date")
assert(get_type(sapply), "closure/function")
assert(get_type(charToRaw("hi")),"vector of raw")
assert(get_type(c(charToRaw("a"), charToRaw("b"))), "vector of raw")
assert(get_type(array(4)), "vector of array of double")
assert(get_type(array(4,5)), "vector of array of double")
assert(get_type(array("hi")), "vector of array of character")
assert(get_type(factor()), "factor")
assert(get_type(factor(3.14)), "factor")
assert(get_type(factor(TRUE)), "factor")
assert(get_type(matrix(3,4,5)), "matrix of double")
assert(get_type(as.matrix(5)), "matrix of double")
assert(get_type(matrix("yatta")),"matrix of character")
I put in a C++/Java/Python ideology here that gives me the scoop of what the memory most looks like. R triad typing system is like trying to nail spaghetti to the wall, <-
and <<-
will package your matrix to a list when you least suspect. As the old duck-typing saying goes: If it waddles like a duck and if it quacks like a duck and if it has feathers, then it's a duck.
Or, you can use the Newtownsoft.Json library as follows:
using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);
Where T
is your object type that matches your JSON string.
Most recent solution:
HTML
<div class="parent">
<img src="image.jpg" height="600" width="600"/>
</div>
CSS
.parent {
width: 200px;
height: 200px;
overflow: hidden;
/* Magic */
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
}
We can define maximum pool size in following way:
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>200</max-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
in exemple if you want to compile sources but have objects in an different directory :
You need to do :
gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...
but with most of macros the result will be all objects followed by all sources, like :
gcc -c -o <all OBJ path> <all SRC path>
so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(
the solution is to use these special macros
$@ $<
this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)
$(OBJ):$(SRC)
gcc -c -o $@ $< $(HEADERS) $(FLAGS)
it means :
$@ = $(OBJ)
$< = $(SRC)
but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC
You don't need to do anything, the Model Binding
will pass null
to property without any problem.
Consider this example :
var array = new string[2]
{
"I like what I like",
"I like what you like"
};
//query1 returns two elements sth like this:
//fisrt element would be array[5] :[0] = "I" "like" "what" "I" "like"
//second element would be array[5] :[1] = "I" "like" "what" "you" "like"
IEnumerable<string[]> query1 = array.Select(s => s.Split(' ')).Distinct();
//query2 return back flat result sth like this :
// "I" "like" "what" "you"
IEnumerable<string> query2 = array.SelectMany(s => s.Split(' ')).Distinct();
So as you see duplicate values like "I" or "like" have been removed from query2 because "SelectMany" flattens and projects across multiple sequences. But query1 returns sequence of string arrays. and since there are two different arrays in query1 (first and second element), nothing would be removed.
You have to do write
in the same loop as read
.
I've been using this in Python 3, including pattern matching on the filename.
from pathlib import Path
def latest_file(path: Path, pattern: str = "*"):
files = path.glob(pattern)
return max(files, key=lambda x: x.stat().st_ctime)
If you are using maven try to maven update all projects and force for snapshots. It will clean as well and rebuilt all classpath.. It solved my problem..
The show()
method only affects the display
CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button
element is a button and does not raise a submit
event. You would need to change your selector to the form
for that to work:
$('#login_form').submit(function() {
$('#gif').css('visibility', 'visible');
});
Also note that return true;
is redundant in your logic, so it can be removed.
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
GraalVM is a good choice. I've done Java+Javascript combination with GraalVM for microservice design (Java with Javascript reflection). They recently added support for python, I'd give it a try especially with how big its community has grown over the years.
The problem is the Python module requests
. It can be fixed by
$ sudo apt-get purge python-requests
[now requests and pip gets deinstalled]
$ sudo apt-get install python-requests python-pip
If you have this problem with Python 3, you have to write python3
instead of python
.
chartr
is also convenient for these types of substitutions:
chartr("_", "-", data1$c)
# [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"
Thus, you can just do:
data1$c <- chartr("_", "-", data1$c)
For TSQL I like to encapsulate case statements in an outer apply. This prevents me from having to have the case statement written twice, allows reference to the case statement by alias in future joins and avoids the need for positional references.
select oa.day,
model.name,
attempt.type,
oa.result
COUNT(*) MyCount
FROM attempt attempt, prod_hw_id prod_hw_id, model model
WHERE time >= '2013-11-06 00:00:00'
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
OUTER APPLY (
SELECT CURRENT_DATE-1 AS day,
CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END result
) oa
group by oa.day,
model.name,
attempt.type,
oa.result
order by model.name, attempt.type, oa.result;
I would recommend creating a HashMap
from set A, and then iterating through set B and checking if any element of B is in A. This would run in O(|A|+|B|)
time (as there would be no collisions), whereas retainAll(Collection<?> c)
must run in O(|A|*|B|)
time.
Here is the App Bit Web Server (PHP,MySQL,PMA)
It can run a variety of CMS like Wordpress, Joomla, Drupal, Prestashop, etc. Besides CMS can also run PHP frameworks like Code Igniter, YII, CakePHP, etc. It is the same as WAMP or LAMP or XAMPP on your computer or laptop, but this is for android devices with lighttpd instead of apache.
Image.fromarray -> returns an image object
from PIL import Image
import numpy as np
PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
Your regex should be something like
[0-9\-\(\)\s]+
.
It matches numbers, dashes, parentheses and space.
If you need something more strict, matching just your example, try this:
([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})
Whenever you use
export someobject
and someobject is
{
"prop1":"Property1",
"prop2":"Property2",
}
the above you can import anywhere using import
or module.js
and there you can use someobject. This is not a restriction that someobject will be an object only it can be a function too, a class or an object.
When you say
new Object()
like you said
new Vue({
el: '#app',
data: []
)}
Here you are initiating an object of class Vue.
I hope my answer explains your query in general and more explicitly.
Consider 2 dataFrames:
>>> aDF.show()
+---+----+
| id|datA|
+---+----+
| 1| a1|
| 2| a2|
| 3| a3|
+---+----+
and
>>> bDF.show()
+---+----+
| id|datB|
+---+----+
| 2| b2|
| 3| b3|
| 4| b4|
+---+----+
To accomplish what you are looking for, there are 2 ways:
1. Different joining condition. Instead of saying aDF.id == bDF.id
aDF.join(bDF, aDF.id == bDF.id, "outer")
Write this:
aDF.join(bDF, "id", "outer").show()
+---+----+----+
| id|datA|datB|
+---+----+----+
| 1| a1|null|
| 3| a3| b3|
| 2| a2| b2|
| 4|null| b4|
+---+----+----+
This will automatically get rid of the extra the dropping process.
2. Use Aliasing: You will lose data related to B Specific Id's in this.
>>> from pyspark.sql.functions import col
>>> aDF.alias("a").join(bDF.alias("b"), aDF.id == bDF.id, "outer").drop(col("b.id")).show()
+----+----+----+
| id|datA|datB|
+----+----+----+
| 1| a1|null|
| 3| a3| b3|
| 2| a2| b2|
|null|null| b4|
+----+----+----+
for me , using export PYTHONIOENCODING=UTF-8 before executing python command worked .
Here are a couple: http://www.amp-what.com/unicode/search/check%20mark
✓ ✔
I think the most safest downgrade path from PHP7 to PHP5 in Xampp is:
Download a self-packaged version of Xampp with PHP5 from here (as of today this is xampp-win32-5.6.37-0-VC11.zip
).
Rename the php
folder to php7
in Xampp.
Now copy the php
folder from xampp-win32-5.6.37-0-VC11.zip
into your Xampp install folder.
Make a backup from .\xampp\apache\conf\extra\httpd-xampp.conf
file.
Replace this file from xampp-win32-5.6.37-0-VC11.zip
as well.
This way the config files (including php.ini
) has settings from the Xampp team.
Before any changes, to verify changed Apache configs, you can compare both Xampp release folder at .\xampp\apache\conf
with tools like Meld.
I should note that please download PHP 5 and 7 Xampp packages released at the same time.
Notify me if I miss something.
This is a warning for usual. You can either disable it by
#pragma warning(disable:4996)
or simply use fopen_s like Microsoft has intended.
But be sure to use the pragma before other headers.
I searched for any solution to not use the "SendKeys(CHR(13))
" methode I ever used to submit stuff in Browser. In this case I was happy to see your
InvokeMember("click")
but dont know why you know that you have to write "click" in there. Anyway Thanks
Just had this problem.
I fixed it by navigating to:
Tools -> Options -> Debugging -> Symbols
Then unchecking all non-local sources for Symbol file (.pdb) locations
e.g. Microsoft Symbol Servers and msdl.microsoft.com/download/symbols
The replace function should work for you.
REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE()
performs a case-sensitive match when searching for from_str.
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)
Based on @mat-khor's answer, I took the syswin su.exe
, saved it as manufacture-syswin-su.exe
, and wrote this wrapper script. It handles redirection of the command's stdout and stderr, so it can be used in a pipe, etc. Also, the script exits with the status of the given command.
Limitations:
env USERNAME=...
to the script invocation overrides it. If other options were needed, the script would have to distinguish between syswin-su and command arguments, e.g. splitting at the first --
..
#!/bin/bash
set -e
# join command $@ into a single string with quoting (required for syswin-su)
cmd=$( ( set -x; set -- "$@"; ) 2>&1 | perl -nle 'print $1 if /\bset -- (.*)/' )
tmpDir=$(mktemp -t -d -- "$(basename "$0")_$(date '+%Y%m%dT%H%M%S')_XXX")
mkfifo -- "$tmpDir/out"
mkfifo -- "$tmpDir/err"
cat >> "$tmpDir/script" <<-SCRIPT
#!/bin/env bash
$cmd > '$tmpDir/out' 2> '$tmpDir/err'
echo \$? > '$tmpDir/status'
SCRIPT
chmod 700 -- "$tmpDir/script"
manufacture-syswin-su -s bash -u "$USERNAME" -m -c "cygstart --showminimized bash -c '$tmpDir/script'" > /dev/null &
cat -- "$tmpDir/err" >&2 &
cat -- "$tmpDir/out"
wait $!
exit $(<"$tmpDir/status")
I'm fairly confident that providing code-examples would help you receive a solution must faster. If you can upload an example of this issue somewhere, or provide the markup so we can test it on our localhosts, you'll have a better chance of getting some valuable input.
The problem with questions is that they lead others to believe the person asking the question has sufficient knowledge to ask the question. In programming that isn't always the case. There may have been something you missed, or accidentally jipped. Without others having eyes on your code, they have to assume you missed nothing, and overlooked nothing.
The files/folder in your version control will not just delete themselves just because you added them to the .gitignore
. They are already in the repository and you have to remove them. You can just do that with this:
Remember to commit everything you've changed before you do this!
git rm -rf --cached .
git add .
This removes all files from the repository and adds them back (this time respecting the rules in your .gitignore
).
The controller
function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model
changes coming from View
the Controller
is the right person to do that job.
The story about link
function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view
(template).
Let' start with the parameters which are passed into the link
function:
function link(scope, element, attrs) {
To put the link
into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:
Compile phase (a sister of link, let's mention it here to get a clear picture):
In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,
Link phase:
To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.
A nice example how to use the link
could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.
Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks
.directive('myCurrentTime', function($timeout, dateFilter) {
function link(scope, element, attrs) {
...
// the not MVC job must be done
function updateTime() {
element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
}
function scheduleUpdate() {
// save the timeoutId for canceling
timeoutId = $timeout(function() {
updateTime(); // update DOM
scheduleUpdate(); // schedule the next update
}, 1000);
}
element.on('$destroy', function() {
$timeout.cancel(timeoutId);
});
...
That would be:
b.rstrip('\n')
If you want to strip space from each and every line, you might consider instead:
a.read().splitlines()
This will give you a list of lines, without the line end characters.
the button 'Use same account' below thee main window will fill in all the textboxes automatically. this worked fpr me.
I prefer this:
DateTime s = //get some datetime;
s = new DateTime(s.Year, s.Month,s.Day,s.Hour,s.Minute,0);
For mocking static functions i was able to do it that way:
wrapper code snippet (not really functional, just for illustration)
class myWrapperClass ...
def myWrapperFunction (...) {
return theOriginalFunction (...)
}
of course having multiple such functions accumulated in a single wrapper class might be beneficial in terms of code reuse.
This can also be achieved with jsp:include. Chad Darby explains well here in this video https://www.youtube.com/watch?v=EWbYj0qoNHo
As mentioned by some and if you are the code author, you should correct all those errors, notices, etc. because it will cause more problems for you long terms than not fixing them (especially when you upgrade your OS). For your server, you should have errors displayed in your logs only, not the client's screen.
So to avoid the errors in your browser you use the display_errors
flag as you already found:
display_errors = Off
Now the real problem is when you are running someone else code. In that case, modifying the code is likely to get overwritten each time you upgrade that code. It makes it tedious to maintain that code.
In my case, I am running PHP with crontab
to have the wp-cron.php
script running once in a while. I was getting errors sent to my emails, which becomes tedious when you get one email every 10 minutes! In that case, though, the Wordpress system has a configuration file includes a WP_DEBUG
and they call the error_reporting()
function so trying to change the error_reporting
variable on the command line won't work. Instead you have to edit the wp-config.php
file in the root folder and make sure that the WP_DEBUG
is set to false
. Otherwise you will get all those warnings and notices all the time.
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()
It can be %f
, %g
or %e
depending on how you want the number to be formatted. See here for more details. The l
modifier is required in scanf
with double
, but not in printf
.
Use the \b
operator (the backspace escape operator) in the second parameter
String test= "Anna Banana";
System.out.println(test); //returns Anna Banana<br><br>
System.out.println(test.replaceAll(" ","\b")); //returns AnnaBanana removing all the spaces in the string
The accepted answer misses some rather significant locales. For example, the Chinese locales don't distinguish between the different scriptures (simplified han, traditional han). What's a main-land Chinese citizen who wants traditional han supposed to use - the Hong Kong setting?
I've taken this list of iOS locales, removed the strange POSIX entry, formatted it as Javascript and sorted it by value (so if you use an ordered object implementation and create a list by going through the keys and returning the value, it will show the human readable text in correct order). Also, this list both contains a main entry per language as well as all the region specific variants - this way you always have a designated fallback option, say if your interface has only defined the 'en' option - you wouldn't otherwise know on what to fall back on reliably.
var LANGUAGE_BY_LOCALE = {
af_NA: "Afrikaans (Namibia)",
af_ZA: "Afrikaans (South Africa)",
af: "Afrikaans",
ak_GH: "Akan (Ghana)",
ak: "Akan",
sq_AL: "Albanian (Albania)",
sq: "Albanian",
am_ET: "Amharic (Ethiopia)",
am: "Amharic",
ar_DZ: "Arabic (Algeria)",
ar_BH: "Arabic (Bahrain)",
ar_EG: "Arabic (Egypt)",
ar_IQ: "Arabic (Iraq)",
ar_JO: "Arabic (Jordan)",
ar_KW: "Arabic (Kuwait)",
ar_LB: "Arabic (Lebanon)",
ar_LY: "Arabic (Libya)",
ar_MA: "Arabic (Morocco)",
ar_OM: "Arabic (Oman)",
ar_QA: "Arabic (Qatar)",
ar_SA: "Arabic (Saudi Arabia)",
ar_SD: "Arabic (Sudan)",
ar_SY: "Arabic (Syria)",
ar_TN: "Arabic (Tunisia)",
ar_AE: "Arabic (United Arab Emirates)",
ar_YE: "Arabic (Yemen)",
ar: "Arabic",
hy_AM: "Armenian (Armenia)",
hy: "Armenian",
as_IN: "Assamese (India)",
as: "Assamese",
asa_TZ: "Asu (Tanzania)",
asa: "Asu",
az_Cyrl: "Azerbaijani (Cyrillic)",
az_Cyrl_AZ: "Azerbaijani (Cyrillic, Azerbaijan)",
az_Latn: "Azerbaijani (Latin)",
az_Latn_AZ: "Azerbaijani (Latin, Azerbaijan)",
az: "Azerbaijani",
bm_ML: "Bambara (Mali)",
bm: "Bambara",
eu_ES: "Basque (Spain)",
eu: "Basque",
be_BY: "Belarusian (Belarus)",
be: "Belarusian",
bem_ZM: "Bemba (Zambia)",
bem: "Bemba",
bez_TZ: "Bena (Tanzania)",
bez: "Bena",
bn_BD: "Bengali (Bangladesh)",
bn_IN: "Bengali (India)",
bn: "Bengali",
bs_BA: "Bosnian (Bosnia and Herzegovina)",
bs: "Bosnian",
bg_BG: "Bulgarian (Bulgaria)",
bg: "Bulgarian",
my_MM: "Burmese (Myanmar [Burma])",
my: "Burmese",
yue_Hant_HK: "Cantonese (Traditional, Hong Kong SAR China)",
ca_ES: "Catalan (Spain)",
ca: "Catalan",
tzm_Latn: "Central Morocco Tamazight (Latin)",
tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",
tzm: "Central Morocco Tamazight",
chr_US: "Cherokee (United States)",
chr: "Cherokee",
cgg_UG: "Chiga (Uganda)",
cgg: "Chiga",
zh_Hans: "Chinese (Simplified Han)",
zh_Hans_CN: "Chinese (Simplified Han, China)",
zh_Hans_HK: "Chinese (Simplified Han, Hong Kong SAR China)",
zh_Hans_MO: "Chinese (Simplified Han, Macau SAR China)",
zh_Hans_SG: "Chinese (Simplified Han, Singapore)",
zh_Hant: "Chinese (Traditional Han)",
zh_Hant_HK: "Chinese (Traditional Han, Hong Kong SAR China)",
zh_Hant_MO: "Chinese (Traditional Han, Macau SAR China)",
zh_Hant_TW: "Chinese (Traditional Han, Taiwan)",
zh: "Chinese",
kw_GB: "Cornish (United Kingdom)",
kw: "Cornish",
hr_HR: "Croatian (Croatia)",
hr: "Croatian",
cs_CZ: "Czech (Czech Republic)",
cs: "Czech",
da_DK: "Danish (Denmark)",
da: "Danish",
nl_BE: "Dutch (Belgium)",
nl_NL: "Dutch (Netherlands)",
nl: "Dutch",
ebu_KE: "Embu (Kenya)",
ebu: "Embu",
en_AS: "English (American Samoa)",
en_AU: "English (Australia)",
en_BE: "English (Belgium)",
en_BZ: "English (Belize)",
en_BW: "English (Botswana)",
en_CA: "English (Canada)",
en_GU: "English (Guam)",
en_HK: "English (Hong Kong SAR China)",
en_IN: "English (India)",
en_IE: "English (Ireland)",
en_IL: "English (Israel)",
en_JM: "English (Jamaica)",
en_MT: "English (Malta)",
en_MH: "English (Marshall Islands)",
en_MU: "English (Mauritius)",
en_NA: "English (Namibia)",
en_NZ: "English (New Zealand)",
en_MP: "English (Northern Mariana Islands)",
en_PK: "English (Pakistan)",
en_PH: "English (Philippines)",
en_SG: "English (Singapore)",
en_ZA: "English (South Africa)",
en_TT: "English (Trinidad and Tobago)",
en_UM: "English (U.S. Minor Outlying Islands)",
en_VI: "English (U.S. Virgin Islands)",
en_GB: "English (United Kingdom)",
en_US: "English (United States)",
en_ZW: "English (Zimbabwe)",
en: "English",
eo: "Esperanto",
et_EE: "Estonian (Estonia)",
et: "Estonian",
ee_GH: "Ewe (Ghana)",
ee_TG: "Ewe (Togo)",
ee: "Ewe",
fo_FO: "Faroese (Faroe Islands)",
fo: "Faroese",
fil_PH: "Filipino (Philippines)",
fil: "Filipino",
fi_FI: "Finnish (Finland)",
fi: "Finnish",
fr_BE: "French (Belgium)",
fr_BJ: "French (Benin)",
fr_BF: "French (Burkina Faso)",
fr_BI: "French (Burundi)",
fr_CM: "French (Cameroon)",
fr_CA: "French (Canada)",
fr_CF: "French (Central African Republic)",
fr_TD: "French (Chad)",
fr_KM: "French (Comoros)",
fr_CG: "French (Congo - Brazzaville)",
fr_CD: "French (Congo - Kinshasa)",
fr_CI: "French (Côte d’Ivoire)",
fr_DJ: "French (Djibouti)",
fr_GQ: "French (Equatorial Guinea)",
fr_FR: "French (France)",
fr_GA: "French (Gabon)",
fr_GP: "French (Guadeloupe)",
fr_GN: "French (Guinea)",
fr_LU: "French (Luxembourg)",
fr_MG: "French (Madagascar)",
fr_ML: "French (Mali)",
fr_MQ: "French (Martinique)",
fr_MC: "French (Monaco)",
fr_NE: "French (Niger)",
fr_RW: "French (Rwanda)",
fr_RE: "French (Réunion)",
fr_BL: "French (Saint Barthélemy)",
fr_MF: "French (Saint Martin)",
fr_SN: "French (Senegal)",
fr_CH: "French (Switzerland)",
fr_TG: "French (Togo)",
fr: "French",
ff_SN: "Fulah (Senegal)",
ff: "Fulah",
gl_ES: "Galician (Spain)",
gl: "Galician",
lg_UG: "Ganda (Uganda)",
lg: "Ganda",
ka_GE: "Georgian (Georgia)",
ka: "Georgian",
de_AT: "German (Austria)",
de_BE: "German (Belgium)",
de_DE: "German (Germany)",
de_LI: "German (Liechtenstein)",
de_LU: "German (Luxembourg)",
de_CH: "German (Switzerland)",
de: "German",
el_CY: "Greek (Cyprus)",
el_GR: "Greek (Greece)",
el: "Greek",
gu_IN: "Gujarati (India)",
gu: "Gujarati",
guz_KE: "Gusii (Kenya)",
guz: "Gusii",
ha_Latn: "Hausa (Latin)",
ha_Latn_GH: "Hausa (Latin, Ghana)",
ha_Latn_NE: "Hausa (Latin, Niger)",
ha_Latn_NG: "Hausa (Latin, Nigeria)",
ha: "Hausa",
haw_US: "Hawaiian (United States)",
haw: "Hawaiian",
he_IL: "Hebrew (Israel)",
he: "Hebrew",
hi_IN: "Hindi (India)",
hi: "Hindi",
hu_HU: "Hungarian (Hungary)",
hu: "Hungarian",
is_IS: "Icelandic (Iceland)",
is: "Icelandic",
ig_NG: "Igbo (Nigeria)",
ig: "Igbo",
id_ID: "Indonesian (Indonesia)",
id: "Indonesian",
ga_IE: "Irish (Ireland)",
ga: "Irish",
it_IT: "Italian (Italy)",
it_CH: "Italian (Switzerland)",
it: "Italian",
ja_JP: "Japanese (Japan)",
ja: "Japanese",
kea_CV: "Kabuverdianu (Cape Verde)",
kea: "Kabuverdianu",
kab_DZ: "Kabyle (Algeria)",
kab: "Kabyle",
kl_GL: "Kalaallisut (Greenland)",
kl: "Kalaallisut",
kln_KE: "Kalenjin (Kenya)",
kln: "Kalenjin",
kam_KE: "Kamba (Kenya)",
kam: "Kamba",
kn_IN: "Kannada (India)",
kn: "Kannada",
kk_Cyrl: "Kazakh (Cyrillic)",
kk_Cyrl_KZ: "Kazakh (Cyrillic, Kazakhstan)",
kk: "Kazakh",
km_KH: "Khmer (Cambodia)",
km: "Khmer",
ki_KE: "Kikuyu (Kenya)",
ki: "Kikuyu",
rw_RW: "Kinyarwanda (Rwanda)",
rw: "Kinyarwanda",
kok_IN: "Konkani (India)",
kok: "Konkani",
ko_KR: "Korean (South Korea)",
ko: "Korean",
khq_ML: "Koyra Chiini (Mali)",
khq: "Koyra Chiini",
ses_ML: "Koyraboro Senni (Mali)",
ses: "Koyraboro Senni",
lag_TZ: "Langi (Tanzania)",
lag: "Langi",
lv_LV: "Latvian (Latvia)",
lv: "Latvian",
lt_LT: "Lithuanian (Lithuania)",
lt: "Lithuanian",
luo_KE: "Luo (Kenya)",
luo: "Luo",
luy_KE: "Luyia (Kenya)",
luy: "Luyia",
mk_MK: "Macedonian (Macedonia)",
mk: "Macedonian",
jmc_TZ: "Machame (Tanzania)",
jmc: "Machame",
kde_TZ: "Makonde (Tanzania)",
kde: "Makonde",
mg_MG: "Malagasy (Madagascar)",
mg: "Malagasy",
ms_BN: "Malay (Brunei)",
ms_MY: "Malay (Malaysia)",
ms: "Malay",
ml_IN: "Malayalam (India)",
ml: "Malayalam",
mt_MT: "Maltese (Malta)",
mt: "Maltese",
gv_GB: "Manx (United Kingdom)",
gv: "Manx",
mr_IN: "Marathi (India)",
mr: "Marathi",
mas_KE: "Masai (Kenya)",
mas_TZ: "Masai (Tanzania)",
mas: "Masai",
mer_KE: "Meru (Kenya)",
mer: "Meru",
mfe_MU: "Morisyen (Mauritius)",
mfe: "Morisyen",
naq_NA: "Nama (Namibia)",
naq: "Nama",
ne_IN: "Nepali (India)",
ne_NP: "Nepali (Nepal)",
ne: "Nepali",
nd_ZW: "North Ndebele (Zimbabwe)",
nd: "North Ndebele",
nb_NO: "Norwegian Bokmål (Norway)",
nb: "Norwegian Bokmål",
nn_NO: "Norwegian Nynorsk (Norway)",
nn: "Norwegian Nynorsk",
nyn_UG: "Nyankole (Uganda)",
nyn: "Nyankole",
or_IN: "Oriya (India)",
or: "Oriya",
om_ET: "Oromo (Ethiopia)",
om_KE: "Oromo (Kenya)",
om: "Oromo",
ps_AF: "Pashto (Afghanistan)",
ps: "Pashto",
fa_AF: "Persian (Afghanistan)",
fa_IR: "Persian (Iran)",
fa: "Persian",
pl_PL: "Polish (Poland)",
pl: "Polish",
pt_BR: "Portuguese (Brazil)",
pt_GW: "Portuguese (Guinea-Bissau)",
pt_MZ: "Portuguese (Mozambique)",
pt_PT: "Portuguese (Portugal)",
pt: "Portuguese",
pa_Arab: "Punjabi (Arabic)",
pa_Arab_PK: "Punjabi (Arabic, Pakistan)",
pa_Guru: "Punjabi (Gurmukhi)",
pa_Guru_IN: "Punjabi (Gurmukhi, India)",
pa: "Punjabi",
ro_MD: "Romanian (Moldova)",
ro_RO: "Romanian (Romania)",
ro: "Romanian",
rm_CH: "Romansh (Switzerland)",
rm: "Romansh",
rof_TZ: "Rombo (Tanzania)",
rof: "Rombo",
ru_MD: "Russian (Moldova)",
ru_RU: "Russian (Russia)",
ru_UA: "Russian (Ukraine)",
ru: "Russian",
rwk_TZ: "Rwa (Tanzania)",
rwk: "Rwa",
saq_KE: "Samburu (Kenya)",
saq: "Samburu",
sg_CF: "Sango (Central African Republic)",
sg: "Sango",
seh_MZ: "Sena (Mozambique)",
seh: "Sena",
sr_Cyrl: "Serbian (Cyrillic)",
sr_Cyrl_BA: "Serbian (Cyrillic, Bosnia and Herzegovina)",
sr_Cyrl_ME: "Serbian (Cyrillic, Montenegro)",
sr_Cyrl_RS: "Serbian (Cyrillic, Serbia)",
sr_Latn: "Serbian (Latin)",
sr_Latn_BA: "Serbian (Latin, Bosnia and Herzegovina)",
sr_Latn_ME: "Serbian (Latin, Montenegro)",
sr_Latn_RS: "Serbian (Latin, Serbia)",
sr: "Serbian",
sn_ZW: "Shona (Zimbabwe)",
sn: "Shona",
ii_CN: "Sichuan Yi (China)",
ii: "Sichuan Yi",
si_LK: "Sinhala (Sri Lanka)",
si: "Sinhala",
sk_SK: "Slovak (Slovakia)",
sk: "Slovak",
sl_SI: "Slovenian (Slovenia)",
sl: "Slovenian",
xog_UG: "Soga (Uganda)",
xog: "Soga",
so_DJ: "Somali (Djibouti)",
so_ET: "Somali (Ethiopia)",
so_KE: "Somali (Kenya)",
so_SO: "Somali (Somalia)",
so: "Somali",
es_AR: "Spanish (Argentina)",
es_BO: "Spanish (Bolivia)",
es_CL: "Spanish (Chile)",
es_CO: "Spanish (Colombia)",
es_CR: "Spanish (Costa Rica)",
es_DO: "Spanish (Dominican Republic)",
es_EC: "Spanish (Ecuador)",
es_SV: "Spanish (El Salvador)",
es_GQ: "Spanish (Equatorial Guinea)",
es_GT: "Spanish (Guatemala)",
es_HN: "Spanish (Honduras)",
es_419: "Spanish (Latin America)",
es_MX: "Spanish (Mexico)",
es_NI: "Spanish (Nicaragua)",
es_PA: "Spanish (Panama)",
es_PY: "Spanish (Paraguay)",
es_PE: "Spanish (Peru)",
es_PR: "Spanish (Puerto Rico)",
es_ES: "Spanish (Spain)",
es_US: "Spanish (United States)",
es_UY: "Spanish (Uruguay)",
es_VE: "Spanish (Venezuela)",
es: "Spanish",
sw_KE: "Swahili (Kenya)",
sw_TZ: "Swahili (Tanzania)",
sw: "Swahili",
sv_FI: "Swedish (Finland)",
sv_SE: "Swedish (Sweden)",
sv: "Swedish",
gsw_CH: "Swiss German (Switzerland)",
gsw: "Swiss German",
shi_Latn: "Tachelhit (Latin)",
shi_Latn_MA: "Tachelhit (Latin, Morocco)",
shi_Tfng: "Tachelhit (Tifinagh)",
shi_Tfng_MA: "Tachelhit (Tifinagh, Morocco)",
shi: "Tachelhit",
dav_KE: "Taita (Kenya)",
dav: "Taita",
ta_IN: "Tamil (India)",
ta_LK: "Tamil (Sri Lanka)",
ta: "Tamil",
te_IN: "Telugu (India)",
te: "Telugu",
teo_KE: "Teso (Kenya)",
teo_UG: "Teso (Uganda)",
teo: "Teso",
th_TH: "Thai (Thailand)",
th: "Thai",
bo_CN: "Tibetan (China)",
bo_IN: "Tibetan (India)",
bo: "Tibetan",
ti_ER: "Tigrinya (Eritrea)",
ti_ET: "Tigrinya (Ethiopia)",
ti: "Tigrinya",
to_TO: "Tonga (Tonga)",
to: "Tonga",
tr_TR: "Turkish (Turkey)",
tr: "Turkish",
uk_UA: "Ukrainian (Ukraine)",
uk: "Ukrainian",
ur_IN: "Urdu (India)",
ur_PK: "Urdu (Pakistan)",
ur: "Urdu",
uz_Arab: "Uzbek (Arabic)",
uz_Arab_AF: "Uzbek (Arabic, Afghanistan)",
uz_Cyrl: "Uzbek (Cyrillic)",
uz_Cyrl_UZ: "Uzbek (Cyrillic, Uzbekistan)",
uz_Latn: "Uzbek (Latin)",
uz_Latn_UZ: "Uzbek (Latin, Uzbekistan)",
uz: "Uzbek",
vi_VN: "Vietnamese (Vietnam)",
vi: "Vietnamese",
vun_TZ: "Vunjo (Tanzania)",
vun: "Vunjo",
cy_GB: "Welsh (United Kingdom)",
cy: "Welsh",
yo_NG: "Yoruba (Nigeria)",
yo: "Yoruba",
zu_ZA: "Zulu (South Africa)",
zu: "Zulu"
}
I had this issue after installing dotnetframework4.5.
Open path below:
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin" ( in 64 bits machine)
or
"C:\Program Files\Microsoft Visual Studio 10.0\VC\bin" (in 32 bits machine)
In this path find file cvtres.exe and rename it to cvtres1.exe then compile your project again.
Sadly, Python doesn't have a simple way to flatten lists. Try this:
def flatten(some_list):
for element in some_list:
if type(element) in (tuple, list):
for item in flatten(element):
yield item
else:
yield element
Which will recursively flatten a list; you can then do
result = []
[ result.extend(el) for el in x]
for el in flatten(result):
print el
I think it'd be more confusing if your comparison algorithm were "clever". I'd go with the numerous comparison methods you suggested.
The only exception for me would be equality. For unit testing, it's been useful to me to override the .Equals (in .net) in order to determine if several fields are equal between two objects (and not that the references are equal).
If you do it a lot I would suggest writing a function that compares the two structures. That way, if you ever change the structure you only need to change the compare in one place.
As for how to do it.... You need to compare every element individually
@echo off
cd "folder directory to your file"
start filename.ext
For example:
cd "C:\Program Files (x86)\Winamp"
Start winamp.exe
Why not just:
int plusIndex = s.indexOf("+");
if (plusIndex != -1) {
String before = s.substring(0, plusIndex);
// Use before
}
It's not really clear why your original version didn't work, but then you didn't say what actually happened. If you want to split not using regular expressions, I'd personally use Guava:
Iterable<String> bits = Splitter.on('+').split(s);
String firstPart = Iterables.getFirst(bits, "");
If you're going to use split
(either the built-in version or Guava) you don't need to check whether it contains +
first - if it doesn't there'll only be one result anyway. Obviously there's a question of efficiency, but it's simpler code:
// Calling split unconditionally
String[] parts = s.split("\\+");
s = parts[0];
Note that writing String[] parts
is preferred over String parts[]
- it's much more idiomatic Java code.
In my case I received this exception even when all parameter values were correctly supplied but the type of command was not specified :
cmd.CommandType = System.Data.CommandType.StoredProcedure;
This is obviously not the case in the question above, but exception description is not very clear in this case, so I decided to specify that.
You're the victim of the classic deadlock. task.Wait()
or task.Result
is a blocking call in UI thread which causes the deadlock.
Don't block in the UI thread. Never do it. Just await it.
private async void Button_Click(object sender, RoutedEventArgs
{
var task = GetResponseAsync<MyObject>("my url");
var items = await task;
}
Btw, why are you catching the WebException
and throwing it back? It would be better if you simply don't catch it. Both are same.
Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse
method. StreamReader.ReadToEnd
is a blocking call --you should be using StreamReader.ReadToEndAsync
.
Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.
Your method should look something like the following when you've addressed all the above concerns.
public static async Task<List<T>> GetResponseAsync<T>(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
Stream stream = response.GetResponseStream();
StreamReader strReader = new StreamReader(stream);
string text = await strReader.ReadToEndAsync();
return JsonConvert.DeserializeObject<List<T>>(text);
}
One interesting thing that I came across is the fact that you can have a capturing group inside a non-capturing group. Have a look at below regex for matching web urls:
var parse_url_regex = /^(?:([A-Za-z]+):)(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
Input url string:
var url = "http://www.ora.com:80/goodparts?q#fragment";
The first group in my regex (?:([A-Za-z]+):)
is a non-capturing group which matches the protocol scheme and colon :
character i.e. http:
but when I was running below code, I was seeing the 1st index of the returned array was containing the string http
when I was thinking that http
and colon :
both will not get reported as they are inside a non-capturing group.
console.debug(parse_url_regex.exec(url));
I thought if the first group (?:([A-Za-z]+):)
is a non-capturing group then why it is returning http
string in the output array.
So if you notice that there is a nested group ([A-Za-z]+)
inside the non-capturing group. That nested group ([A-Za-z]+)
is a capturing group (not having ?:
at the beginning) in itself inside a non-capturing group (?:([A-Za-z]+):)
. That's why the text http
still gets captured but the colon :
character which is inside the non-capturing group but outside the capturing group doesn't get reported in the output array.
$array = explode(' ', $string);
You can also use the actual text of the *e*xample test case with -e
!
So for:
it "shows the plane arrival time"
you can use
rspec path/to/spec/file.rb -e 'shows the plane arrival time'
./scripts/spec path/to/spec/file.rb -e 'shows the plane arrival time'
no need for rake here.
How about this:
try:
f = open(fname, 'rb')
except OSError:
print "Could not open/read file:", fname
sys.exit()
with f:
reader = csv.reader(f)
for row in reader:
pass #do stuff here
The nextInt()
method leaves the \n
(end line) symbol and is picked up immediately by nextLine()
, skipping over the next input. What you want to do is use nextLine()
for everything, and parse it later:
String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int
This is by far the easiest way to avoid problems--don't mix your "next" methods. Use only nextLine()
and then parse int
s or separate words afterwards.
Also, make sure you use only one Scanner
if your are only using one terminal for input. That could be another reason for the exception.
Last note: compare a String
with the .equals()
function, not the ==
operator.
if (playAgain == "yes"); // Causes problems
if (playAgain.equals("yes")); // Works every time
This worked for me:
explorer <YOUR URL>
For example:
explorer "https://www.google.com/"
This will open https://www.google.com/ in your default browser.
According to the Android developers guide for android.hardware.Camera
, they state:
We recommend using the new android.hardware.camera2 API for new applications.
On the information page about android.hardware.camera2
, (linked above), it is stated:
The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class.
When you check that documentation you'll find that the implementation of these 2 Camera API's are very different.
For example getting camera orientation on android.hardware.camera
@Override
public int getOrientation(final int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
return info.orientation;
}
Versus android.hardware.camera2
@Override
public int getOrientation(final int cameraId) {
try {
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String[] cameraIds = manager.getCameraIdList();
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
} catch (CameraAccessException e) {
// TODO handle error properly or pass it on
return 0;
}
}
This makes it hard to switch from one to another and write code that can handle both implementations.
Note that in this single code example I already had to work around the fact that the olde camera API works with int
primitives for camera IDs while the new one works with String
objects. For this example I quickly fixed that by using the int as an index in the new API. If the camera's returned aren't always in the same order this will already cause issues. Alternative approach is to work with String objects and String representation of the old int cameraIDs which is probably safer.
Now to work around this huge difference you can implement an interface first and reference that interface in your code.
Here I'll list some code for that interface and the 2 implementations. You can limit the implementation to what you actually use of the camera API to limit the amount of work.
In the next section I'll quickly explain how to load one or another.
The interface wrapping all you need, to limit this example I only have 2 methods here.
public interface CameraSupport {
CameraSupport open(int cameraId);
int getOrientation(int cameraId);
}
Now have a class for the old camera hardware api:
@SuppressWarnings("deprecation")
public class CameraOld implements CameraSupport {
private Camera camera;
@Override
public CameraSupport open(final int cameraId) {
this.camera = Camera.open(cameraId);
return this;
}
@Override
public int getOrientation(final int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
return info.orientation;
}
}
And another one for the new hardware api:
public class CameraNew implements CameraSupport {
private CameraDevice camera;
private CameraManager manager;
public CameraNew(final Context context) {
this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
}
@Override
public CameraSupport open(final int cameraId) {
try {
String[] cameraIds = manager.getCameraIdList();
manager.openCamera(cameraIds[cameraId], new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
CameraNew.this.camera = camera;
}
@Override
public void onDisconnected(CameraDevice camera) {
CameraNew.this.camera = camera;
// TODO handle
}
@Override
public void onError(CameraDevice camera, int error) {
CameraNew.this.camera = camera;
// TODO handle
}
}, null);
} catch (Exception e) {
// TODO handle
}
return this;
}
@Override
public int getOrientation(final int cameraId) {
try {
String[] cameraIds = manager.getCameraIdList();
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
} catch (CameraAccessException e) {
// TODO handle
return 0;
}
}
}
Now to load either your CameraOld
or CameraNew
class you'll have to check the API level since CameraNew
is only available from api level 21.
If you have dependency injection set up already you can do so in your module when providing the CameraSupport
implementation. Example:
@Module public class CameraModule {
@Provides
CameraSupport provideCameraSupport(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return new CameraNew(context);
} else {
return new CameraOld();
}
}
}
If you don't use DI you can just make a utility or use Factory pattern to create the proper one. Important part is that the API level is checked.
Note that the variables @fname
or @ext
can be simply concatenated. This:
forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"
renames all PDF files to "filename_old.pdf"
Taken from a related post:
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
https://www.youtube.com/account_advanced now provides both channel and user ids. See also https://developers.google.com/youtube/v3/guides/working_with_channel_ids .
Way out for me was to add
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
annotation to class running Spring boot (marked with `@SpringBootApplication).
Finally, it looks like:
@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
<div style="cursor:pointer;" onclick="document.location='http://www.google.com'">Foo</div>
To complement Jon Lin's answer, here is a no-trailing-slash technique that also works if the website is located in a directory (like example.org/blog/):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
For the sake of completeness, here is an alternative emphasizing that REQUEST_URI
starts with a slash (at least in .htaccess
files):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L] <-- added slash here too, don't forget it
Just don't use %{REQUEST_URI} (.*)/$
. Because in the root directory REQUEST_URI
equals /
, the leading slash, and it would be misinterpreted as a trailing slash.
If you are interested in more reading:
(update: this technique is now implemented in Laravel 5.5)
jQuery.post(post_url,{ content: "John" } )_x000D_
.done(function( data ) {_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check
ob_start();_x000D_
_x000D_
include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
$content = ob_get_clean();_x000D_
_x000D_
_x000D_
_x000D_
$test = $_SESSION['content'] ;_x000D_
_x000D_
require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
$html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 ); _x000D_
$html2pdf->setDefaultFont('Arial');_x000D_
$html2pdf->WriteHTML($test);
_x000D_
The "BIGINT(20)" specification isn't a digit limit. It just means that when the data is displayed, if it uses less than 20 digits it will be left-padded with zeros. 2^64 is the hard limit for the BIGINT type, and has 20 digits itself, hence BIGINT(20) just means everything less than 10^20 will be left-padded with spaces on display.
In case you have a multi-module project :
let us say your module structure is
root-module
-> a-module
-> b-module
and the test(testToRun) you are looking to run is in b-module, with full path : com.xyz.b.module.TestClass.testToRun
As here you are interested to run the test in b-module, so you should see the tasks available for b-module.
./gradlew :b-module:tasks
The above command will list all tasks in b-module with description. And in ideal case, you will have a task named test to run the unit tests in that module.
./gradlew :b-module:test
Now, you have reached the point for running all the tests in b-module, finally you can pass a parameter to the above task to run tests which matches the certain path pattern
./gradlew :b-module:test --tests "com.xyz.b.module.TestClass.testToRun"
Now, instead of this if you run
./gradlew test --tests "com.xyz.b.module.TestClass.testToRun"
It will run the test task for both module a and b, which might result in failure as there is nothing matching the above pattern in a-module.
Use NSBox, which is a subclass of NSView, allowing us to easily style
Swift 3
let box = NSBox()
box.boxType = .custom
box.fillColor = NSColor.red
box.cornerRadius = 5
Something like this:
using System.Diagnostics;
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (!String.IsNullOrEmpty(process.MainWindowTitle))
{
Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
}
}
In MATLAB R2015a or newer, it is no longer necessary (or advisable from a performance standpoint) to use fspecial
followed by imfilter
since there is a new function called imgaussfilt
that performs this operation in one step and more efficiently.
The basic syntax:
B = imgaussfilt(A,sigma)
filters imageA
with a 2-D Gaussian smoothing kernel with standard deviation specified bysigma
.
The size of the filter for a given Gaussian standard deviation (sigam
) is chosen automatically, but can also be specified manually:
B = imgaussfilt(A,sigma,'FilterSize',[3 3]);
The default is 2*ceil(2*sigma)+1
.
Additional features of imgaussfilter
are ability to operate on gpuArray
s, filtering in frequency or spacial domain, and advanced image padding options. It looks a lot like IPP... hmmm. Plus, there's a 3D version called imgaussfilt3
.
You can try open MVG library, It can be used for multiple interfaces too.
If you want to run from the current directory without a fully qualified path, you can use:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& './ps.ps1'"
[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.
The commit should be present in your local, check by using git log
.
If the commit is not present then try git fetch
to update the local with the latest remote.
The performance of @atk's implementation for sorted arrays of primitives can be improved by using .pop rather than .shift.
function intersect(array1, array2) {
var result = [];
// Don't destroy the original arrays
var a = array1.slice(0);
var b = array2.slice(0);
var aLast = a.length - 1;
var bLast = b.length - 1;
while (aLast >= 0 && bLast >= 0) {
if (a[aLast] > b[bLast] ) {
a.pop();
aLast--;
} else if (a[aLast] < b[bLast] ){
b.pop();
bLast--;
} else /* they're equal */ {
result.push(a.pop());
b.pop();
aLast--;
bLast--;
}
}
return result;
}
I created a benchmark using jsPerf: http://bit.ly/P9FrZK. It's about three times faster to use .pop.
You can think it as a CSS style visibility & display.
<div style="visibility:visible; display:block">
This is View.VISIBLE : Content is displayed normally.
</div>
<div style="visibility:hidden; display:block">
This is View.INVISIBLE : Content is not displayed, but div still takes up place, but empty.
</div>
<div style="display:none">
This is View.GONE : Container div is not shown, you can say the content is not displayed.
</div>
Same problem for me on apache http client 4.5.5 adding default header
Connection: close
resolve the problem
You can also use :checked
$("#myselect option:checked").val(); //to get value
or as said in other answers simply
$("#myselect").val(); //to get value
and
$("#myselect option:checked").text(); //to get text
If you use cPanel and have installed CloudLinux you can go to section Software > Select PHP Version > Switch To PHP Options and define max_execution_time among other options.
Short gif: http://cloud.mercadoalvo.com/nDdE
Public Function RandomNumber(ByVal n As Integer) As Integer
'initialize random number generator
Dim r As New Random(System.DateTime.Now.Millisecond)
Return r.Next(1, n)
End Function
You can use the ng-value directive in a hidden field as below :-
<input type="hidden" ng-value="myScopeVar = someValue"/>
This will set the value of the scope variable (myScopeVar) to "someValue"
I was getting the below as well trying to get out to github.com as our proxy re-writes the HTTPS connection with their self-signed cert:
no peer certificate available No client certificate CA names sent
In my output there was also:
Protocol : TLSv1.3
I added -tls1_2
and it worked fine and now I can see which CA it is using on the outgoing request. e.g.:
openssl s_client -connect github.com:443 -tls1_2
var sizef = document.getElementById('input-file-id').files[0].size;
if(sizef > 210000){
alert('sorry error');
}else {
//action
}
Make sure you are using binding to get component props in REACT
class FileUploader extends Component {
constructor (props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
onChange=(e,props)=>{
const files = e.target.files;
const selectedFile = files[0];
ProcessFileUpload(selectedFile,props.ProgressCallBack,props.ErrorCallBack,props.CompleatedCallBack,props.BaseURL,props.Location,props.FilesAllowed);
}
handleClick = () => {
this.refs.fileUploader.click();
}
render()
{
return(
<div>
<button type="button" onClick={this.handleClick}>Select File</button>
<input type='file' onChange={(e)=>this.onChange(e,this.props)} ref="fileUploader" style={{display:"none"}} />
</div>)
}
}
Those script tags are a common way to implement templating functionality (like in PHP) but on the client side.
By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.
Backbone doesn't force you to use any particular templating library - there are quite a few out there: Mustache, Haml, Eco,Google Closure template, and so on (the one used in the example you linked to is underscore.js). These will use their own syntax for you to write within those script tags.
I increased max execution time to 600 seconds job done !
Since vars passed through url are $_GET vars, you can use filter_input()
function:
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$othervar = filter_input(INPUT_GET, 'othervar', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
It would store the values of each var and sanitize/validate them too.
As mentioned in the comments, there cannot be a continuous scale on variable of the factor
type. You could change the factor
to numeric
as follows, just after you define the meltDF
variable.
meltDF$variable=as.numeric(levels(meltDF$variable))[meltDF$variable]
Then, execute the ggplot
command
ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y = variable)) +
scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))
And you will have your chart.
Hope this helps
(First, I'd like to recommend this useful reference site for batch: http://ss64.com/nt/)
Then just another useful explanation: http://htipe.wordpress.com/2008/10/09/the-dp0-variable/
The %~dp0 Variable
The
%~dp0
(that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.The variables
%0-%9
refer to the command line parameters of the batch file.%1-%9
refer to command line arguments after the batch file name.%0
refers to the batch file itself.If you follow the percent character (
%
) with a tilde character (~
), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. Thed
modifier expands to the drive letter and thep
modifier expands to the path of the parameter.Example: Let’s say you have a directory on
C:
calledbat_files
, and in that directory is a file calledexample.bat
. In this case,%~dp0
(combining thed
andp
modifiers) will expand toC:\bat_files\
.Check out this Microsoft article for a full explanation.
Also, check out this forum thread.
And a more clear reference from here:
%CmdCmdLine%
will return the entire command line as passed to CMD.EXE
%*
will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces)
%~dn
will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC)
%~pn
will return the directory of %n if %n is a valid path or file name (no UNC)
%~nn
will return the file name only of %n if %n is a valid file name
%~xn
will return the file extension only of %n if %n is a valid file name
%~fn
will return the fully qualified path of %n if %n is a valid file name or directory
Just found some good reference for the mysterious ~
tilde operator.
The %~
string is called percent tilde operator. You can find it in situations like: %~0
.
The :~
string is called colon tilde operator. You can find it like %SOME_VAR:~0,-1%
.
%1-%9
refer to the command line args. If they are not valid path values, %~dp1
- %~dp9
will all expand to the same value as %~dp0
. But if they are valid path values, they will expand to their own driver/path value.
For example: (batch.bat)
@echo off
@echo ~dp0= %~dp0
@echo ~dp1= %~dp1
@echo ~dp2= %~dp2
@echo on
Run 1:
D:\Workbench>batch arg1 arg2
~dp0= D:\Workbench\
~dp1= D:\Workbench\
~dp2= D:\Workbench\
Run 2:
D:\Workbench>batch c:\123\a.exe e:\abc\b.exe
~dp0= D:\Workbench\
~dp1= c:\123\
~dp2= e:\abc\
There are three possible ways to do that.
Option
SELECT lt.* FROM table_left lt
LEFT JOIN
table_right rt
ON rt.value = lt.value
WHERE rt.value IS NULL
Option
SELECT lt.* FROM table_left lt
WHERE lt.value NOT IN
(
SELECT value
FROM table_right rt
)
Option
SELECT lt.* FROM table_left lt
WHERE NOT EXISTS
(
SELECT NULL
FROM table_right rt
WHERE rt.value = lt.value
)
There are many ways to check if a checkbox is checked or not:
Way to check using jQuery
if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))
Check example or also document:
I had to accept the XCode license after my first install before I could run it. You can run the following to get the license prompt via command line. You have to type agree
and confirm as well.
sudo xcodebuild -license
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
Key codes can differ between browsers, so you may need to check for more than just 115.
You can create a SP with the code below - it supports NULLS as well.
select 'my_table_name' into @tableName;
/*find column names*/
select GROUP_CONCAT(column_name SEPARATOR ', ') from information_schema.COLUMNS
where table_schema =DATABASE()
and table_name = @tableName
group by table_name
into @columns
;
/*wrap with IFNULL*/
select replace(@columns,',',',IFNULL(') into @selectColumns;
select replace(@selectColumns,',IFNULL(',',\'~NULL~\'),IFNULL(') into @selectColumns;
select concat('IFNULL(',@selectColumns,',\'~NULL~\')') into @selectColumns;
/*RETRIEVE COLUMN DATA FIELDS BY PK*/
SELECT
CONCAT(
'SELECT CONCAT_WS(','''\'\',\'\''',' ,
@selectColumns,
') AS all_columns FROM ',@tableName, ' where id = 5 into @values;'
)
INTO @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
/*Create Insert Statement*/
select CONCAT('insert into ',@tableName,' (' , @columns ,') values (\'',@values,'\')') into @prepared;
/*UNWRAP NULLS*/
select replace(@prepared,'\'~NULL~\'','NULL') as statement;
There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.
Update:
As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile
to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile
on OS X now requires the output to be a socket and the code won't work!
The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.
#include <fcntl.h>
#include <unistd.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <copyfile.h>
#else
#include <sys/sendfile.h>
#endif
int OSCopyFile(const char* source, const char* destination)
{
int input, output;
if ((input = open(source, O_RDONLY)) == -1)
{
return -1;
}
if ((output = creat(destination, 0660)) == -1)
{
close(input);
return -1;
}
//Here we use kernel-space copying for performance reasons
#if defined(__APPLE__) || defined(__FreeBSD__)
//fcopyfile works on FreeBSD and OS X 10.5+
int result = fcopyfile(input, output, 0, COPYFILE_ALL);
#else
//sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
off_t bytesCopied = 0;
struct stat fileinfo = {0};
fstat(input, &fileinfo);
int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
#endif
close(input);
close(output);
return result;
}
EDIT: Replaced the opening of the destination with the call to creat()
as we want the flag O_TRUNC
to be specified. See comment below.
We can add drawable .xml like below
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1dp"
android:color="@color/color_C4CDD5"/>
<corners android:radius="8dp"/>
<solid
android:color="@color/color_white"/>
</shape>
A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2]
have only two index 0, 1 available but you are trying to access the 3rd index.
This is a simple solution where we do not need to use JSON
public interface RegisterAPI {
@FormUrlEncoded
@POST("/RetrofitExample/insert.php")
public void insertUser(
@Field("name") String name,
@Field("username") String username,
@Field("password") String password,
@Field("email") String email,
Callback<Response> callback);
}
method to send data
private void insertUser(){
//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
RegisterAPI api = adapter.create(RegisterAPI.class);
//Defining the method insertuser of our interface
api.insertUser(
//Passing the values by getting it from editTexts
editTextName.getText().toString(),
editTextUsername.getText().toString(),
editTextPassword.getText().toString(),
editTextEmail.getText().toString(),
//Creating an anonymous callback
new Callback<Response>() {
@Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
//Initializing buffered reader
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
}
@Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
}
}
);
}
Now we can get the post request using php aur any other server side scripting.
Source Android Retrofit Tutorial
If you have run php artisan config:cache
on your server, then your Laravel app could cache outdated config settings that you've put in the .env
file.
Run php artisan config:clear
to fix that.
Take out the parentheses and the curly braces, neither are required when adding columns.
Left Click on the WAMP icon the system try -> PHP -> PHP Extensions -> Enable php_curl
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
To make it easier to invoke MySQL programs, you can add the path name of the MySQL bin directory to your Windows system PATH environment variable:
On the Windows desktop, right-click the My Computer icon, and select Properties.
Next select the Advanced tab from the System Properties menu that appears, and click the Environment Variables button.
Under System Variables, select Path, and then click the Edit button. The Edit System Variable dialogue should appear.
Place your cursor at the end of the text appearing in the space marked Variable Value. (Use the End key to ensure that your cursor is positioned at the very end of the text in this space.) Then enter the complete path name of your MySQL bin directory (for example, C:\Program Files\MySQL\MySQL Server 8.0\bin
).
Open a different terminal and if you are using root as user run mysql -u root -p
else use the a different username you created.
Yes, it is significantly slower. We were running some code that did that, and while I don't have the metrics available at the moment, the end result was that we had to refactor that code to not use reflection. If you know what the class is, just call the constructor directly.
I did all above and spent an hour on the issue.
Tried everything above as well as restarted Xcode.
Finally, restarted computer and everything working normally again!
java.util.Date represents a date/time down to milliseconds. You don't have an option but to include a time with it. You could try zeroing out the time, but then timezones and daylight savings will come into play--and that can screw things up down the line (e.g. 21/03/2012 0:00 GMT is 20/03/2012 PDT).
What you might want is a java.sql.Date
to represent only the date portion (though internally it still uses ms).
If key is present table.put(key, val)
will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
you can get the value from a map by using key is table.get(key);
That's about it
String text = readFileAsString("textfile.txt").replaceAll("\n", "");
Even though the definition of trim() in oracle website is "Returns a copy of the string, with leading and trailing whitespace omitted."
the documentation omits to say that new line characters (leading and trailing) will also be removed.
In short
String text = readFileAsString("textfile.txt").trim();
will also work for you.
(Checked with Java 6)
Here's the way I was able to truncate and not round:
select 100.0019-(100.0019%.001)
returns 100.0010
And your example:
select 123.456-(123.456%.001)
returns 123.450
Now if you want to get rid of the ending zero, simply cast it:
select cast((123.456-(123.456%.001)) as decimal (18,2))
returns 123.45
This is a universal wrapper for hover written in typescript. The component will apply style passed via props 'hoverStyle' on hover event.
import React, { useState } from 'react';
export const Hover: React.FC<{
style?: React.CSSProperties;
hoverStyle: React.CSSProperties;
}> = ({ style = {}, hoverStyle, children }) => {
const [isHovered, setHovered] = useState(false);
const calculatedStyle = { ...style, ...(isHovered ? hoverStyle : {}) };
return (
<div
style={calculatedStyle}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
{children}
</div>
);
};
error 'Class' does not name a type
Just in case someone does the same idiotic thing I did ... I was creating a small test program from scratch and I typed Class instead of class (with a small C). I didn't take any notice of the quotes in the error message and spent a little too long not understanding my problem.
My search for a solution brought me here so I guess the same could happen to someone else.
As mentioned in comments, you are still able to access element by navigating between elements by using tab key. so I recommend this :
$("#mydiv")
.css({"pointer-events" : "none" , "opacity" : "0.4"})
.attr("tabindex" , "-1");
Unlike in the case of Angular, in React.js you need to update the state manually. You can do something like this:
<input
className="form-control"
type="text" value={this.state.name}
id={'todoName' + this.props.id}
onChange={e => this.onTodoChange(e.target.value)}
/>
And then in the function:
onTodoChange(value){
this.setState({
name: value
});
}
Also, you can set the initial state in the constructor of the component:
constructor (props) {
super(props);
this.state = {
updatable: false,
name: props.name,
status: props.status
};
}
What I use for IsNotNullOrEmptyOrWhiteSpace
in T-SQL is:
SELECT [column_name] FROM [table_name]
WHERE LEN(RTRIM(ISNULL([column_name], ''))) > 0
For google chrome autocomplete, this worked for me:
if ($("#textbox").is(":-webkit-autofill"))
{
// the value in the input field of the form was filled in with google chrome autocomplete
}
Creating a virtual environment for Jupyter Notebooks
A minimal Python install is
sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip
Then you can create and use the environment
/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate
You can make a kernel for Jupyter with
ipython3 kernel install --user --name=test
Pickle save:
try:
import cPickle as pickle
except ImportError: # Python 3.x
import pickle
with open('data.p', 'wb') as fp:
pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)
See the pickle module documentation for additional information regarding the protocol
argument.
Pickle load:
with open('data.p', 'rb') as fp:
data = pickle.load(fp)
JSON save:
import json
with open('data.json', 'w') as fp:
json.dump(data, fp)
Supply extra arguments, like sort_keys
or indent
, to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure with indent=N
spaces.
json.dump(data, fp, sort_keys=True, indent=4)
JSON load:
with open('data.json', 'r') as fp:
data = json.load(fp)
Matching any text but those matching a pattern is usually achieved with splitting the string with the regex pattern.
Examples:
Regex.Split(text, @"red|green|blue")
or, to get rid of empty values, Regex.Split(text, @"red|green|blue").Where(x => !string.IsNullOrEmpty(x))
(see demo)Regex.Split(text, "red|green|blue")
or, to remove empty items, Regex.Split(text, "red|green|blue").Where(Function(s) Not String.IsNullOrWhitespace(s))
(see demo, or this demo where LINQ is supported)text.split(/red|green|blue/)
(no need to use g
modifier here!) (to get rid of empty values, use text.split(/red|green|blue/).filter(Boolean)
), see demotext.split("red|green|blue")
, or - to keep all trailing empty items - use text.split("red|green|blue", -1)
, or to remove all empty items use more code to remove them (see demo)text.split(/red|green|blue/)
, to get all trailing items use text.split(/red|green|blue/, -1)
and to remove all empty items use text.split(/red|green|blue/).findAll {it != ""})
(see demo)text.split(Regex("red|green|blue"))
or, to remove blank items, use text.split(Regex("red|green|blue")).filter{ !it.isBlank() }
, see demotext.split("red|green|blue")
, or to keep all trailing empty items, use text.split("red|green|blue", -1)
and to remove all empty items, use text.split("red|green|blue").filter(_.nonEmpty)
(see demo)text.split(/red|green|blue/)
, to get rid of empty values use .split(/red|green|blue/).reject(&:empty?)
(and to get both leading and trailing empty items, use -1
as the second argument, .split(/red|green|blue/, -1)
) (see demo)my @result1 = split /red|green|blue/, $text;
, or with all trailing empty items, my @result2 = split /red|green|blue/, $text, -1;
, or without any empty items, my @result3 = grep { /\S/ } split /red|green|blue/, $text;
(see demo)preg_split('~red|green|blue~', $text)
or preg_split('~red|green|blue~', $text, -1, PREG_SPLIT_NO_EMPTY)
to output no empty items (see demo)re.split(r'red|green|blue', text)
or, to remove empty items, list(filter(None, re.split(r'red|green|blue', text)))
(see demo)regexp.MustCompile("red|green|blue").Split(text, -1)
, and if you need to remove empty items, use this code. See Go demo.NOTE: If you patterns contain capturing groups, regex split functions/methods may behave differently, also depending on additional options. Please refer to the appropriate split method documentation then.
here is the example which i used to retrive and parse json data from s3.
var params = {Bucket: BUCKET_NAME, Key: KEY_NAME};
new AWS.S3().getObject(params, function(err, json_data)
{
if (!err) {
var json = JSON.parse(new Buffer(json_data.Body).toString("utf8"));
// PROCESS JSON DATA
......
}
});
I use Portable winpython in Windows, it includes IPython QT console, I could achieve the following.
>>>print ("??")
??
>>>print ("????")
????
>>>str = "??"
>>>print (str)
??
your console interpreter should support unicode in order to show unicode characters.
I used this regex expression (".*[a-zA-Z]+.*")
. With if not
statement it will avoid all expressions that have a letter before, at the end or between any type of other character.
String strWithLetters = "123AZ456";
if(! Pattern.matches(".*[a-zA-Z]+.*", str1))
return true;
else return false
Yes, people use these terms interchangeably with regard to MySQL. Though oftentimes you will hear people inappropriately refer to the entire database server as the database.
You can define a Root ng-App and in this ng-App you can define multiple nd-Controler. Like this
<!DOCTYPE html>
<html>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController1', function ($scope) {
$scope.student = {
firstName: "MUKESH",
lastName: "Paswan",
fullName: function () {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
mainApp.controller('studentController2', function ($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees: 500,
subjects: [
{ name: 'Physics', marks: 70 },
{ name: 'Chemistry', marks: 80 },
{ name: 'Math', marks: 65 },
{ name: 'English', marks: 75 },
{ name: 'Hindi', marks: 67 }
],
fullName: function () {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
<body>
<div ng-app = "mainApp">
<div id="dv1" ng-controller = "studentController1">
Enter first name: <input type = "text" ng-model = "student.firstName"><br/><br/> Enter last name: <input type = "text" ng-model = "student.lastName"><br/>
<br/>
You are entering: {{student.fullName()}}
</div>
<div id="dv2" ng-controller = "studentController2">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td>
<input type = "text" ng-model = "student.lastName">
</td>
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table>
<tr>
<th>Name</th>.
<th>Marks</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
The posts here help me a lot on my way to find a solution for the Uncaught TypeError: Cannot read property 'value' of undefined issue.
There are already here many answers which are correct, but what we don't have here is the combination for 2 answers that i think resolve this issue completely.
function myFunction(field, data){
if (typeof document.getElementsByName("+field+")[0] != 'undefined'){
document.getElementsByName("+field+")[0].value=data;
}
}
The difference is that you make a check(if a property is defined or not) and if the check is true then you can try to assign it a value.
DocStoc.com and Scribd.com both work well with Internet Explorer 6 and Internet Explorer 7. They'll show a variety of document types, including PowerPoint files (.ppt). I use these services for my intranet here at work. Of course, just remember to mark your documents as 'private' after you upload them.
Here is one without parentheses
[io.fileinfo] 'c:\temp\myfile.txt' | % basename
You can set your test properties in src/test/resources/config/application.yml
file. Spring Boot test cases will take properties from application.yml
file in test directory.
The config
folder is predefined in Spring Boot.
As per documentation:
If you do not like application.properties as the configuration file name, you can switch to another file name by specifying a spring.config.name environment property. You can also refer to an explicit location by using the spring.config.location environment property (which is a comma-separated list of directory locations or file paths). The following example shows how to specify a different file name:
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
The same works for application.yml
Documentation:
I am late to the party, but for option #1, I would go with IdentityServer3(.NET 4.6 or below) or IdentityServer4 (compatible with Core) .
You can reuse your existing user store in your app and plug that to be IdentityServer's User Store. Then the clients must be pointed to your IdentityServer as the open id provider.
Kinda. You could check the __length_hint__
method, but be warned that (at least up to Python 3.4, as gsnedders helpfully points out) it's a undocumented implementation detail (following message in thread), that could very well vanish or summon nasal demons instead.
Otherwise, no. Iterators are just an object that only expose the next()
method. You can call it as many times as required and they may or may not eventually raise StopIteration
. Luckily, this behaviour is most of the time transparent to the coder. :)
here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).
<html>
<head>
<title>An example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function call_counter(url, pk) {
window.open(url);
$.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
alert("counter updated!");
});
}
</script>
</head>
<body>
<button onclick="call_counter('http://www.google.com', 12345);">
I update object 12345
</button>
<button onclick="call_counter('http://www.yahoo.com', 999);">
I update object 999
</button>
</body>
</html>
Alternative approach
Instead of placing the JavaScript code, you can change your link in this way:
<a target="_blank"
class="btn btn-info pull-right"
href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
Check It Out
</a>
and in your views.py
:
def YOUR_VIEW_DEF(request, pk):
YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
return HttpResponseRedirect(request.GET.get('next')))
use google Guava and do it in 2 lines:
import java.util.Map;
import com.google.common.base.Splitter;
public class Parser {
public static void main(String... args) {
String uri = "https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback";
String query = uri.split("\\?")[1];
final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(query);
System.out.println(map);
}
}
which gives you
{client_id=SS, response_type=code, scope=N_FULL, access_type=offline, redirect_uri=http://localhost/Callback}
Streams (InputStream
and OutputStream
) transfer binary data. If you want to write a string to a stream, you must first convert it to bytes, or in other words encode it. You can do that manually (as you suggest) using the String.getBytes(Charset)
method, but you should avoid the String.getBytes()
method, because that uses the default encoding of the JVM, which can't be reliably predicted in a portable way.
The usual way to write character data to a stream, though, is to wrap the stream in a Writer
, (often a PrintWriter
), that does the conversion for you when you call its write(String)
(or print(String)
) method. The corresponding wrapper for InputStreams is a Reader.
PrintStream
is a special OutputStream
implementation in the sense that it also contain methods that automatically encode strings (it uses a writer internally). But it is still a stream. You can safely wrap your stream with a writer no matter if it is a PrintStream
or some other stream implementation. There is no danger of double encoding.
Example of PrintWriter with OutputStream:
try (PrintWriter p = new PrintWriter(new FileOutputStream("output-text.txt", true))) {
p.println("Hello");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
import pandas as pd
dataset = pd.read_csv('/home/nspython/Downloads/movie_metadata1.csv')
If HTML and use bootstrap they have a helper class.
<span class="text-nowrap">1-866-566-7233</span>
When we try to drop a column which is depended upon then we see this kind of error:
The object 'DF__*' is dependent on column ''.
drop the constraint which is dependent on that column with:
ALTER TABLE TableName DROP CONSTRAINT dependent_constraint;
Example:
Msg 5074, Level 16, State 1, Line 1
The object 'DF__Employees__Colf__1273C1CD' is dependent on column 'Colf'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN Colf failed because one or more objects access this column.
Drop Constraint(DF__Employees__Colf__1273C1CD):
ALTER TABLE Employees DROP CONSTRAINT DF__Employees__Colf__1273C1CD;
Then you can Drop Column:
Alter Table TableName Drop column ColumnName
Inside your current folder, simply press Shift+Alt+F --then--> Enter.
The prompt will appear with your current folder's path set.
Note: That works only in Windows 7 / Vista. What it does is that drops the "File" menu down for you, because the "Shift" key is pressed the option "Open command window here" is enabled and focused as the first available option of "File" menu. Pressing enter starts the focused option therefor the command window.
Edit:
In case you are in a folder and you already selected some of its contents (file/folder) this wont work. In that case Click on the empty area inside the folder to deselect any previously selected files and repeat.
Edit2:
Another way you can open terminal in current directory is to type cmd
on file browser navigation bar where the path of current folder is written.
In order to focus with your keyboard on the navigation bar Ctrl+L. Then you can type cmd
and hit Enter
One needs to understand what a JOIN or a series of JOINs does to a set of data. With strae's post, a pe_id of 1 joined with corresponding order and items on pe_id = 1 will give you the following data to "select" from:
[ table people portion ] [ table orders portion ] [ table items portion ]
| people.pe_id | people.pe_name | orders.ord_id | orders.pe_id | orders.ord_title | item.item_id | item.ord_id | item.pe_id | item.title |
| 1 | Foo | 1 | 1 | First order | 1 | 1 | 1 | Apple |
| 1 | Foo | 1 | 1 | First order | 2 | 1 | 1 | Pear |
The joins essentially come up with a cartesian product of all the tables. You basically have that data set to select from and that's why you need a distinct count on orders.ord_id and items.item_id. Otherwise both counts will result in 2 - because you effectively have 2 rows to select from.
You can use jQuery:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
An example of Dave Syer's answer:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyWebMvcConfig {
@Bean
public WebMvcConfigurerAdapter forwardToIndex() {
return new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// forward requests to /admin and /user to their index.html
registry.addViewController("/admin").setViewName(
"forward:/admin/index.html");
registry.addViewController("/user").setViewName(
"forward:/user/index.html");
}
};
}
}
To simply append to a file in powershell,you can use add-content.
So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.
$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file
Or,
"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file
This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.
Regarding the original question asked in the title ...
sudo apt-get install libtcnative-1
or if you are on RHEL Linux yum install tomcat-native
The documentation states you need http://tomcat.apache.org/native-doc/
sudo apt-get install libapr1.0-dev libssl-dev
yum install apr-devel openssl-devel
This is how it was on the Microsoft site, with me just tweaking the SPSite and SPWeb since these might vary from environment to environment and it helps not to have to hard-code these:
using (SPSite oSiteCollection = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb oWeb = oSiteCollection.OpenWeb(SPContext.Current.Web))
{
SPList oList = oWeb.Lists["Announcements"];
// You may also use
// SPList oList = oWeb.GetList("/Lists/Announcements");
// to avoid querying all of the sites' lists
SPListItem oListItem = oList.Items.Add();
oListItem["Title"] = "My Item";
oListItem["Created"] = new DateTime(2004, 1, 23);
oListItem["Modified"] = new DateTime(2005, 10, 1);
oListItem["Author"] = 3;
oListItem["Editor"] = 3;
oListItem.Update();
}
}
Source: SPListItemClass (Microsoft.SharePoint). (2012). Retrieved February 22, 2012, from http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx.
You can solve it by adding these two lines in the VERY beginning of your .py script.
import matplotlib
matplotlib.use('Agg')
PS: The error will still exists if these two lines are not added in the very beginning of the source code.
Use FOR XML PATH('')
- which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result
SELECT STUFF((SELECT ',' + INSTITUTIONNAME
FROM EDUCATION EE
WHERE EE.STUDENTNUMBER=E.STUDENTNUMBER
ORDER BY sortOrder
FOR XML PATH('')), 1, 1, '') AS listStr
FROM EDUCATION E
GROUP BY E.STUDENTNUMBER
Here is the FIDDLE
C has always been very specific about the initial values of objects. If global or static
, they will be zeroed. If auto
, the value is indeterminate.
This was the case in pre-C89 compilers and was so specified by K&R and in DMR's original C report.
This was the case in C89, see section 6.5.7 Initialization.
If an object that has automatic storage duration is not initialized explicitely, its value is indeterminate. If an object that has static storage duration is not initialized explicitely, it is initialized implicitely as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
This was the case in C99, see section 6.7.8 Initialization.
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.
As to what exactly indeterminate means, I'm not sure for C89, C99 says:
3.17.2
indeterminate value
either an unspecified value or a trap representation
But regardless of what standards say, in real life, each stack page actually does start off as zero, but when your program looks at any auto
storage class values, it sees whatever was left behind by your own program when it last used those stack addresses. If you allocate a lot of auto
arrays you will see them eventually start neatly with zeroes.
You might wonder, why is it this way? A different SO answer deals with that question, see: https://stackoverflow.com/a/2091505/140740
Here is a simple way to define those constants, and I'm pretty sure it's portable:
const double inf = 1.0/0.0;
const double nan = 0.0/0.0;
When I run this code:
printf("inf = %f\n", inf);
printf("-inf = %f\n", -inf);
printf("nan = %f\n", nan);
printf("-nan = %f\n", -nan);
I get:
inf = inf
-inf = -inf
nan = -nan
-nan = nan
public static string ConvertIntoJson(DataTable dt)
{
var jsonString = new StringBuilder();
if (dt.Rows.Count > 0)
{
jsonString.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
jsonString.Append("\"" + dt.Columns[j].ColumnName + "\":\""
+ dt.Rows[i][j].ToString().Replace('"','\"') + (j < dt.Columns.Count - 1 ? "\"," : "\""));
jsonString.Append(i < dt.Rows.Count - 1 ? "}," : "}");
}
return jsonString.Append("]").ToString();
}
else
{
return "[]";
}
}
public static string ConvertIntoJson(DataSet ds)
{
var jsonString = new StringBuilder();
jsonString.Append("{");
for (int i = 0; i < ds.Tables.Count; i++)
{
jsonString.Append("\"" + ds.Tables[i].TableName + "\":");
jsonString.Append(ConvertIntoJson(ds.Tables[i]));
if (i < ds.Tables.Count - 1)
jsonString.Append(",");
}
jsonString.Append("}");
return jsonString.ToString();
}
Take a look at the FormBorderStyle property
form1.FormBorderStyle = FormBorderStyle.FixedSingle;
You may also want to remove the minimize and maximize buttons:
form1.MaximizeBox = false;
form1.MinimizeBox = false;
This question has been answered but I feel I should also mention another potential cause. This is a direct result of coming across the same error message but for different reasons. If your list/s are empty the operation will not be performed. check your code for indents and typos
These answers all collect shallow size information. I suspect that visitors to this question will end up here looking to answer the question, "How big is this complex object in memory?"
There's a great answer here: https://goshippo.com/blog/measure-real-size-any-python-object/
The punchline:
import sys
def get_size(obj, seen=None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([get_size(v, seen) for v in obj.values()])
size += sum([get_size(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, seen) for i in obj])
return size
Used like so:
In [1]: get_size(1)
Out[1]: 24
In [2]: get_size([1])
Out[2]: 104
In [3]: get_size([[1]])
Out[3]: 184
If you want to know Python's memory model more deeply, there's a great article here that has a similar "total size" snippet of code as part of a longer explanation: https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609
In my case (Mac High Sierra) it was installed at ~/opt/anaconda3.
How about mkString ?
theStrings.mkString(",")
A variant exists in which you can specify a prefix and suffix too.
See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.
Extending on Adam Rosenfield's answer for Windows.
I tested this code with on both VS2013 Update 4 and VS2015 preview:
// test.c
#include <stdio.h>
#include <BaseTsd.h> // see the note below
int main()
{
size_t x = 1;
SSIZE_T y = 2;
printf("%zu\n", x); // prints as unsigned decimal
printf("%zx\n", x); // prints as hex
printf("%zd\n", y); // prints as signed decimal
return 0;
}
VS2015 generated binary outputs:
1
1
2
while the one generated by VS2013 says:
zu
zx
zd
Note: ssize_t
is a POSIX extension and SSIZE_T
is similar thing in Windows Data Types, hence I added <BaseTsd.h>
reference.
Additionally, except for the follow C99/C11 headers, all C99 headers are available in VS2015 preview:
C11 - <stdalign.h>
C11 - <stdatomic.h>
C11 - <stdnoreturn.h>
C99 - <tgmath.h>
C11 - <threads.h>
Also, C11's <uchar.h>
is now included in latest preview.
For more details, see this old and the new list for standard conformance.
For Chrome, instead of
response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);
you need to add Content-Security-Policy
string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);
to the HTTP-response-headers.
Note that this assumes you checked on the server whether or not refAuth is allowed.
And also, note that you need to do browser-detection in order to avoid adding the allow-from
header for Chrome (outputs error on console).
For details, see my answer here.
This is pretty old, but if you completely remove the cmake-build-debug folder, when you compile using cmake it should automatically create a new cmake-build-debug folder with everything you need. Works especially well in CLion.
Press Ctrl+F5 in browser window
It's just as simple as adding this:
legend: {
display: false,
}
// Or if you want you could use this other option which should also work:
Chart.defaults.global.legend.display = false;
Here is my answer:
def draw_text(text, font_name, size, color, x, y, align="nw"):
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
if align == "nw":
text_rect.topleft = (x, y)
if align == "ne":
text_rect.topright = (x, y)
if align == "sw":
text_rect.bottomleft = (x, y)
if align == "se":
text_rect.bottomright = (x, y)
if align == "n":
text_rect.midtop = (x, y)
if align == "s":
text_rect.midbottom = (x, y)
if align == "e":
text_rect.midright = (x, y)
if align == "w":
text_rect.midleft = (x, y)
if align == "center":
text_rect.center = (x, y)
screen.blit(text_surface, text_rect)
Of course, you'll need to import pygame, a font and a screen, but this is just a def to add on to the rest of the code, and then call "draw_text".
Example
find <path> -name *FileName*
From manual:
find -name pattern
Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories are removed, the file names considered for a match with -name will never include a slash, so "-name a/b" will never match anything (you probably need to use -path instead). The metacharacters ("*", "?", and "[]") match a "." at the start of the base name (this is a change in find- utils-4.2.2; see section STANDARDS CONFORMANCE below). To ignore a directory and the files under it, use -prune; see an example in the description of -path. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell.
You can see all the version of a module with npm view
.
eg: To list all versions of bootstrap including beta.
npm view bootstrap versions
But if the version list is very big it will truncate. An --json
option will print all version including beta versions as well.
npm view bootstrap versions --json
If you want to list only the stable versions not the beta then use singular version
npm view bootstrap@* versions
Or
npm view bootstrap@* versions --json
And, if you want to see only latest version then here you go.
npm view bootstrap version
Had the same issue with target version 19
on both project.properties
and AndroidManifest.xml
with Ant.
Fixed it by:
Android SDK Build-Tools 19.0.1
Android SDK Build-Tools 19.0.2
I think @Al-Kathiri-Khalid is spot on. The issue is only due to missing support for the API level in Build Tools.
The reason for this error is because there is a mismatch of the ABI between your app and the native library you linked against. Another words, your app and your .so
is targeting different ABI.
if you create your app using latest Android Studio templates, its probably targeting the arm64-v8a
but your .so
may be targeting armeabi-v7a
for example.
There is 2 way to solve this problem:
.so
built against.Choice 2 is dirty but I think you probably have more interested in:
change your app's build.gradle
android {
defaultConfig {
...
ndk {
abiFilters 'armeabi-v7a'
}
}
}
Just to add to the answers above,
I was having a 2 regular buttons as shown below. (No type="submit"anywhere)
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.
As a workaround,
I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.
<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
Well, my intention was never to submit on Enter, so the above given hack just works fine.
I haven't seen a JavaScript answer without jQuery. Hopefully it helps someone.
var elements = document.querySelectorAll('[data-customerID="22"]');_x000D_
_x000D_
elements[0].innerHTML = 'it worked!';
_x000D_
<a data-customerID='22'>test</a>
_x000D_
They are indeed fools. If you look at RFC 3986 Appendix A, you will see that "space" is simply not mentioned anywhere in the grammar for defining a URL. Since it's not mentioned anywhere in the grammar, the only way to encode a space is with percent-encoding (%20
).
In fact, the RFC even states that spaces are delimiters and should be ignored:
In some cases, extra whitespace (spaces, line-breaks, tabs, etc.) may have to be added to break a long URI across lines. The whitespace should be ignored when the URI is extracted.
and
For robustness, software that accepts user-typed URI should attempt to recognize and strip both delimiters and embedded whitespace.
Curiously, the use of +
as an encoding for space isn't mentioned in the RFC, although it is reserved as a sub-delimeter. I suspect that its use is either just convention or covered by a different RFC (possibly HTTP).
You should use the Time.IsZero() function instead:
func (Time) IsZero
func (t Time) IsZero() bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
use this
select * from xxx where dates between '10/oct/2012' and '10/dec/2012'
you are entering string, So give the name of month as according to format...
springframework library Check whether the given String is empty.
f(StringUtils.isEmpty(str)) {
//.... String is blank or null
}
Try to change this: <csrf />
to this : <csrf disabled="true"/>
. It should disable csfr.
Adding context to hopefully help provide a bit of additional clarity on this subject. To a BaSH newbie, it's sense of true/false statements is rather odd. Take the following simple examples and their results.
This statement will return "true":
foo=" "; if [ "$foo" ]; then echo "true"; else echo "false"; fi
But this will return "false":
foo=" "; if [ $foo ]; then echo "true"; else echo "false"; fi
Do you see why? The first example has a quoted "" string. This causes BaSH to treat it literally. So, in a literal sense, a space is not null. While in a non-literal sense (the 2nd example above), a space is viewed by BaSH (as a value in $foo) as 'nothing' and therefore it equates to null (interpreted here as 'false').
These statements will all return a text string of "false":
foo=; if [ $foo ]; then echo "true"; else echo "false"; fi
foo=; if [ "$foo" ]; then echo "true"; else echo "false"; fi
foo=""; if [ $foo ]; then echo "true"; else echo "false"; fi
foo=""; if [ "$foo" ]; then echo "true"; else echo "false"; fi
Interestingly, this type of conditional will always return true:
These statements will all return a result of "true":
foo=""; if [ foo ]; then echo "true"; else echo "false"; fi
Notice the difference; the $ symbol has been omitted from preceding the variable name in the conditional. It doesn't matter what word you insert between the brackets. BaSH will always see this statement as true, even if you use a word that has never been associated with a variable in the same shell before.
if [ sooperduper ]; then echo "true"; else echo "false"; fi
Likewise, defining it as an undeclared variable ensures it will always return false:
if [ $sooperduper ]; then echo "true"; else echo "false"; fi
As to BaSH it's the same as writing:
sooperduper="";if [ $sooperduper ]; then echo "true"; else echo "false"; fi
One more tip....
Brackets vs No Brackets
Making matters more confusing, these variations on the IF/THEN conditional both work, but return opposite results.
These return false:
if [ $foo ]; then echo "true"; else echo "false"; fi
if [ ! foo ]; then echo "true"; else echo "false"; fi
However, these will return a result of true:
if $foo; then echo "true"; else echo "false"; fi
if [ foo ]; then echo "true"; else echo "false"; fi
if [ ! $foo ]; then echo "true"; else echo "false"; fi
And, of course this returns a syntax error (along with a result of 'false'):
if foo; then echo "true"; else echo "false"; fi
Confused yet? It can be quite challenging to keep it straight in your head in the beginning, especially if you're used to other, higher level programming languages.
Like Jan It took me a while to get it .. =S So for anyone else who's blinded with frustration.
The Main Reason for the denying permission is that we don’t have permission for drawing over another apps,We have to provide the permission for the Drawing over other apps that can be done by the following code
Request code for Permission
public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 5469;
add this in your MainActivity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
askPermission();
}
private void askPermission() {
Intent intent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName()));
startActivityForResult(intent,ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
Add this also
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE){
if(!Settings.canDrawOverlays(this)){
askPermission();
}
}
}
You can easily use the formula
distance = np.sqrt(np.sum(np.square(a-b)))
which does actually nothing more than using Pythagoras' theorem to calculate the distance, by adding the squares of ?x, ?y and ?z and rooting the result.
You want to pass these extra parameters to subprocess.Popen
:
bufsize=1, universal_newlines=True
Then you can iterate as in your example. (Tested with Python 3.5)
I would strongly suggest you start using jQuery. Your code would look like:
$(function() {
$('form[name="myform"]').submit(function(e) {
var username = $('form[name="myform"] input[name="username"]').val();
if ( username == '') {
e.preventDefault();
$('#errors').text('*Please enter a username*');
}
});
});
If you are on xampp and using phpMyadmin to import large sql files and you have increased max_execution time, max file upload limit and everything needed And If none of the above answers work for you come here
Go to your xampp folder, in my case here is the relative path to the file that I need to modify: C:\xampp\phpMyAdmin\libraries\config.default.php
/**
* maximum execution time in seconds (0 for no limit)
*
* @global integer $cfg['ExecTimeLimit']
* by defautlt 300 is the value
* change it to 0 for unlimited
* time is seconds
* Line 709 for me
*/
$cfg['ExecTimeLimit'] = 0;
I have just spend three days on this nightmare. Ideally, you should have a backup that you can restore, then simply drop the damaged table. These sorts of errors can cause your ibdata1 to grow huge (100GB+ in size for modest tables)
If you don't have a recent backup, such as if you relied on mySqlDump, then your backups probably silently broke at some point in the past. You will need to export the databases, which of course you cant do, because you will get lock errors while running mySqlDump.
So, as a workaround, go to /var/log/mysql/database_name/
and remove the table_name.*
Then immediately try to dump the table; doing this should now work. Now restore the database to a new database and rebuild the missing table(s). Then dump the broken database.
In our case we were also constantly getting mysql has gone away
messages at random intervals on all databases; once the damaged database were removed everything went back to normal.
Use this instead:
string objTextBox = t.Text;
The object t
is the TextBox
. The object you call objTextBox
is assigned the ID
property of the TextBox
.
So better code would be:
TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;