That's because there was an error in your query. MySQli->query()
will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
You have to insert your <table>
into a <div>
that it has fixed size, and in <div>
style you have to set overflow: scroll
.
You can split string to the words and check the result list.
if word in string.split():
print 'success'
To change the radio button color programmatically you can use following:
yourradio button name.buttonDrawable?.setColorFilter(Color.parseColor( color_value), PorterDuff.Mode.SRC_ATOP)
I had the same issue.
Solution was to change the platform of my current solution to x64.
To do that in Visual Studio, right click solution > Configuration Manager > Active Solution Platform.
I had a similar requirement on my system and this was my solution:
In MATLAB there is a function called perl.m, which allows you to call perl scripts from MATLAB. Depending on which version you are using it will be located somewhere like
C:\Program Files\MATLAB\R2008a\toolbox\matlab\general\perl.m
Create a copy called python.m, a quick search and replace of perl with python, double check the command path it sets up to point to your installation of python. You should now be able to run python scripts from MATLAB.
Example
A simple squared function in python saved as "sqd.py", naturally if I was doing this properly I'd have a few checks in testing input arguments, valid numbers etc.
import sys
def squared(x):
y = x * x
return y
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
Then in MATLAB
>> r=python('sqd.py','3.5')
r =
12.25
>> r=python('sqd.py','5')
r =
25.0
>>
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Along with the answer given by @Yehuda Shapira I had to make another change which is Delete the .csproj.user file where the binding information like
<IISUrl>http://localhost:54462/</IISUrl>
is stored.Delete that File Close visual Studio and then rebuild.Hope this helps.
Some online API's work pretty well: ocr.space and Google Cloud Vision. Both of these are free, as long as you do less than 1000 OCR's per month. You can drag & drop an image to do a quick manual test to see how they perform for your images.
I find OCR.space easier to use (no messing around with nuget libraries), but, for my purpose, Google Cloud Vision provided slightly better results than OCR.space.
Google Cloud Vision example:
GoogleCredential cred = GoogleCredential.FromJson(json);
Channel channel = new Channel(ImageAnnotatorClient.DefaultEndpoint.Host, ImageAnnotatorClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
ImageAnnotatorClient client = ImageAnnotatorClient.Create(channel);
Image image = Image.FromStream(stream);
EntityAnnotation googleOcrText = client.DetectText(image).First();
Console.Write(googleOcrText.Description);
OCR.space example:
string uri = $"https://api.ocr.space/parse/imageurl?apikey=helloworld&url={imageUri}";
string responseString = WebUtilities.DoGetRequest(uri);
OcrSpaceResult result = JsonConvert.DeserializeObject<OcrSpaceResult>(responseString);
if ((!result.IsErroredOnProcessing) && !String.IsNullOrEmpty(result.ParsedResults[0].ParsedText))
return result.ParsedResults[0].ParsedText;
I know its late replying to this question, but I have recently found a better solution to this problem without installing any plugin. We can create a formatted version number and can then use the variable created to display the build date/time. Steps to create: Build Environment --> Create a formatted version number:
Environment Variable Name: BUILD_DATE
Version Number Format String: ${BUILD_DATE_FORMATTED}
thats it. Just use the variable created above in the email subject line as ${ENV, var="BUILD_DATE"} and you will get the date/time of the current build.
To make it short, it means that you lacked some "dependencies" for the libraries you wanted to use. Before trying to use any kind of library, first it is suggested to look up whether it needs another library in python "family". What do I mean?
Downloading "dlls" is something that I avoid. I had the same problem with another library "kivy". The problem occurred when I wanted to use Python 3.4v instead of 3.5 Everything was working correctly in 3.5 but I just wanted to use the stable version for kivy which is 3.4 as they officially "advise". So, I switched to 3.4 but then I had the very same "dll" error saying lots of things are missing. So I checked the website and learned that I needed to install extra "dependencies" from the official website of kivy, then the problem got solved.
What I'm guessing is that you need to set those input elements to runat="server".
So you won't be able to access the control
<input type="text" name="email" id="myTextBox" />
But you'll be able to work with
<input type="text" name="email" id="myTextBox" runat="server" />
And read from it by using
string myStringFromTheInput = myTextBox.Value;
I would approach this by using re.match
in the following way:
import re
match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
if match:
items = match.groups()
print(items)
>> ("foofo", "21")
That's probably the best from the performance point of view, but it's rough:
String element = "el5";
String s;
int x = element.charAt(2)-'0';
It works if you assume your character is a digit, and only in languages always using Unicode, like Java...
From W3 Schools HTML DOM Changes: If you look at the 3rd example it shows how you can change the text in your link, "click here". Example:
<a id="a_tbnotesverbergen" href="#nothing">click here</a>
JS:
var element=document.getElementById("a_tbnotesverbergen");
element.innerHTML="New Text";
You can use jhat
(Java Heap Analysis Tool) to read the generated file:
jhat [ options ] <heap-dump-file>
The jhat command parses a java heap dump file and launches a webserver. jhat enables you to browse heap dumps using your favorite webbrowser.
Note that you should have a hprof
binary format output to be able to parse it with jhat
. You can use format=b
option to generate the dump in this format.
-dump:format=b,file=<filename>
You have to use the FormulaEvaluator, as shown here. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :
FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
if (cell!=null) {
switch (evaluator.evaluateFormulaCell(cell)) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
System.out.println(cell.getErrorCellValue());
break;
// CELL_TYPE_FORMULA will never occur
case Cell.CELL_TYPE_FORMULA:
break;
}
}
if you need the exact contant (ie the formla if the cell contains a formula), then this is shown here.
Edit : Added a few example to help you.
first you get the cell (just an example)
Row row = sheet.getRow(rowIndex+2);
Cell cell = row.getCell(1);
If you just want to set the value into the cell using the formula (without knowing the result) :
String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)";
cell.setCellFormula(formula);
cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground);
if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like
IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100))
(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error).
if you want to get the value corresponding to the formula, then you have to use the evaluator.
Hope this help,
Guillaume
range = 10..50
rand(range)
or
range.to_a.sample
or
range.to_a.shuffle(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)
You need to create a separate interface for your custom methods:
public interface AccountRepository
extends JpaRepository<Account, Long>, AccountRepositoryCustom { ... }
public interface AccountRepositoryCustom {
public void customMethod();
}
and provide an implementation class for that interface:
public class AccountRepositoryImpl implements AccountRepositoryCustom {
@Autowired
@Lazy
AccountRepository accountRepository; /* Optional - if you need it */
public void customMethod() { ... }
}
See also:
Note that the naming scheme has changed between versions. See https://stackoverflow.com/a/52624752/66686 for details.
See these Date methods ...
Clone the repository as normal:
git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle
Then checkout the tag you want like so:
git checkout tags/1.1.4
This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".
To retain any changes made, move them to a new branch:
git checkout -b 1.1.4-jspooner
You can get back to the master branch by using:
git checkout master
Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:
git checkout 1.1.4
But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:
warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'
The shorthand can be safely used if the repository does not share names between branches and tags.
Here is how I figured it out. I am behind corporate firewall too.
Go to Chrome or your Internet Settings by clicking the wrench in Chrome --> Settings --> Under the Hood --> Network --> Change Proxy Settings
Click on LAN Settings and then Advanced. Copy the proxy server address and port.
Mostly the connection refused link occurs when trying to download SDK packages through Eclipse.
Navigate to the SDK Manager.exe and double click on it. Once it starts click on Tools --> Options and then enter the proxy server address and the Port #
Check the checkbox force https:// to http:// That's it your SDK Manager will now be able to download packages from google remote site without any issue even from behind a firewall.
I am on Windows by the way. Tried everything and this works great.
Some practical uses for the [Serializable]
attribute:
BinaryFormatter
class in System.Runtime.Serialization.Formatters.BinaryClipboard.SetData()
- nonserialisable classes cannot be placed on the clipboard.MarshalByRefObject
) must be serialisable.These are the most common usage cases that I have come across.
I found this extremely helpful, and it solved my problem. This command will allow your 2FA to do its thing (and save you the trouble of entering your username and password):
git config --global --add url."[email protected]:".insteadOf "https://github.com/"
Source: http://albertech.blogspot.com/2016/11/fix-git-error-could-not-read-username.html
If you're not using 2FA, you can still use SSH and this will work.
Edit: added the --add
flag as suggested by slatunje.
class='col-xs-3'
(for example).class="btn-block"
to your buttons. This will provide permanent spacing.
Use obj[0].nick and you will get desired result,
RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).
While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:
Microsoft Internet Explorer (Browser)
Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.
Microsoft Edge (Browser)
The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge
Chrome
It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.
Firefox (Browser)
After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.
Safari (Browser)
At least 80,000 characters will work. Testing was not tried beyond that.
Opera (Browser)
At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable,
copyable and pasteable URL in the location bar even at 190,000 characters.
Apache (Server)
Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.
Microsoft Internet Information Server (Server)
The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.
Perl HTTP::Daemon (Server)
Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.
Try:
float number mkm = (((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt)*1000f;
int newNum = (int) mkm;
mkm = newNum/1000f; // Will return 3 decimal places
For those using Monotouch (Xamarin.iOS), here's Adam's answer, translated to C#:
public class MyTextBox : UITextField
{
public override void DrawPlaceholder(RectangleF rect)
{
UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
new NSString(this.Placeholder).DrawString(rect, Font);
}
}
Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
In my case, I just added this class and use @EnableAutConfiguration
:
@Component
public class SimpleCORSFilter extends GenericFilterBean {
/**
* The Logger for this class.
*/
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
logger.info("> doFilter");
HttpServletResponse response = (HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
//response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, resp);
logger.info("< doFilter");
}
}
A string in Javascript is already a character array.
You can simply access any character in the array as you would any other array.
var s = "overpopulation";
alert(s[0]) // alerts o.
UPDATE
As is pointed out in the comments below, the above method for accessing a character in a string is part of ECMAScript 5 which certain browsers may not conform to.
An alternative method you can use is charAt(index)
.
var s = "overpopulation";
alert(s.charAt(0)) // alerts o.
Ruby aliases the method Array#map to Array#collect; they can be used interchangeably. (Ruby Monk)
In other words, same source code :
static VALUE
rb_ary_collect(VALUE ary)
{
long i;
VALUE collect;
RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
collect = rb_ary_new2(RARRAY_LEN(ary));
for (i = 0; i < RARRAY_LEN(ary); i++) {
rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));
}
return collect;
}
It sounds like you want to convert the rownames to a proper column of the data.frame. eg:
# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF
# Row.Names id val vr2
# row_one row_one A 1 23
# row_two row_two A 2 24
# row_three row_three B 3 25
# row_four row_four C 4 26
If you want to then remove the original rownames:
rownames(myDF) <- NULL
myDF
# Row.Names id val vr2
# 1 row_one A 1 23
# 2 row_two A 2 24
# 3 row_three B 3 25
# 4 row_four C 4 26
Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames
myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat
# Names.of.Rows id val vr2
# row_one "A" "1" "23"
# row_two "A" "2" "24"
# row_three "B" "3" "25"
# row_four "C" "4" "26"
Gson is also good for it: http://code.google.com/p/google-gson/
" Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. "
Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
If you want to use the upstream version:
rm -rf <submodule dir>
git submodule init
git submodule update
If you want an alternative to pickle
or json
, you can use klepto
.
>>> init = {'y': 2, 'x': 1, 'z': 3}
>>> import klepto
>>> cache = klepto.archives.file_archive('memo', init, serialized=False)
>>> cache
{'y': 2, 'x': 1, 'z': 3}
>>>
>>> # dump dictionary to the file 'memo.py'
>>> cache.dump()
>>>
>>> # import from 'memo.py'
>>> from memo import memo
>>> print memo
{'y': 2, 'x': 1, 'z': 3}
With klepto
, if you had used serialized=True
, the dictionary would have been written to memo.pkl
as a pickled dictionary instead of with clear text.
You can get klepto
here: https://github.com/uqfoundation/klepto
dill
is probably a better choice for pickling then pickle
itself, as dill
can serialize almost anything in python. klepto
also can use dill
.
You can get dill
here: https://github.com/uqfoundation/dill
The additional mumbo-jumbo on the first few lines are because klepto
can be configured to store dictionaries to a file, to a directory context, or to a SQL database. The API is the same for whatever you choose as the backend archive. It gives you an "archivable" dictionary with which you can use load
and dump
to interact with the archive.
In this particular case the clearest solution is the S.Lott answer
But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution.
Using De Morgan's law ¬(A^B) = ¬Av¬B
not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step
then
if u0 > u or u >= u0+step:
pass
... in this case the «clear» solution is not more clear :P
I'm actually surprised no one provided my answer. This is what you do (this will work if you have at least 1 eligible device):
You should be able to get your App Preview in the desired resolution.
To start a particular service defined in your docker-compose file. for example if your have a docker-compose.yml
docker-compose start db
given a compose file like as:
version: '3.3'
services:
db:
image: mysql:5.7
ports:
- "3306:3306"
volumes:
- ./db_data:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: yourPassword
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: yourPassword
wordpress:
depends_on:
- db
image: wordpress:latest
ports:
- "80:80"
volumes:
- ./l3html:/var/www/html
restart: always
environment:
WORDPRESS_DB_HOST: db:3306
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: yourPassword
volumes:
db_data:
l3html:
Some times you want to start mySQL only (sometimes you just want to populate a database) before you start your entire suite.
$('#input').on('keyup', function() {
var RegExpression = /^[a-zA-Z\s]*$/;
...
});
\s
will allow the space
Just to add a new method to an old (but still relevant question). In the new portal, clicking the help icon from any screen and selecting 'Show Diagnostics' will show you a JSON document containing all your tenant information including TenantId, Tenant Name, and much, much more useful information
I've had this problem in the past, so I bookmarked this discussion.
To summarize it, you can:
An interesting way to see null in java in my opinion is to see it as something that DOES NOT denote an absence of information but simply as a literal value that can be assigned to a reference of any type. If you think about it if it denoted absence of information then for a1==a2 to be true doesn't make sense (in case they were both assigned a value of null) as they could really could be pointing to ANY object (we simply don't know what objects they should be pointing to)... By the way null == null returns true in java. If java e.g. would be like SQL:1999 then null==null would return unknown (a boolean value in SQL:1999 can take three values : true,false and unknown but in practise unknown is implemented as null in real systems)... http://en.wikipedia.org/wiki/SQL
None of the solutions above work perfectly.They either loses CSS or have to include/edit external CSS file. I found a perfect solution that will not lose your CSS nor you have to edit/add external CSS.
HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p
JQuery:
function printFunc() {
var divToPrint = document.getElementById('printarea');
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += divToPrint.outerHTML;
newWin = window.open("");
newWin.document.write("<h3 align='center'>Print Page</h3>");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
}
Are you asking for renaming column itself or capitalise the data inside column? If its data you've to change, then use this:
UPDATE [yourtable]
SET word=UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word)))
If you just wanted to change it only for displaying and do not need the actual data in table to change:
SELECT UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word))) FROM [yourtable]
Hope this helps.
EDIT: I realised about the '-' so here is my attempt to solve this problem in a function.
CREATE FUNCTION [dbo].[CapitalizeFirstLetter]
(
--string need to format
@string VARCHAR(200)--increase the variable size depending on your needs.
)
RETURNS VARCHAR(200)
AS
BEGIN
--Declare Variables
DECLARE @Index INT,
@ResultString VARCHAR(200)--result string size should equal to the @string variable size
--Initialize the variables
SET @Index = 1
SET @ResultString = ''
--Run the Loop until END of the string
WHILE (@Index <LEN(@string)+1)
BEGIN
IF (@Index = 1)--first letter of the string
BEGIN
--make the first letter capital
SET @ResultString =
@ResultString + UPPER(SUBSTRING(@string, @Index, 1))
SET @Index = @Index+ 1--increase the index
END
-- IF the previous character is space or '-' or next character is '-'
ELSE IF ((SUBSTRING(@string, @Index-1, 1) =' 'or SUBSTRING(@string, @Index-1, 1) ='-' or SUBSTRING(@string, @Index+1, 1) ='-') and @Index+1 <> LEN(@string))
BEGIN
--make the letter capital
SET
@ResultString = @ResultString + UPPER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--increase the index
END
ELSE-- all others
BEGIN
-- make the letter simple
SET
@ResultString = @ResultString + LOWER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--incerase the index
END
END--END of the loop
IF (@@ERROR
<> 0)-- any error occur return the sEND string
BEGIN
SET
@ResultString = @string
END
-- IF no error found return the new string
RETURN @ResultString
END
So then the code would be:
UPDATE [yourtable]
SET word=dbo.CapitalizeFirstLetter([STRING TO GO HERE])
If you are getting 500 - Internal server error that means you don't have permission to set these values by .htaccess. You have to contact your web server providers and ask to set AllowOverride Options
for your host or to put these lines in their virtual host configuration file.
//My Form
<form id="someform">
<div class="input-group">
<textarea placeholder="Post your Comment Here ..." name="post" class="form-control custom-control" rows="3" style="resize:none"></textarea>
<span class="input-group-addon">
<button type="submit" name="post_comment" class="btn btn-primary">
Post
</button>
</span>
</div>
</form>
//your text area get value to URL
<?php
if(isset($_POST['post_comment']))
{
echo htmlspecialchars($_POST['post']);
}
?>
//print the value using get
echo $_GET['post'];
//url must be like this
http://localhost/blog/home.php?post=asdasdsad&post_comment=
//post value has asdasdsad so it will print to your page
Try to encode backslash between domain and user
pip --proxy https://domain%5Cuser:password@proxy:port install -r requirements.txt
To solve the issue try to repair the .net framework 4
and then run the command
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
In addition to @senderle's here, some might also be wondering how to use the functionality of multiprocessing.Pool
.
The nice thing is that there is a .Pool()
method to the manager
instance that mimics all the familiar API of the top-level multiprocessing
.
from itertools import repeat
import multiprocessing as mp
import os
import pprint
def f(d: dict) -> None:
pid = os.getpid()
d[pid] = "Hi, I was written by process %d" % pid
if __name__ == '__main__':
with mp.Manager() as manager:
d = manager.dict()
with manager.Pool() as pool:
pool.map(f, repeat(d, 10))
# `d` is a DictProxy object that can be converted to dict
pprint.pprint(dict(d))
Output:
$ python3 mul.py
{22562: 'Hi, I was written by process 22562',
22563: 'Hi, I was written by process 22563',
22564: 'Hi, I was written by process 22564',
22565: 'Hi, I was written by process 22565',
22566: 'Hi, I was written by process 22566',
22567: 'Hi, I was written by process 22567',
22568: 'Hi, I was written by process 22568',
22569: 'Hi, I was written by process 22569',
22570: 'Hi, I was written by process 22570',
22571: 'Hi, I was written by process 22571'}
This is a slightly different example where each process just logs its process ID to the global DictProxy
object d
.
This will automatically open your window as well
ng serve -o --port 4801
In case someone missed the obvious; note that if you build a GUI application and use
"-subsystem:windows" in the link-args, the application entry is WinMain@16. Not main(). Hence you can use this snippet to call your main():
#include <stdlib.h>
#include <windows.h>
#ifdef __GNUC__
#define _stdcall __attribute__((stdcall))
#endif
int _stdcall
WinMain (struct HINSTANCE__ *hInstance,
struct HINSTANCE__ *hPrevInstance,
char *lpszCmdLine,
int nCmdShow)
{
return main (__argc, __argv);
}
There should be a line in your postgresql.conf
file that says:
port = 1486
Change that.
The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/
On Windows it is C:\Program Files\PostgreSQL\9.3\data
Don't forget to sudo service postgresql restart
for changes to take effect.
Since R version 2.12, there's a droplevels()
function.
levels(droplevels(subdf$letters))
I think the most simple way to skip some elements from an array is by using the filter() method.
By using this method (ES5) and the ES6 syntax you can write your code in one line, and this will return what you want:
let images = [{src: 'img.png'}, {src: 'j1.json'}, {src: 'img.png'}, {src: 'j2.json'}];_x000D_
_x000D_
let sources = images.filter(img => img.src.slice(-4) != 'json').map(img => img.src);_x000D_
_x000D_
console.log(sources);
_x000D_
content
doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.
Another problem with your code is "
inside a "
block. You should mix '
and "
(class='headingDetail'
).
If content
did support HTML you could end up in an infinite loop where content
is added inside content
.
T-SQL doesn't support arrays that I'm aware of.
What's your table structure? You could probably design a query that does this instead:
select
month,
sum(sales)
from sales_table
group by month
order by month
File->Settings->Appearance & Behavior-> Appearance and In theme select Darcula and apply dark background theme editor.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('h1').css('color','#3498db');
});
</script>
<style>
.wrapper{
height:450px;
background:#ededed;
text-align:center
}
</style>
</head>
<body>
<div class="wrapper">
<h1>Title</h1>
</div>
</body>
</html>
For Windows: Filemon from SysInternals will show you what files are being accessed.
Remember to set your filters so you are not overwhelmed by the chatty file system traffic.
Added: Filemon does not work with newer Windows versions, so you might have to use Process Monitor.
My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)
# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)
# tails of the arrows
tails= np.zeros(len(bvecs))
# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('b-vectors on unit sphere')
plt.show()
Error is that you are using 'ID' in lower case like 'checkbox1' but when you loop json object its return in upper case. So you need to replace checkbox1 to CHECKBOX1.
In my case :-
var response = jQuery.parseJSON(response);
$.each(response, function(key, value) {
$.each(value, function(key, value){
$('#'+key).val(value);
});
});
Before
<input type="text" name="abc" id="abc" value="">
I am getting the same error but when i replace the id in html code its work fine.
After
<input type="text" name="abc" id="ABC" value="">
You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.
Here is the directive:
app.directive("ngScopeElement", function () {
var directiveDefinitionObject = {
restrict: "A",
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
scope[iAttrs.ngScopeElement] = iElement;
}
};
}
};
return directiveDefinitionObject;
});
Usage:
app.directive("myDirective", function() {
return {
template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
link: function(scope, element, attrs) {
scope.list[0] // scope.list is the jqlite element,
// scope.list[0] is the native dom element
}
}
});
Some remarks:
scope.list
from myDirective
s postLink-Function, which you are very likely using anywayngScopeElement
uses a preLink-function, so that directives nested within the element having ng-scope-element
can already access scope.list
The existing answers which leverage SJCL, CryptoJS, and/or WebCrypto aren't necessarily wrong but they're not as safe as you might initially suspect. Generally you want to use libsodium. First I'll explain why, then how.
Short answer: In order for your encryption to actually be secure, these libraries expect you to make too many choices e.g. the block cipher mode (CBC, CTR, GCM; if you can't tell which of the three I just listed is secure to use and under what constraints, you shouldn't be burdened with this sort of choice at all).
Unless your job title is cryptography engineer, the odds are stacked against you implementing it securely.
CryptoJS offers a handful of building blocks and expects you to know how to use them securely. It even defaults to CBC mode (archived).
Read this write-up on AES-CBC vulnerabilities.
WebCrypto is a potluck standard, designed by committee, for purposes that are orthogonal to cryptography engineering. Specifically, WebCrypto was meant to replace Flash, not provide security.
SJCL's public API and documentation begs users to encrypt data with a human-remembered password. This is rarely, if ever, what you want to do in the real world.
Additionally: Its default PBKDF2 round count is roughly 86 times as small as you want it to be. AES-128-CCM is probably fine.
Out of the three options above, SJCL is the least likely to end in tears. But there are better options available.
You don't need to choose between a menu of cipher modes, hash functions, and other needless options. You'll never risk screwing up your parameters and removing all security from your protocol.
Instead, libsodium just gives you simple options tuned for maximum security and minimalistic APIs.
crypto_box()
/ crypto_box_open()
offer authenticated public-key encryption.
crypto_secretbox()
/ crypto_secretbox_open()
offer shared-key authenticated encryption.
Additionally, libsodium has bindings in dozens of popular programming languages, so it's very likely that libsodium will just work when trying to interoperate with another programming stack. Also, libsodium tends to be very fast without sacrificing security.
First, you need to decide one thing:
If you selected the first option, get CipherSweet.js.
The documentation is available online. EncryptedField
is sufficient for most use cases, but the EncryptedRow
and EncryptedMultiRows
APIs may be easier if you have a lot of distinct fields you want to encrypt.
With CipherSweet, you don't need to even know what a nonce/IV is to use it securely.
Additionally, this handles int
/float
encryption without leaking facts about the contents through ciphertext size.
Otherwise, you'll want sodium-plus, which is a user-friendly frontend to various libsodium wrappers. Sodium-Plus allows you to write performant, asynchronous, cross-platform code that's easy to audit and reason about.
To install sodium-plus, simply run...
npm install sodium-plus
There is currently no public CDN for browser support. This will change soon. However, you can grab sodium-plus.min.js
from the latest Github release if you need it.
const { SodiumPlus } = require('sodium-plus');_x000D_
let sodium;_x000D_
_x000D_
(async function () {_x000D_
if (!sodium) sodium = await SodiumPlus.auto();_x000D_
let plaintext = 'Your message goes here';_x000D_
let key = await sodium.crypto_secretbox_keygen();_x000D_
let nonce = await sodium.randombytes_buf(24);_x000D_
let ciphertext = await sodium.crypto_secretbox(_x000D_
plaintext,_x000D_
nonce,_x000D_
key _x000D_
);_x000D_
console.log(ciphertext.toString('hex'));_x000D_
_x000D_
let decrypted = await sodium.crypto_secretbox_open(_x000D_
ciphertext,_x000D_
nonce,_x000D_
key_x000D_
);_x000D_
_x000D_
console.log(decrypted.toString());_x000D_
})();
_x000D_
The documentation for sodium-plus is available on Github.
If you'd like a step-by-step tutorial, this dev.to article has what you're looking for.
You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.
This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;
public class Encrypt {
static byte [] arr = {1,2,3,4,5,6,7,8,9};
// static byte [] arr = new byte[16];
public static void main(String...args) {
try {
// System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
Base64.Decoder decoder = Base64.getDecoder();
// static byte [] arr = new byte[16];
Security.setProperty("crypto.policy", "unlimited");
String key = "Your key";
// System.out.println("-------" + key);
String value = "Hey, i am adnan";
String IV = "0123456789abcdef";
// System.out.println(value);
// log.info(value);
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
// IvParameterSpec iv = new IvParameterSpec(arr);
// System.out.println(key);
SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
// System.out.println(skeySpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// System.out.println("ddddddddd"+IV);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
// System.out.println(cipher.getIV());
byte[] encrypted = cipher.doFinal(value.getBytes());
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
// vars.put("input-1",encryptedString);
// log.info("beanshell");
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
Also, could be simple as:
if( typeof foo == "function" )
foo();
It's an old question, however might be useful for someone like me.
lodash
has _.inRange()
function https://lodash.com/docs/4.17.4#inRange
Example:
_.inRange(3, 2, 4);
// => true
Please note that this method utilizes the Lodash
utility library, and requires access to an installed version of Lodash.
Is there a way ( I mean how do I ) set a system property in a maven project? I want to access a property from my test [...]
You can set system properties in the Maven Surefire Plugin configuration (this makes sense since tests are forked by default). From Using System Properties:
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
<systemPropertyVariables>
<propertyName>propertyValue</propertyName>
<buildDirectory>${project.build.directory}</buildDirectory>
[...]
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
[...]
</project>
and my webapp ( running locally )
Not sure what you mean here but I'll assume the webapp container is started by Maven. You can pass system properties on the command line using:
mvn -DargLine="-DpropertyName=propertyValue"
Update: Ok, got it now. For Jetty, you should also be able to set system properties in the Maven Jetty Plugin configuration. From Setting System Properties:
<project>
...
<plugins>
...
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<configuration>
...
<systemProperties>
<systemProperty>
<name>propertyName</name>
<value>propertyValue</value>
</systemProperty>
...
</systemProperties>
</configuration>
</plugin>
</plugins>
</project>
Reviving an old question because it seems to appear at the top of search results.
I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.
<div class="parent-style-one"> @Html.ActionLink("Homepage", "Home", "Home") </div>
.parent-style-one { /* your styles here */ }
.parent-style-one a { text-decoration: none; }
.parent-style-one a:hover { text-decoration: underline; -webkit-transition-duration: 1.1s; /* Safari */ transition-duration: 1.1s; }
This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.
Just as an update this can be done by using Toad 9 also.Goto Database>Export>Data Pump Export wizard.At the desitination directory window if you dont find any directory in the dropdown,then you probably have to create a directory object.
CREATE OR REPLACE DIRECTORY data_pmp_dir_test AS '/u01/app/oracle/oradata/pmp_dir_test';
See this for an example.
I know you guys all have great solution; I just want to share mine - maybe that is not the best way, but it is perfect for myself!
With python
and pip
on, it is really quite simple! BOOM!
On Mac or Ubuntu (mine is mac)
$ pip install drawtree
$python
, enter python console; you can do it in other wayfrom drawtree import draw_level_order
draw_level_order('{2,1,3,0,7,9,1,2,#,1,0,#,#,8,8,#,#,#,#,7}')
DONE!
2
/ \
/ \
/ \
1 3
/ \ / \
0 7 9 1
/ / \ / \
2 1 0 8 8
/
7
Source tracking:
Before I saw this post, I went google "binary tree plain text"
And I found this https://www.reddit.com/r/learnpython/comments/3naiq8/draw_binary_tree_in_plain_text/, direct me to this https://github.com/msbanik/drawtree
All the answers above came with it's own issues. Easiest/cleanest way IMO is to create a helper
MVC5 Razor
App_Code/Helpers.cshtml
@helper CheckBoxFor(WebViewPage page, string propertyName, bool? value, string htmlAttributes = null)
{
if (value == null)
{
<div class="checkbox-nullable">
<input type="checkbox" @page.Html.Raw(htmlAttributes)>
</div>
}
else if (value == true)
{
<input type="checkbox" value="true" @page.Html.Raw(htmlAttributes) checked>
}
else
{
<input type="checkbox" value="false" @page.Html.Raw(htmlAttributes)>
}
}
Usage
@Helpers.CheckBoxFor(this, "IsPaymentRecordOk", Model.IsPaymentRecordOk)
In my scenario, a nullable checkbox means that a staff member had not yet asked the question to the client, so it's wrapped in a .checkbox-nullable
so that you may style appropriately and help the end-user identify that it is neither true
nor false
CSS
.checkbox-nullable {
border: 1px solid red;
padding: 3px;
display: inline-block;
}
Check out the sass-globbing project.
After checking all of these answers above without luck, the folling code worked for me to solve the problem:
$(".ui-dialog").dialog("close");
Maybe this will be also a good try if you seek for alternatives.
.img-responsive {
margin: 0 auto;
}
you can write like above code in your document so no need to add one another class in image tag.
Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16
iOS8 requires these images
Using PowerShell, you can use the following
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name
This will show a list off all services which displayname starts with "NATION-".
You can also directly stop or start the services;
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service
or simply
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service
_meta
is private, but it's relatively stable. There are efforts to formalise it, document it and remove the underscore, which might happen before 1.3 or 1.4. I imagine effort will be made to ensure things are backwards compatible, because lots of people have been using it anyway.
If you're particularly concerned about compatibility, write a function that takes a model and returns the fields. This means if something does change in the future, you only have to change one function.
def get_model_fields(model):
return model._meta.fields
I believe this will return a list of Field
objects. To get the value of each field from the instance, use getattr(instance, field.name)
.
Update: Django contributors are working on an API to replace the _Meta object as part of a Google Summer of Code. See:
- https://groups.google.com/forum/#!topic/django-developers/hD4roZq0wyk
- https://code.djangoproject.com/wiki/new_meta_api
For those wanting to do a JOIN that updates ONLY the rows your join returns use:
UPDATE a
SET price = b_alias.unit_price
FROM a AS a_alias
LEFT JOIN b AS b_alias ON a_alias.b_fk = b_alias.id
WHERE a_alias.unit_name LIKE 'some_value'
AND a.id = a_alias.id
--the below line is critical for updating ONLY joined rows
AND a.pk_id = a_alias.pk_id;
This was mentioned above but only through a comment..Since it's critical to getting the correct result posting NEW answer that Works
Another good way to serialize json into c# is below:
RootObject ro = new RootObject();
try
{
StreamReader sr = new StreamReader(FileLoc);
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<RootObject>(jsonString);
}
you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client
An alternative adaptation of Jebs Solution that avoids the use of call via the use of Macro arguments and variable substitution:
@Echo off
:# Macro Definitions
For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")
:# %\C% - Color macro; No error checking. Usage:
:# %\C:?=HEXVALUE%Output String
:# (%\C:?=HEXVALUE%Output String) & (%\C:?=HEXVALUE%Output String)
Set "\C=For %%o in (1 2)Do if %%o==2 (( <nul set /p ".=%DEL%" > "^^!os:\n=^^!" ) & ( findstr /v /a:? /R "^$" "^^!os:\n=^^!" nul ) & ( del "^^!os:\n=^^!" > nul 2>&1 ) & (Set "testos=^^!os:\n=^^!" & If not "^^!testos^^!" == "^^!os^^!" (Echo/)))Else Set os="
:# Ensure macro escaping is correct depending on delayedexpansion environment type
If Not "!![" == "[" (
Set "\C=%\C:^^=^%"
)
Setlocal EnableExtensions EnableDelayedExpansion
PUSHD "%~dp0"
:# SCRIPT MAIN BODY
:# To force a new line; terminate an output string with: \n
:# Usage info:
(%\C:?=40% This is an example of usage\n)&(%\C:?=50% Trailing whitespace and periods are removed.\n)
(%\C:?=0e% Leading spaces and periods are retained)&(%\C:?=e0%. NOT SUPPORTED - \n)
%\C:?=02% Colon ^& Unescaped Ampersands ^& doublequotes\n
%\C:?=02% LSS than ^& GTR than symbols ^& foreward and backward slashes\n
(%\C:?=02% Pipe ^& Question Mark and Asterisk characters.\n) & (%\C:?=e2%^^! Exclaimation ^^! marks must be escaped\n)
:end
POPD
Endlocal
Goto :Eof
Simple.... use tapku library.... you can google that word and use it... its open source... enjoy..... no need of bugging with those codes....
Step 1: Start button -> Computer menu item -> Properties on right click menu item -> Advanced System Settings button on left panel -> Advanced tab in System Properties dialog -> Environment Variables button -> System variables table
Step 2: Add MAVEN_HOME variable
Step 3: Update PATH variable
Step 4: Make sure you have JAVA_HOME variable correctly
step 5: open console and check below command
mvn -v
The Bootstrap3 .form-control
is cool but for those who love or need the drop-down with button and ul option, here is the updated code. I have edited the code by Steve to fix jumping to the hash link and closing the drop-down after selection.
Thanks to Steve, Ben and Skelly!
$(".dropdown-menu li a").click(function () {
var selText = $(this).text();
$(this).closest('div').find('button[data-toggle="dropdown"]').html(selText + ' <span class="caret"></span>');
$(this).closest('.dropdown').removeClass("open");
return false;
});
We can use title()
function with negative line
value to bring down the title.
See this example:
plot(1, 1)
title("Title", line = -2)
Try ceiling...
SELECT Ceiling(45.01), Ceiling(45.49), Ceiling(45.99)
You can use aggregate, too:
db.accommodations.aggregate(
[
{$project: {_id:1, name:1, zipcode:1,
size_of_name: {$size: "$name"}
}
},
{$match: {"size_of_name": {$gt: 1}}}
])
// you add "size_of_name" to transit document and use it to filter the size of the name
The accepted solution of modifying a Run Configuration wasn't ideal for me as I have a few different run configurations and could easily forget to do this when adding further ones in future. Also I wanted the setting to apply whenever running anything, e.g. when running JUnit tests by right-clicking and selecting "Run As" -> "JUnit Test".
The above can be achieved by modifying the JRE/JDK settings instead:-
-Xms512m -Xmx4G -XX:MaxPermSize=256M
The control searches for a view in the following order:
As you do not have xxx.cshtml
in those locations, it returns a "view not found" error.
Solution: You can use the complete path of your view:
Like
PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
Since VB6 is very similar to VBA, I think I might have a solution which does not require this much code to ReDim
a 2-dimensional array - using Transpose
, if you are working in Excel.
The solution (Excel VBA):
Dim n, m As Integer
n = 2
m = 1
Dim arrCity() As Variant
ReDim arrCity(1 To n, 1 To m)
m = m + 1
ReDim Preserve arrCity(1 To n, 1 To m)
arrCity = Application.Transpose(arrCity)
n = n + 1
ReDim Preserve arrCity(1 To m, 1 To n)
arrCity = Application.Transpose(arrCity)
What is different from OP's question: the lower bound of arrCity
array is not 0, but 1. This is in order to let Application.Transpose
do it's job.
Note that Transpose
is a method of the Excel Application
object (which in actuality is a shortcut to Application.WorksheetFunction.Transpose
). And in VBA, one must take care when using Transpose
as it has two significant limitations: If the array has more than 65536 elements, it will fail. If ANY element's length exceed 256 characters, it will fail. If neither of these is an issue, then Transpose will nicely convert the rank of an array form 1D to 2D or vice-versa.
Unfortunately there is nothing like 'Transpose' build into VB6.
The state you save at onSaveInstanceState()
is later available at onCreate()
method invocation. So use onCreate
(and its Bundle
parameter) to restore state of your activity.
Check your monitor scaling.
My problem turned out to be this:
It turned out to be different DPI-scaling on the primary and secondary monitor. When the secondary monitor was set to 125% (same as the primary monitor) the icons appeared again.
Answer actually provided by User3163 posting on SuperUser.com
This is what worked for me:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
try {
keyStore.load(instream, "password".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "password".toCharArray())
//.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java
You have to figure out if the string is ascii encoded or encoded with a multi-byte format.
In the former case, you can just use strlen
.
In the latter case you need to find the number of bytes per character.
the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274
In C use INT32_MAX
after #include <stdint.h>
.
In C++ use INT32_MAX
after #include <cstdint>
.
Or INT_MAX
for platform-specific size or UINT32_MAX
or UINT_MAX
for unsigned int
. See http://www.cplusplus.com/reference/cstdint/ and http://www.cplusplus.com/reference/climits/.
Or sizeof(int)
.
If you add the favicon into the root/images folder with the name favicon.ico browser will automatically understand and get it as favicon.I tested and worked. your link must be www.website.com/images/favicon.ico
For more information look this answer:
Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?
You can pivot your DataFrame after creating:
>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1 c1 c2
0
r1 avg11 avg12
r2 avg21 avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1 c1 c2
0
r1 stdev11 stdev12
r2 stdev21 stdev22
A bit decent web application consists of a mix of design patterns. I'll mention only the most important ones.
The core (architectural) design pattern you'd like to use is the Model-View-Controller pattern. The Controller is to be represented by a Servlet which (in)directly creates/uses a specific Model and View based on the request. The Model is to be represented by Javabean classes. This is often further dividable in Business Model which contains the actions (behaviour) and Data Model which contains the data (information). The View is to be represented by JSP files which have direct access to the (Data) Model by EL (Expression Language).
Then, there are variations based on how actions and events are handled. The popular ones are:
Request (action) based MVC: this is the simplest to implement. The (Business) Model works directly with HttpServletRequest
and HttpServletResponse
objects. You have to gather, convert and validate the request parameters (mostly) yourself. The View can be represented by plain vanilla HTML/CSS/JS and it does not maintain state across requests. This is how among others Spring MVC, Struts and Stripes works.
Component based MVC: this is harder to implement. But you end up with a simpler model and view wherein all the "raw" Servlet API is abstracted completely away. You shouldn't have the need to gather, convert and validate the request parameters yourself. The Controller does this task and sets the gathered, converted and validated request parameters in the Model. All you need to do is to define action methods which works directly with the model properties. The View is represented by "components" in flavor of JSP taglibs or XML elements which in turn generates HTML/CSS/JS. The state of the View for the subsequent requests is maintained in the session. This is particularly helpful for server-side conversion, validation and value change events. This is how among others JSF, Wicket and Play! works.
As a side note, hobbying around with a homegrown MVC framework is a very nice learning exercise, and I do recommend it as long as you keep it for personal/private purposes. But once you go professional, then it's strongly recommended to pick an existing framework rather than reinventing your own. Learning an existing and well-developed framework takes in long term less time than developing and maintaining a robust framework yourself.
In the below detailed explanation I'll restrict myself to request based MVC since that's easier to implement.
First, the Controller part should implement the Front Controller pattern (which is a specialized kind of Mediator pattern). It should consist of only a single servlet which provides a centralized entry point of all requests. It should create the Model based on information available by the request, such as the pathinfo or servletpath, the method and/or specific parameters. The Business Model is called Action
in the below HttpServlet
example.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Action action = ActionFactory.getAction(request);
String view = action.execute(request, response);
if (view.equals(request.getPathInfo().substring(1)) {
request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);
}
else {
response.sendRedirect(view); // We'd like to fire redirect in case of a view change as result of the action (PRG pattern).
}
}
catch (Exception e) {
throw new ServletException("Executing action failed.", e);
}
}
Executing the action should return some identifier to locate the view. Simplest would be to use it as filename of the JSP. Map this servlet on a specific url-pattern
in web.xml
, e.g. /pages/*
, *.do
or even just *.html
.
In case of prefix-patterns as for example /pages/*
you could then invoke URL's like http://example.com/pages/register, http://example.com/pages/login, etc and provide /WEB-INF/register.jsp
, /WEB-INF/login.jsp
with the appropriate GET and POST actions. The parts register
, login
, etc are then available by request.getPathInfo()
as in above example.
When you're using suffix-patterns like *.do
, *.html
, etc, then you could then invoke URL's like http://example.com/register.do, http://example.com/login.do, etc and you should change the code examples in this answer (also the ActionFactory
) to extract the register
and login
parts by request.getServletPath()
instead.
The Action
should follow the Strategy pattern. It needs to be defined as an abstract/interface type which should do the work based on the passed-in arguments of the abstract method (this is the difference with the Command pattern, wherein the abstract/interface type should do the work based on the arguments which are been passed-in during the creation of the implementation).
public interface Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
You may want to make the Exception
more specific with a custom exception like ActionException
. It's just a basic kickoff example, the rest is all up to you.
Here's an example of a LoginAction
which (as its name says) logs in the user. The User
itself is in turn a Data Model. The View is aware of the presence of the User
.
public class LoginAction implements Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
return "home"; // Redirect to home page.
}
else {
request.setAttribute("error", "Unknown username/password. Please retry."); // Store error message in request scope.
return "login"; // Go back to redisplay login form with error.
}
}
}
The ActionFactory
should follow the Factory method pattern. Basically, it should provide a creational method which returns a concrete implementation of an abstract/interface type. In this case, it should return an implementation of the Action
interface based on the information provided by the request. For example, the method and pathinfo (the pathinfo is the part after the context and servlet path in the request URL, excluding the query string).
public static Action getAction(HttpServletRequest request) {
return actions.get(request.getMethod() + request.getPathInfo());
}
The actions
in turn should be some static/applicationwide Map<String, Action>
which holds all known actions. It's up to you how to fill this map. Hardcoding:
actions.put("POST/register", new RegisterAction());
actions.put("POST/login", new LoginAction());
actions.put("GET/logout", new LogoutAction());
// ...
Or configurable based on a properties/XML configuration file in the classpath: (pseudo)
for (Entry entry : configuration) {
actions.put(entry.getKey(), Class.forName(entry.getValue()).newInstance());
}
Or dynamically based on a scan in the classpath for classes implementing a certain interface and/or annotation: (pseudo)
for (ClassFile classFile : classpath) {
if (classFile.isInstanceOf(Action.class)) {
actions.put(classFile.getAnnotation("mapping"), classFile.newInstance());
}
}
Keep in mind to create a "do nothing" Action
for the case there's no mapping. Let it for example return directly the request.getPathInfo().substring(1)
then.
Those were the important patterns so far.
To get a step further, you could use the Facade pattern to create a Context
class which in turn wraps the request and response objects and offers several convenience methods delegating to the request and response objects and pass that as argument into the Action#execute()
method instead. This adds an extra abstract layer to hide the raw Servlet API away. You should then basically end up with zero import javax.servlet.*
declarations in every Action
implementation. In JSF terms, this is what the FacesContext
and ExternalContext
classes are doing. You can find a concrete example in this answer.
Then there's the State pattern for the case that you'd like to add an extra abstraction layer to split the tasks of gathering the request parameters, converting them, validating them, updating the model values and execute the actions. In JSF terms, this is what the LifeCycle
is doing.
Then there's the Composite pattern for the case that you'd like to create a component based view which can be attached with the model and whose behaviour depends on the state of the request based lifecycle. In JSF terms, this is what the UIComponent
represent.
This way you can evolve bit by bit towards a component based framework.
The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.
According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:
git tag <tagname>
, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).git tag -a <tagname>
, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.git tag -a -m <msg> <tagname>
, Git will tag the commit and annotate it with the provided message.git tag -m <msg> <tagname>
, Git will behave as if you passed the -a flag for annotation and use the provided message.Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.
I suspect the problem is the slashes in the format string versus the ones in the data. That's a culture-sensitive date separator character in the format string, and the final argument being null
means "use the current culture". If you either escape the slashes ("M'/'d'/'yyyy") or you specify CultureInfo.InvariantCulture
, it will be okay.
If anyone's interested in reproducing this:
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy",
new CultureInfo("de-DE"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("en-US"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
CultureInfo.InvariantCulture);
// Fails
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("de-DE"));
This will convert Hello World to 48656c6c6f20576f726c64 and print it.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char hello[20]="Hello World";
for(unsigned int i=0; i<strlen(hello); i++)
cout << hex << (int) hello[i];
return 0;
}
It is worth noting that @Marius's second answer could be used as pure Javascript solution.
document.getElementById('elementId').tagName
Also, if all you are trying to do is break up the main.go file into multiple files, then just name the other files "package main" as long as you only define the main function in one of those files, you are good to go.
The headers you are trying to set are response headers. They have to be provided, in the response, by the server you are making the request to.
They have no place being set on the client. It would be pointless having a means to grant permissions if they could be granted by the site that wanted permission instead of the site that owned the data.
I think you are on the right track with COALESCE. See here for an example of building a comma-delimited string:
http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string
You can use any selector with not
p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}
First off, are you setting your desired JRE or your desired JDK?
Even if your Eclipse is set up properly, there might be a wacky project-specific setting somewhere. You can open up a context menu on a given Java project in the Project Explorer and select Properties > Java Compiler to check on that.
If none of that helps, leave a comment and I'll take another look.
Similar to Andrews which is #1:
Something that worked for me is:
name = "Blue Jeans"
Product.find_by("lower(name) = ?", name.downcase)
This eliminates the need to do a #where
and #first
in the same query. Hope this helps!
Probably the most significant things below are the font choices and the colour schemes. Yes, I have spent far too long enjoyably fiddling with those things. :)
"set tildeop
set nosmartindent
" set guifont=courier
" awesome programming font
" set guifont=peep:h09:cANSI
" another nice looking font for programming and general use
set guifont=Bitstream_Vera_Sans_MONO:h09:cANSI
set lines=68
set tabstop=2
set shiftwidth=2
set expandtab
set ignorecase
set nobackup
" set writebackup
" Some of my favourite colour schemes, lovingly crafted over the years :)
" very dark scarlet background, almost white text
" hi Normal guifg=#FFFFF0 guibg=#3F0000 ctermfg=white ctermbg=Black
" C64 colours
"hi Normal guifg=#8CA1EC guibg=#372DB4 ctermfg=white ctermbg=Black
" nice forest green background with bisque fg
hi Normal guifg=#9CfCb1 guibg=#279A1D ctermfg=white ctermbg=Black
" dark green background with almost white text
"hi Normal guifg=#FFFFF0 guibg=#003F00 ctermfg=white ctermbg=Black
" french blue background, almost white text
"hi Normal guifg=#FFFFF0 guibg=#00003F ctermfg=white ctermbg=Black
" slate blue bg, grey text
"hi Normal guifg=#929Cb1 guibg=#20403F ctermfg=white ctermbg=Black
" yellow/orange bg, black text
hi Normal guifg=#000000 guibg=#f8db3a ctermfg=white ctermbg=Black
HTML Component
<input type="text" [formControl]="txtValue">
TS Component
public txtValue = new FormControl('', { validators:[Validators.required] });
We can use this method to save using API. LearnersModules is the module file on our Angular files SaveSampleExams is the service file is one function method.
> this.service.SaveSampleExams(LearnersModules).subscribe(
> (data) => {
> this.dataSaved = true;
> LearnersModules.txtValue = this.txtValue.value;
> });
var x = condition || null;
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
Perhaps replace
is what you are looking for:
> x = c(3, 2, 1, 0, 4, 0)
> replace(x, x==0, 1)
[1] 3 2 1 1 4 1
Or, if you don't have x
(any specific reason why not?):
replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)
Many people are familiar with gsub
, so you can also try either of the following:
as.numeric(gsub(0, 1, x))
as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))
After reading the comments, perhaps with
is an option:
with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))
Try this way:
wc -l < file.txt
I encountered this problem when attempint to run my web application as a fat jar rather than from within my IDE (IntelliJ).
This is what worked for me. Simply adding a default profile to the application.properties file.
spring.profiles.active=default
You don't have to use default if you have already set up other specific profiles (dev/test/prod). But if you haven't this is necessary to run the application as a fat jar.
int is the C# language's shortcut for System.Int32
Whilst this does mean that Microsoft could change this mapping, a post on FogCreek's discussions stated [source]
"On the 64 bit issue -- Microsoft is indeed working on a 64-bit version of the .NET Framework but I'm pretty sure int will NOT map to 64 bit on that system.
Reasons:
1. The C# ECMA standard specifically says that int is 32 bit and long is 64 bit.
2. Microsoft introduced additional properties & methods in Framework version 1.1 that return long values instead of int values, such as Array.GetLongLength in addition to Array.GetLength.
So I think it's safe to say that all built-in C# types will keep their current mapping."
If you don't declare a function and it only appears after being called, it is automatically assumed to be int
, so in your case, you didn't declare
void my_print (char *);
void my_print2 (char *);
before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *);
and int my_print2 (char *);
and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types
.
As Brian suggested, declare those two methods before main.
In a KeyPress event, if the user pressed Enter, call
SendKeys.Send("{TAB}")
Nicest way to implement automatically selecting the text on receiving focus is to create a subclass of TextBox in your project with the following override:
Protected Overrides Sub OnGotFocus(ByVal e As System.EventArgs)
SelectionStart = 0
SelectionLength = Text.Length
MyBase.OnGotFocus(e)
End Sub
Then use this custom TextBox in place of the WinForms standard TextBox on all your Forms.
The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.
Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.
If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/
is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/
or http://s3-external-1.amazonaws.com/bucket/
.¹
The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].
S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com
. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.
If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.
However... the two endpoints do not offer the same functionality.
Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.
Choose the correct type of endpoint (REST or web site) for your application:
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff
¹ s3-external-1.amazonaws.com
has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com
. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2
had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1
so s3-external-2
appears to have no purpose except backwards-compatibility.
Why and when would we create a static constructor ...?
One specific reason to use a static constructor is to create a 'super enum' class. Here's a (simple, contrived) example:
public class Animals
{
private readonly string _description;
private readonly string _speciesBinomialName;
public string Description { get { return _description; } }
public string SpeciesBinomialName { get { return _speciesBinomialName; } }
private Animals(string description, string speciesBinomialName)
{
_description = description;
_speciesBinomialName = speciesBinomialName;
}
private static readonly Animals _dog;
private static readonly Animals _cat;
private static readonly Animals _boaConstrictor;
public static Animals Dog { get { return _dog; } }
public static Animals Cat { get { return _cat; } }
public static Animals BoaConstrictor { get { return _boaConstrictor; } }
static Animals()
{
_dog = new Animals("Man's best friend", "Canis familiaris");
_cat = new Animals("Small, typically furry, killer", "Felis catus");
_boaConstrictor = new Animals("Large, heavy-bodied snake", "Boa constrictor");
}
}
You'd use it very similarly (in syntactical appearance) to any other enum:
Animals.Dog
The advantage of this over a regular enum
is that you can encapsulate related info easily. One disadvantage is that you can't use these values in a switch
statement (because it requires constant values).
I feel it is worth adding that a static variable is not the same as a constant variable.
using a constant variable in a class
struct Foo{
const int a;
Foo(int b) : a(b){}
}
and we would declare it like like so
fooA = new Foo(5);
fooB = new Foo(10);
// fooA.a = 5;
// fooB.a = 10;
For a static variable
struct Bar{
static int a;
Foo(int b){
a = b;
}
}
Bar::a = 0; // set value for a
which is used like so
barA = new Bar(5);
barB = new Bar(10);
// barA.a = 10;
// barB.a = 10;
// Bar::a = 10;
You see what happens here. The constant variable, which is instanced along with each instance of Foo, as Foo is instanced has a separate value for each instance of Foo, and it can't be changed by Foo at all.
Where as with Bar, their is only one value for Bar::a no matter how many instances of Bar are made. They all share this value, you can also access it with their being any instances of Bar. The static variable also abides rules for public/private, so you could make it that only instances of Bar can read the value of Bar::a;
You can use:
npm show {pkg} version
(so npm show express version
will return now 3.0.0rc3
).
The standard way to do division is by implementing binary long-division. This involves subtraction, so as long as you don't discount this as not a bit-wise operation, then this is what you should do. (Note that you can of course implement subtraction, very tediously, using bitwise logical operations.)
In essence, if you're doing Q = N/D
:
N
and D
.t = (N - D);
.(t >= 0)
, then set the least significant bit of Q
to 1, and set N = t
.N
by 1.Q
by 1.Loop for as many output bits (including fractional) as you require, then apply a final shift to undo what you did in Step 1.
You can apply the when
method to your array:
var arr = [ /* Deferred objects */ ];
$.when.apply($, arr);
Use "attr" method in jquery.
$('.test').click(function(){
var id = $(this).attr('id');
});
I've solved this problem by using following steps
su hdfs
hadoop fs -put /usr/local/input-data/ /input
exit
You can do it in a simpler way using the DialogResult.cancel
method.
Eg:
Dim anInput as String = InputBox("Enter your pin")
If anInput <>"" then
' Do something
Elseif DialogResult.Cancel then
Msgbox("You've canceled")
End if
If the above answer does not work, change the encoding to cp1252 or manually remove all occurrences of the special character. For me ? special character was causing the prob which was inside a comment block.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<encoding>Cp1252</encoding>
</configuration>
</plugin>
PS:I was using GNU/Linux OS(Ubuntu).
Here's a general solution that will handle an arbitrary amount of dictionaries, with cases when keys are in only some of the dictionaries:
from collections import defaultdict
d1 = {1: 2, 3: 4}
d2 = {1: 6, 3: 7}
dd = defaultdict(list)
for d in (d1, d2): # you can list as many input dicts as you want here
for key, value in d.items():
dd[key].append(value)
print(dd)
Shows:
defaultdict(<type 'list'>, {1: [2, 6], 3: [4, 7]})
Also, to get your .attrib
, just change append(value)
to append(value.attrib)
As RocketDonkey suggested, your module itself needs to have some docstrings.
For example, in myModule/__init__.py
:
"""
The mod module
"""
You'd also want to generate documentation for each file in myModule/*.py
using
pydoc myModule.thefilename
to make sure the generated files match the ones that are referenced from the main module documentation file.
One possible solution in pure javascript:
for (var x = 0; x < str.length; x++)
{
var c = str.charAt(x);
alert(c);
}
It would be best to have a TIMESTAMP
column that defaults to CURRENT_TIMESTAMP
.. it is the only true predictive behavior you can find here.
The second-best thing you can do is ORDER BY ID DESC LIMIT 1
and hope the newest ID is the largest value.
Just add the autocomplete="new-password"
attribute to your password input field.
To learn more about autocomplete
: https://html.spec.whatwg.org/multipage/forms.html#attr-fe-autocomplete-new-password
SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.
There are a few third-party extensions that provide that capability - check out e.g.:
Click somewhere on the chart to select it.
You should now see 3 new tabs appear at the top of the screen called "Design", "Layout" and "Format".
Click on the "Design" tab.
There will be a button called "Switch Row/Column" within the "data" group, click it.
if(!file3.exists()){
file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null) fop.write(nodeValue.getBytes());
fop.write("\n".getBytes());
fop.flush();
fop.close();
You need to add a newline at the end of each write.
While it's possible to abort a thread, in practice it's almost always a very bad idea to do so. Aborthing a thread means the thread is not given a chance to clean up after itself, leaving resources undeleted, and things in unknown states.
In practice, if you abort a thread, you should only do so in conjunction with killing the process. Sadly, all too many people think ThreadAbort is a viable way of stopping something and continuing on, it's not.
Since Tasks run as threads, you can call ThreadAbort on them, but as with generic threads you almost never want to do this, except as a last resort.
You can upload files by dragging and dropping or by pointing and clicking. To upload folders, you must drag and drop them. Drag and drop functionality is supported only for the Chrome and Firefox browsers
Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.
There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found dependency injection (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.
Technically speaking, you can only extend one class at a time and implement multiple interfaces, but when laying hands on software engineering, I would rather suggest a problem specific solution not generally answerable. By the way, it is good OO practice, not to extend concrete classes/only extend abstract classes to prevent unwanted inheritance behavior - there is no such thing as an "animal" and no use of an animal object but only concrete animals.
From the docs
Bitcode will allow apple to optimise the app without you having to submit another build. But, you can only enable this feature if all frameworks and apps in the app bundle have this feature enabled. Having it helps, but not having it should not have any negative impact.
For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required.
The App Store and operating system optimize the installation of iOS and watchOS apps by tailoring app delivery to the capabilities of the user’s particular device, with minimal footprint. This optimization, called app thinning, lets you create apps that use the most device features, occupy minimum disk space, and accommodate future updates that can be applied by Apple. Faster downloads and more space for other apps and content provides a better user experience.
There should not be any performance impacts.
I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately (a requirement of yours) triggers the following change code.
$('#selectField').change(function(){
if($('#selectField').val() == 'N'){
$('#secondaryInput').hide();
} else {
$('#secondaryInput').show();
}
});
Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".
$('#selectField').val(valueFromDatabase).change();
So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.
For dynamically scaling using XML there is an attribute called "android:layout_weight"
The below example, modified from synic's response on this thread, shows a button that takes up 75% of the screen (weight = .25) and a text view taking up the remaining 25% of the screen (weight = .75).
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="somebutton">
<TextView android:layout_width="fill_parent"
android:layout_height="Wrap_content"
android:layout_weight=".75">
</LinearLayout>
In my experience, /var/www/ directory directive prevents subfolder virtualhost directives. So if you had tried all suggestions and still not working and you are using virtualhosts try this ;
1 - Be sure that you have
AllowOverride All
directive in
/etc/apache2/sites-available/example.com.conf
2 - Check /var/www/ Directory directives in /etc/apache2/apache2.conf
(possibly at line 164), which looks like ;
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
If there is an AllowOverride None
directive change it to
AllowOverride All
or just escape line
In particular if you need recursive clone
GIT_SSL_NO_VERIFY=true git clone --recursive https://github.com/xx/xx.git
In my case, i do:
sudo nano /etc/mysql/my.cnf
bind
names and IPsUse my custome class to check or request permisson
public class Permissons {
//Request Permisson
public static void Request_STORAGE(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},code);
}
public static void Request_CAMERA(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.CAMERA},code);
}
public static void Request_FINE_LOCATION(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.ACCESS_FINE_LOCATION},code);
}
public static void Request_READ_SMS(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.READ_SMS},code);
}
public static void Request_READ_CONTACTS(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.READ_CONTACTS},code);
}
public static void Request_READ_CALENDAR(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.READ_CALENDAR},code);
}
public static void Request_RECORD_AUDIO(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.RECORD_AUDIO},code);
}
//Check Permisson
public static boolean Check_STORAGE(Activity act)
{
int result = ContextCompat.checkSelfPermission(act,android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_CAMERA(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.CAMERA);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_FINE_LOCATION(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_READ_SMS(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_SMS);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_READ_CONTACTS(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_CONTACTS);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_READ_CALENDAR(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_CALENDAR);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_RECORD_AUDIO(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED;
}
}
Example
if(!Permissons.Check_STORAGE(MainActivity.this))
{
//if not permisson granted so request permisson with request code
Permissons.Request_STORAGE(MainActivity.this,22);
}
If you want to use the NSLinkAttributeName in a UITextView, then you may consider using the AttributedTextView library. It's a UITextView subclass that makes it very easy to handle these. For more info see: https://github.com/evermeer/AttributedTextView
You can make any part of the text interact like this (where textView1 is a UITextView IBoutlet):
textView1.attributer =
"1. ".red
.append("This is the first test. ").green
.append("Click on ").black
.append("evict.nl").makeInteract { _ in
UIApplication.shared.open(URL(string: "http://evict.nl")!, options: [:], completionHandler: { completed in })
}.underline
.append(" for testing links. ").black
.append("Next test").underline.makeInteract { _ in
print("NEXT")
}
.all.font(UIFont(name: "SourceSansPro-Regular", size: 16))
.setLinkColor(UIColor.purple)
And for handling hashtags and mentions you can use code like this:
textView1.attributer = "@test: What #hashtags do we have in @evermeer #AtributedTextView library"
.matchHashtags.underline
.matchMentions
.makeInteract { link in
UIApplication.shared.open(URL(string: "https://twitter.com\(link.replacingOccurrences(of: "@", with: ""))")!, options: [:], completionHandler: { completed in })
}
Double importing jquery can cause Error
<script src="static/public/js/jquery/jquery.min.js"></script>
OR
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="" crossorigin="anonymous"></script>
Works for positive or negative numbers
int start = -3;
int end = 6;
for (int val = start; val < end; val++)
{
// Condition to Check Even, Not condition (!) will give Odd number
if (val % 2 == 0)
{
System.out.println("Even" + val);
}
else
{
System.out.println("Odd" + val);
}
}
All these answers are correct, but I had to also check if the string contains other characters and Hebrew letters so I simply used:
if (!str.match(/^[\d]+$/)) {
//contains other characters as well
}
Other answers did not work well for me. My container could not resolve host ip using host.docker.internal. There are two ways
Sharing host network --net=host:
docker run -it --net=host myimage
Using docker's ip address, which is usually 172.17.0.1. You can check it by calling ifconfig command and grabbing inet addr of docker interface
user@ubuntu:~$ ifconfig
docker0 Link encap:Ethernet HWaddr 02:42:a4:a2:b2:f1
inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
inet6 addr: fe80::42:a4ff:fea2:b2f1/64 Scope:Link
Once you have this ip address, you can pass it as an argument to docker run and then to application or as I do it, map the location of jdbc.properties via volume to the directory on host machine, so you can manage the file externally.
docker run -it -v /host_dir/docker_jdbc_config:${jetty_base}/var/config myimage
NOTE: Your database might not allow external connections. In case of postgresql, you need to edit 2 files, as described here and here:
Edit postgresql.conf to listen on all addresses. By default it will point to localhost.
listen_addresses = '*'
Edit pg_hba.conf to allow connections from all addresses. Add on the last line:
host all all 0.0.0.0/0 md5
IMPORTANT: Last step updating database access is not recommended for production use unless you are really sure what you are doing.
There are a couple of points to this answer.
Firstly, you don't need to install Xcode. The Git installer works perfectly well. However, if you want to use Git from within Xcode - it expects to find an installation under /usr/local/bin. If you have your own Git installed elsewhere - I've got a script that fixes this.
Second is to do with the path. My Git path used to be kept under /etc/paths.d/
However, a Mac OS X v10.7 (Lion) install overwrites the contents of this folder and the /etc/paths
file as well. That's what happened to me and I got the same error. Recreating the path file fixed the problem.
This is just a modification of lunicon's answer (https://stackoverflow.com/a/24387115/3519572) if you want to replace one namespace for another during parsing. And if you want to see what exactly is going on, just uncomment the output lines and set a breakpoint.
public class XMLReaderWithNamespaceCorrection extends StreamReaderDelegate {
private final String wrongNamespace;
private final String correctNamespace;
public XMLReaderWithNamespaceCorrection(XMLStreamReader reader, String wrongNamespace, String correctNamespace) {
super(reader);
this.wrongNamespace = wrongNamespace;
this.correctNamespace = correctNamespace;
}
@Override
public String getAttributeNamespace(int arg0) {
// System.out.println("--------------------------\n");
// System.out.println("arg0: " + arg0);
// System.out.println("getAttributeName: " + getAttributeName(arg0));
// System.out.println("super.getAttributeNamespace: " + super.getAttributeNamespace(arg0));
// System.out.println("getAttributeLocalName: " + getAttributeLocalName(arg0));
// System.out.println("getAttributeType: " + getAttributeType(arg0));
// System.out.println("getAttributeValue: " + getAttributeValue(arg0));
// System.out.println("getAttributeValue(correctNamespace, LN):"
// + getAttributeValue(correctNamespace, getAttributeLocalName(arg0)));
// System.out.println("getAttributeValue(wrongNamespace, LN):"
// + getAttributeValue(wrongNamespace, getAttributeLocalName(arg0)));
String origNamespace = super.getAttributeNamespace(arg0);
boolean replace = (((wrongNamespace == null) && (origNamespace == null))
|| ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
return replace ? correctNamespace : origNamespace;
}
@Override
public String getNamespaceURI() {
// System.out.println("getNamespaceCount(): " + getNamespaceCount());
// for (int i = 0; i < getNamespaceCount(); i++) {
// System.out.println(i + ": " + getNamespacePrefix(i));
// }
//
// System.out.println("super.getNamespaceURI: " + super.getNamespaceURI());
String origNamespace = super.getNamespaceURI();
boolean replace = (((wrongNamespace == null) && (origNamespace == null))
|| ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
return replace ? correctNamespace : origNamespace;
}
}
usage:
InputStream is = new FileInputStream(xmlFile);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithNamespaceCorrection xr =
new XMLReaderWithNamespaceCorrection(xsr, "http://wrong.namespace.uri", "http://correct.namespace.uri");
rootJaxbElem = (JAXBElement<SqgRootType>) um.unmarshal(xr);
handleSchemaError(rootJaxbElem, pmRes);
Does this work for you?
http://jojovedder.blogspot.com/2009/04/running-maven-offline-using-local.html
Don't forget to add it to your plugin repository and point the url to wherever your repository is.
<repositories>
<repository>
<id>local</id>
<url>file://D:\mavenrepo</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>local</id>
<url>file://D:\mavenrepo</url>
</pluginRepository>
</pluginRepositories>
If not, you may need to run a local server, e.g. apache, on your machines.
Error is straight forward and its because of wrong placeholders you have used in function call. Inside init
you are not passing any parameters to your function. It should be this way
destination = Node("some key", neighbors: [edge1 , edge2], visited: true, lat: 23.45, long: 45.67) // fill up with your dummy values
Or you can just initialise with default method
destination = Node()
UPDATE
Add empty initialiser in your Node class
init() {
}
Console.WriteLine won't work. Only Debug.WriteLine() or Trace.WriteLine() will work, in debug mode.
I do the following: include using System.Diagnostics in the test module. Then, use Debug.WriteLine for my output, right click on the test, choose Debug Selected Tests. The result output will now appear in the Output window below. I use Visual Studio 2017 vs 15.8.1, with the default unit test framework VS provides.
Write below code into your MainActivity file after setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And below import statement into your java file.
import android.os.StrictMode;
In addition to the suggested answers, you can do this with some lazy generation and list comprehension magic:
import os, glob, itertools
results = itertools.chain.from_iterable(glob.iglob(os.path.join(root,'*.c'))
for root, dirs, files in os.walk('src'))
for f in results: print(f)
Besides fitting in one line and avoiding unnecessary lists in memory, this also has the nice side effect, that you can use it in a way similar to the ** operator, e.g., you could use os.path.join(root, 'some/path/*.c')
in order to get all .c files in all sub directories of src that have this structure.
I had an issue where hundreds of line endings were modified by some program and git diff
listed all source files as changed. After fixing the line endings, git status
still listed the files as modified.
I was able to fix this problem by adding all files to the index and then resetting the index.
git add -A
git reset
core.filemode
was set to false.
You can get the managed bean by passing the name:
public static Object getBean(String beanName){
Object bean = null;
FacesContext fc = FacesContext.getCurrentInstance();
if(fc!=null){
ELContext elContext = fc.getELContext();
bean = elContext.getELResolver().getValue(elContext, null, beanName);
}
return bean;
}
rsync
is actually quite tricky. have to do multiple tests to make it work.
Let's say you want to copy /var/www/html
to /var/www/dev
but need to exclude /var/www/html/site/video/
directory maybe due to its size. The command would be:
rsync -av --exclude 'sites/video' /var/www/html/ /var/www/dev
Some caveat:
/
in the source is needed, otherwise it will also copy the source directory rather than its content and becomes /var/www/dev/html/xxxx
, which maybe is not what you want. The the --exclude
path is relative to the source directly. Even if you put full absolute path, it will not work.
-v
is for verbose, -a
is for archive mode which means you want recursion and want to preserve almost everything.
you can do that on RowAdded Event :
_data_grid_view.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this._data_grid_view_RowsAdded);
private void _data_grid_view_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
_data_grid_view.Rows[e.RowIndex].Height = 42;
}
when a row add to the dataGridView it just change it height to 42.
If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]'
, '[^a-zA-Z0-9][^a-zA-Z0-9]'
, ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.
Consider using django-bulk-update
found here on GitHub.
Install: pip install django-bulk-update
Implement: (code taken directly from projects ReadMe file)
from bulk_update.helper import bulk_update
random_names = ['Walter', 'The Dude', 'Donny', 'Jesus']
people = Person.objects.all()
for person in people:
r = random.randrange(4)
person.name = random_names[r]
bulk_update(people) # updates all columns using the default db
Update: As Marc points out in the comments this is not suitable for updating thousands of rows at once. Though it is suitable for smaller batches 10's to 100's. The size of the batch that is right for you depends on your CPU and query complexity. This tool is more like a wheel barrow than a dump truck.
You can use jackson api for the conversion
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
add above maven dependency in your POM, In your main method create ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
later we nee to add our POJO class to the mapper
String json = mapper.writeValueAsString(pojo);
Hide the body initially, and then show it with jQuery after it has loaded.
body {
display: none;
}
$(function () {
$('body').show();
}); // end ready
Also, it would be best to have $('body').show();
as the last line in your last and main .js file.
Can't you style the forms themselves? Then, style the divs accordingly.
form
{
/* styles */
}
You can always overrule inherited styles by making it important:
form
{
/* styles */ !important
}
It's a general comparison operator. It returns either a -1, 0, or +1 depending on whether its receiver is less than, equal to, or greater than its argument.
To remove all spaces in every column, you can use
data[] <- lapply(data, gsub, pattern = " ", replacement = "", fixed = TRUE)
or to constrict this to just the second and third columns (i.e. every column except the first),
data[-1] <- lapply(data[-1], gsub, pattern = " ", replacement = "", fixed = TRUE)
Easiest way to check if they are authenticated is Request.User.IsAuthenticated
I think (from memory)
Make sure you have imported HttpClientModule
instead of adding HttpClient
direcly to the list of providers.
See https://angular.io/guide/http#setup for more info.
The HttpClientModule
actually provides HttpClient
for you. See https://angular.io/api/common/http/HttpClientModule:
Code sample:
import { HttpClientModule, /* other http imports */ } from "@angular/common/http";
@NgModule({
// ...other declarations, providers, entryComponents, etc.
imports: [
HttpClientModule,
// ...some other imports
],
})
export class AppModule { }
full solution here:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
</RadioGroup>
selector XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected" android:state_checked="false"/>
</selector>
json
seems faster than simplejson
in both cases of loads and dumps in latest version
Tested versions:
Results:
>>> def test(obj, call, data, times):
... s = datetime.now()
... print("calling: ", call, " in ", obj, " ", times, " times")
... for _ in range(times):
... r = getattr(obj, call)(data)
... e = datetime.now()
... print("total time: ", str(e-s))
... return r
>>> test(json, "dumps", data, 10000)
calling: dumps in <module 'json' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\json\\__init__.py'> 10000 times
total time: 0:00:00.054857
>>> test(simplejson, "dumps", data, 10000)
calling: dumps in <module 'simplejson' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\simplejson\\__init__.py'> 10000 times
total time: 0:00:00.419895
'{"1": 100, "2": "acs", "3.5": 3.5567, "d": [1, "23"], "e": {"a": "A"}}'
>>> test(json, "loads", strdata, 1000)
calling: loads in <module 'json' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\json\\__init__.py'> 1000 times
total time: 0:00:00.004985
{'1': 100, '2': 'acs', '3.5': 3.5567, 'd': [1, '23'], 'e': {'a': 'A'}}
>>> test(simplejson, "loads", strdata, 1000)
calling: loads in <module 'simplejson' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\simplejson\\__init__.py'> 1000 times
total time: 0:00:00.040890
{'1': 100, '2': 'acs', '3.5': 3.5567, 'd': [1, '23'], 'e': {'a': 'A'}}
For versions:
json was faster than simplejson during dumps operation but both maintained the same speed during loads operations
Use htmlparser2, its way faster and pretty straightforward. Consult this usage example:
https://www.npmjs.org/package/htmlparser2#usage
And the live demo here:
If you can't get to your php.ini file for some reason, disable errors to stdout (display_errors
) in a .htaccess file in any directory by adding the following line:
php_flag display_errors off
additionally, you can add error logging to a file:
php_flag log_errors on
This will get you a string array of all the resources:
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
I recently (Jul 2014) had a similar issue and found on OS X (10.9.4) that there was a "DigiCert High Assurance EV Root CA" certificate had expired (although I had another unexpired one as well).
I found two certificates named "DigiCert High Assurance EV Root CA", one expiring Nov 2031 and the expired one at July 2014 (a few of days previously). Deleting the expired certificate resolved the issue for me.
Hope this helps.
As stated by Harry Joy, you can do it on the onclick
attr like so:
<input type="button" onclick="func1();func2();" value="Call2Functions" />
Or, in your JS like so:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1();
func2();
};
Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):
var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
func1 = Call2FunctionsEle.onclick;
Call2FunctionsEle.onclick = function()
{
if( typeof func1 === 'function' )
{
func1();
}
func2();
};
If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1.apply( this, arguments );
func2.apply( this, arguments );
};
To add multiple lines you can use lineinfile
module with with_items
also including variable vars
here to make it simple :)
---
- hosts: localhost #change Host group as par inventory
gather_facts: no
become: yes
vars:
test_server: "10.168.1.1"
test_server_name: "test-server"
file_dest: "/etc/test/test_agentd.conf"
- name: configuring test.conf
lineinfile:
dest: "{{ item.dest }}"
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
with_items:
- { dest: '"{{ file_dest }}"', regexp: 'Server=', line: 'Server="{{test_server}}"' }
- { dest: '"{{ file_dest }}"', regexp: 'ServerActive=', line: 'ServerActive="{{test_server}}"' }
- { dest: '"{{ file_dest }}"', regexp: 'Hostname=', line: 'Hostname="{{test_server_name}}"' }
For a slightly different take on the question. A scripting language is a programming language but a programming language is not necessarily a scripting language. A scripting language is used to control or script a system. That system could be an operating system where the scripting language would be bash. The system could be a web server with PHP the scripting language. Scripting languages are designed to fill a specific niche; they are domain specific languages. Interactive systems have interpreted scripting languages giving rise to the notion that scripting languages are interpreted; however, this is a consequence of the system and not the scripting language itself.
Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":
class AddColumnToWidgets < ActiveRecord::Migration
def change
add_column :widgets, :colour, :string, default: 'red'
end
end
This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.
Please try this
<input type="button" value="Home" class="homebutton" id="btnHome" onClick="Javascript:window.location.href = 'http://www.website.com/index.php';" />
window.location.href example:
window.location.href = 'http://www.google.com'; //Will take you to Google.
window.open() example:
window.open('http://www.google.com'); //This will open Google in a new window.
It's a jQuery plugin designed to work as an end-to-end solution for parsing CSV into JavaScript data. It handles every single edge case presented in RFC 4180, as well as some that pop up for Excel/Google spreadsheet exports (i.e., mostly involving null values) that the specification is missing.
Example:
track,artist,album,year
Dangerous,'Busta Rhymes','When Disaster Strikes',1997
// Calling this
music = $.csv.toArrays(csv)
// Outputs...
[
["track", "artist", "album", "year"],
["Dangerous", "Busta Rhymes", "When Disaster Strikes", "1997"]
]
console.log(music[1][2]) // Outputs: 'When Disaster Strikes'
Update:
Oh yeah, I should also probably mention that it's completely configurable.
music = $.csv.toArrays(csv, {
delimiter: "'", // Sets a custom value delimiter character
separator: ';', // Sets a custom field separator character
});
Update 2:
It now works with jQuery on Node.js too. So you have the option of doing either client-side or server-side parsing with the same library.
Update 3:
Since the Google Code shutdown, jquery-csv has been migrated to GitHub.
Disclaimer: I am also the author of jQuery-CSV.
Set validateTLSCertificates
property to false
for your JSoup command.
Jsoup.connect("https://google.com/").validateTLSCertificates(false).get();
You're nearly there, just take out the EXECUTE:
DECLARE
procId NUMBER;
BEGIN
PKG1.INIT(1143824, 0, procId);
DBMS_OUTPUT.PUT_LINE(procId);
END;
I think the best solution is resize the images via script or locally and upload them again. Remember, you're forcing your viewers to download larger files than they need
You could also use the RenderView Controller extension
from here
(source)
and use it like this:
public ActionResult Do() {
var html = this.RenderView("index", theModel);
...
}
it works for razor and web-forms viewengines
You don't need to wrap it in a list with [..]
, just provide the subselection of the columns index:
df.drop(df.columns[[1, 69]], axis=1, inplace=True)
as the index object is already regarded as list-like.
Maybe you could do it like this:
Don't use the model in first controller. Store data in some other shared object which could be then retrieved by second controller.
Look at this and this post. It's about the similar issue.
P.S.
You could probabbly use session scoped bean for that shared data...
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
I needed to do the same thing for a chart where you could select the period of the data that should be displayed.
Therefore I introduced the CSS class 'btn-group-radio' and used the following unobtrusive javascript one-liner:
// application.js
$(document).ready(function() {
$('.btn-group-radio .btn').click(function() {
$(this).addClass('active').siblings('.btn').removeClass('active');
});
});
And here is the HTML:
<!-- some arbitrary view -->
<div class="btn-group btn-group-radio">
<%= link_to '1W', charts_path('1W'), class: 'btn btn-default active', remote: true %>
<%= link_to '1M', charts_path('1M'), class: 'btn btn-default', remote: true %>
<%= link_to '3M', charts_path('3M'), class: 'btn btn-default', remote: true %>
<%= link_to '6M', charts_path('6M'), class: 'btn btn-default', remote: true %>
<%= link_to '1Y', charts_path('1Y'), class: 'btn btn-default', remote: true %>
<%= link_to 'All', charts_path('all'), class: 'btn btn-default', remote: true %>
</div>
You can't provide if-else condition in the return block, make use of ternary block, also this.state will be an object, you shouldn't be comparing it with a value, see which state value you want to check, also return returns only one element, make sure to wrap them in a View
render() {
return (
<View style={styles.container}>
{this.state.page === 'news'? <Text>data</Text>: null}
</View>
)
}
A regular expression can be used to offer more control over the whitespace characters that are combined.
To match unicode whitespace:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"\s+")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()
To match ASCII whitespace only:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)
Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.
About \s
:
For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.
About re.ASCII
:
Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).
strip()
will remote any leading and trailing whitespaces.
If a class defines virtual methods outside that class, then g++ generates the vtable only in the object file that contains the outside-of-class definition of the virtual method that was declared first:
//test.h
struct str
{
virtual void f();
virtual void g();
};
//test1.cpp
#include "test.h"
void str::f(){}
//test2.cpp
#include "test.h"
void str::g(){}
The vtable will be in test1.o, but not in test2.o
This is an optimisation g++ implements to avoid having to compile in-class-defined virtual methods that would get pulled in by the vtable.
The link error you describe suggests that the definition of a virtual method (str::f in the example above) is missing in your project.
If Not editTransactionRow.pay_id AndAlso String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then
stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If