Any Class that implements System.Web.IHttpHandler
Interface becomes HttpHandler
. And this class run as processes in response to a request made to the ASP.NET Site.
The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler(The Class that implements System.Web.IHttpHandler
Interface).
You can create your own custom HTTP handlers that render custom output to the browser.
Some ASP.NET default handlers are:
I had the same problem and was solved by running the following in run
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
There is another way of doing it by adding your image files to public folder instead of assets and access those as static images.
<img :src="'/img/' + pic + '.png'" v-bind:alt="pic" >
This is where you need to put your static images:
Actually, this is the proper way to get what you want, unless you can use MS SQL 2014 (which finally enables custom format strings for date times).
To get yyyymm
instead of yyyym
, you can use this little trick:
select
right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
+ right('00' + cast(datepart(month, getdate()) as varchar(2)), 2)
It's faster and more reliable than gettings parts of convert(..., 112)
.
$data = file_get_contents('php://input');
echo $data;
This worked for me.
I would propose a different approach. Instead of changing the properties of all objects manually, let's add a new CSS to the document:
/* License: CC0 */
var newStylesheet = document.createElement('style');
newStylesheet.textContent = '.classname { display: none; }';
document.head.appendChild(newStylesheet);
BigDecimal is the best data type to use for currency.
There are a whole lot of containers for currency, but they all use BigDecimal as the underlying data type. You won't go wrong with BigDecimal, probably using BigDecimal.ROUND_HALF_EVEN rounding.
Nice...
Try this to remove an specific cron job (tested).
<?php $output = shell_exec('crontab -l'); ?>
<?php $cron_file = "/tmp/crontab.txt"; ?>
<!-- Execute script when form is submitted -->
<?php if(isset($_POST['add_cron'])) { ?>
<!-- Add new cron job -->
<?php if(!empty($_POST['add_cron'])) { ?>
<?php file_put_contents($cron_file, $output.$_POST['add_cron'].PHP_EOL); ?>
<?php } ?>
<!-- Remove cron job -->
<?php if(!empty($_POST['remove_cron'])) { ?>
<?php $remove_cron = str_replace($_POST['remove_cron']."\n", "", $output); ?>
<?php file_put_contents($cron_file, $remove_cron.PHP_EOL); ?>
<?php } ?>
<!-- Remove all cron jobs -->
<?php if(isset($_POST['remove_all_cron'])) { ?>
<?php echo exec("crontab -r"); ?>
<?php } else { ?>
<?php echo exec("crontab $cron_file"); ?>
<?php } ?>
<!-- Reload page to get updated cron jobs -->
<?php $uri = $_SERVER['REQUEST_URI']; ?>
<?php header("Location: $uri"); ?>
<?php exit; ?>
<?php } ?>
<b>Current Cron Jobs:</b><br>
<?php echo nl2br($output); ?>
<h2>Add or Remove Cron Job</h2>
<form method="post" action="<?php $_SERVER['REQUEST_URI']; ?>">
<b>Add New Cron Job:</b><br>
<input type="text" name="add_cron" size="100" placeholder="e.g.: * * * * * /usr/local/bin/php -q /home/username/public_html/my_cron.php"><br>
<b>Remove Cron Job:</b><br>
<input type="text" name="remove_cron" size="100" placeholder="e.g.: * * * * * /usr/local/bin/php -q /home/username/public_html/my_cron.php"><br>
<input type="checkbox" name="remove_all_cron" value="1"> Remove all cron jobs?<br>
<input type="submit"><br>
</form>
In the manual for GNU make, they talk about this specific example when describing the value
function:
The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.
The syntax of the value function is:
$(value variable)
Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)
The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:
FOO = $PATH all: @echo $(FOO) @echo $(value FOO)
The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.
I had the same warning in VS 2017. As it turned out in my case I had added a unit test project and needed to set a dependency for the unit test on the DLL it was testing.
The other answers were incomplete for me. I started from @Vladimir Novopashin answer and modified it. Here are the things, that I needed and bug I found:
.prop
instead of [prop]
. For example, formData.append('photos[0][file]', file)
didn't work on google chrome, while
formData.append('photos[0].file', file)
workedThe following code should work on IE11 and evergreen browsers.
function objectToFormData(obj, rootName, ignoreList) {
var formData = new FormData();
function appendFormData(data, root) {
if (!ignore(root)) {
root = root || '';
if (data instanceof File) {
formData.append(root, data);
} else if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
appendFormData(data[i], root + '[' + i + ']');
}
} else if (typeof data === 'object' && data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
if (root === '') {
appendFormData(data[key], key);
} else {
appendFormData(data[key], root + '.' + key);
}
}
}
} else {
if (data !== null && typeof data !== 'undefined') {
formData.append(root, data);
}
}
}
}
function ignore(root){
return Array.isArray(ignoreList)
&& ignoreList.some(function(x) { return x === root; });
}
appendFormData(obj, rootName);
return formData;
}
I used @timestamp
instead of _timestamp
{
'size' : 1,
'query': {
'match_all' : {}
},
"sort" : [{"@timestamp":{"order": "desc"}}]
}
You might want to do it like this:
DateTime? lastPostDate = (DateTime?)(reader.IsDbNull(3) ? null : reader[3]);
The problem you are having is that the ternary operator wants a viable cast between the left and right sides. And null can't be cast to DateTime.
Note the above works because both sides of the ternary are object's. The object is explicitly cast to DateTime? which works: as long as reader[3] is in fact a date.
One way to look at the & (reference) operator in c++ is that is merely a syntactic sugar to a pointer. For example, the following are roughly equivalent:
void foo(int &x)
{
x = x + 1;
}
void foo(int *x)
{
*x = *x + 1;
}
The more useful is when you're dealing with a class, so that your methods turn from x->bar() to x.bar().
The reason I said roughly is that using references imposes additional compile-time restrictions on what you can do with the reference, in order to protect you from some of the problems caused when dealing with pointers. For instance, you can't accidentally change the pointer, or use the pointer in any way other than to reference the singular object you've been passed.
The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, &&
and ||
only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{}
construction and to direct program control rather than construct new vectors.. The &
and the |
operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.
When the arguments to &&
or ||
are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.
> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3
The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.
This worked for me:
.footer
{
width: 100%;
bottom: 0;
clear: both;
}
Use Range in Python 3.
Here is a example function that return in between numbers from two numbers
def get_between_numbers(a, b):
"""
This function will return in between numbers from two numbers.
:param a:
:param b:
:return:
"""
x = []
if b < a:
x.extend(range(b, a))
x.append(a)
else:
x.extend(range(a, b))
x.append(b)
return x
Result
print(get_between_numbers(5, 9))
print(get_between_numbers(9, 5))
[5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
DEBUG will show all messages, INFO all besides DEBUG messages, and so on.
Usually one uses either INFO or WARN. This dependens on the company policy.
Try this code:
[self.navigationController presentViewController:controller animated:YES completion:nil];
I was tearing my hair out because for some items, the renamed item would get renamed again (repeatedly, unless max file name length was reached). This was happening both for Get-ChildItem and piping the output of dir. I guess that the renamed files got picked up because of a change in the alphabetical ordering. I solved this problem in the following way:
Get-ChildItem -Path . -OutVariable dirs
foreach ($i in $dirs) { Rename-Item $i.name ("<MY_PREFIX>"+$i.name) }
This "locks" the results returned by Get-ChildItem in the variable $dirs and you can iterate over it without fear that ordering will change or other funny business will happen.
Dave.Gugg's tip for using -Exclude should also solve this problem, but this is a different approach; perhaps if the files being renamed already contain the pattern used in the prefix.
(Disclaimer: I'm very much a PowerShell n00b.)
Technically, you can too put image data in an img tag, using data URIs.
<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" />
There are some special circumstances where this could even be useful, although in most cases you're better off serving the image through a separate script like daiscog suggests.
A little improvement to Matthew's answer could be a lookahead instead of the last capturing group:
.replace(/(\w+)(\d+)(?=\w+)/, "$1!NEW_ID!");
Or you could split on the decimal and join with your new id like this:
.split(/\d+/).join("!NEW_ID!");
Example/Benchmark here: https://codepen.io/jogai/full/oyNXBX
Use the absolute value function ABS. The syntax is
ABS ( numeric_expression )
You have a character = STQ8QGpaM4CU6149665!7084880820
, and you have a another column = 7084880820
.
If you want to get only this in excel using the formula: STQ8QGpaM4CU6149665!
, use this:
=REPLACE(H11,SEARCH(J11,H11),LEN(J11),"")
H11 is an old character and for starting number use search option then for no of character needs to replace use len option then replace to new character. I am replacing this to blank.
You can use the code below:
li:hover { cursor: pointer; }
Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n
first):
>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]
Updating this after many years in response to comments of this not working for powers of 10:
[(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]
The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0
--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.
In [32]: n = 43
In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[33]: [4, 3]
In [34]: n = 1000
In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[35]: [1, 0, 0, 0]
Annotating with @JsonAlias
which got introduced with Jackson 2.9+, without mentioning @JsonProperty
on the item to be deserialized with more than one alias(different names for a json property) works fine.
I used com.fasterxml.jackson.annotation.JsonAlias
for package consistency with com.fasterxml.jackson.databind.ObjectMapper
for my use-case.
For e.g.:
@Data
@Builder
public class Chair {
@JsonAlias({"woodenChair", "steelChair"})
private String entityType;
}
@Test
public void test1() {
String str1 = "{\"woodenChair\":\"chair made of wood\"}";
System.out.println( mapper.readValue(str1, Chair.class));
String str2 = "{\"steelChair\":\"chair made of steel\"}";
System.out.println( mapper.readValue(str2, Chair.class));
}
just works fine.
You can cast like this:
return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);
Or like this if you want to be compatible with tsx mode:
return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);
Just remember that this is a compile-time cast, and not a runtime cast.
One addition to @Omid Ariyan's answer is permissions on directories. Add this after the for
loop's done
in his pre-commit
script.
for DIR in $(find ./ -mindepth 1 -type d -not -path "./.git" -not -path "./.git/*" | sed 's@^\./@@')
do
# Save the permissions of all the files in the index
echo $DIR";"`stat -c "%a;%U;%G" $DIR` >> $DATABASE
done
This will save directory permissions as well.
Working JSFIDDLE
If your form is like
<form action="" method="get" id="hidden-element-test">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
<br><br>
<button id="add-input">Add hidden input</button>
<button id="add-textarea">Add hidden textarea</button>
You can add hidden input and textarea to form like this
$(document).ready(function(){
$("#add-input").on('click', function(){
$('#hidden-element-test').prepend('<input type="hidden" name="ipaddress" value="192.168.1.201" />');
alert('Hideen Input Added.');
});
$("#add-textarea").on('click', function(){
$('#hidden-element-test').prepend('<textarea name="instructions" style="display:none;">this is a test textarea</textarea>');
alert('Hideen Textarea Added.');
});
});
Check working jsfiddle here
I'd recommend to replace all :hover
properties to :active
when you detect that device supports touch. Just call this function when you do so as touch()
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
This code is ill-formed:
int&const icr=i;
Reference: C++17 [dcl.ref]/1:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name or decltype-specifier, in which case the cv-qualifiers are ignored.
This rule has been present in all standardized versions of C++. Because the code is ill-formed:
The compiler should reject the program; and if it doesn't, the executable's behaviour is completely undefined.
NB: Not sure how none of the other answers mentioned this yet... nobody's got access to a compiler?
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
I think if you think it from the point of CALayer
, everything is more clear.
Frame is not really a distinct property of the view or layer at all, it is a virtual property, computed from the bounds, position(UIView
's center), and transform.
So basically how the layer/view layouts is really decided by these three property(and anchorPoint), and either of these three property won't change any other property, like changing transform doesn't change bounds.
You can use the following. They all wrap the window
object into a jQuery object.
$(window).load(function () {
topInViewport($("#mydivname"))
});
$(window).resize(function () {
topInViewport($("#mydivname"))
});
$(window).scroll(function () {
topInViewport($("#mydivname"))
});
Or bind to them all using on
:
$(window).on("load resize scroll",function(e){
topInViewport($("#mydivname"))
});
From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response
"text": A plain text string.
So you want contentType to be application/json
and dataType to be text
:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
signup to github and then use:
https://import.github.com/new.
instructions:
once you have a git repo on github you can download zip
Compared to the other parser libraries lxml
is extremely fast:
And with cssselect
it’s quite easy to use for scraping HTML pages too:
from lxml.html import parse
doc = parse('http://www.google.com').getroot()
for div in doc.cssselect('a'):
print '%s: %s' % (div.text_content(), div.get('href'))
Using Xcode 12.3 Distribute App and xcodebuild both got stuck today at this point.
I finally was able to solve this. Peeking around my system I found 3 versions of iTMSTransporter.
Printing the version of each using ./iTMSTransporter -version
gives the following results:
/Applications/Transporter.app/Contents/itms/bin/
has version 2.0.0
/Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/Versions/A/itms/bin/
has version 2.1.0
/usr/local/itms/bin/
has version version 1.9.3
So it looks that old version in /usr/local/itms
was used by Xcode. After deleting /usr/local/itms
I was able to upload my binary within Xcode 12.2 and using the xcodebuild
command line tool.
@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
DECLARE @AA INT
SET @AA=(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress)
IF @AA> 0
BEGIN
SET @UserId = 0
END
ELSE
BEGIN
INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
SELECT SCOPE_IDENTITY()
END
END
Try username = root and password is blank.
If your existing code is already relying on from datetime import datetime
, you can also simply also import date
from datetime import datetime, timedelta, date
print isinstance(datetime.today().date(), date)
Use microsoft's tool for remote commands executions: PsExec
If there isn't your bat-file on remote host, copy it first. For example:
copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\
And then execute:
psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat
Note: filepath for psexec is path to file on remote server, not your local.
The following compiles for me:
class E{
String s = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[~#;:?/@&!\"'%*=¼.,-])(?=[^\\s]+$).{8,24}$";
}
See:
If you need to open the DevTools press ctrl-shift-i.
If the DevTools window is already opened you can use the ctrl-shift-d shortcut; it switches the window into a detached mode.
For example in my case the electron application window (Chrome) is really small.
It's not possible to use any other suggestions except the ctrl-shift-d shortcut
Just Add reference to System.Web.Extensions and happy to go.
If you want to know if it's an empty string use === instead of ==.
if(variable === "") {
}
This is because === will only return true if the values on both sides are of the same type, in this case a string.
for example: (false == "") will return true, and (false === "") will return false.
Another variation:
UPDATE test
SET field = IF ( {condition}, {new value}, field )
WHERE id = 123
This will update the field
with {new value}
only if {condition}
is met
Unfortunately C# still doesn't offer this capability in the built in libs. The best solution at present is to create a custom class with a method that pops up a small form. If you're working in Visual Studio you can do this by clicking on Project >Add class
Name the class PopUpBox (you can rename it later if you like) and paste in the following code:
using System.Drawing;
using System.Windows.Forms;
namespace yourNameSpaceHere
{
public class PopUpBox
{
private static Form prompt { get; set; }
public static string GetUserInput(string instructions, string caption)
{
string sUserInput = "";
prompt = new Form() //create a new form at run time
{
Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption,
StartPosition = FormStartPosition.CenterScreen, TopMost = true
};
//create a label for the form which will have instructions for user input
Label lblTitle = new Label() { Left = 50, Top = 20, Text = instructions, Dock = DockStyle.Top, TextAlign = ContentAlignment.TopCenter };
TextBox txtTextInput = new TextBox() { Left = 50, Top = 50, Width = 400 };
////////////////////////////OK button
Button btnOK = new Button() { Text = "OK", Left = 250, Width = 100, Top = 70, DialogResult = DialogResult.OK };
btnOK.Click += (sender, e) =>
{
sUserInput = txtTextInput.Text;
prompt.Close();
};
prompt.Controls.Add(txtTextInput);
prompt.Controls.Add(btnOK);
prompt.Controls.Add(lblTitle);
prompt.AcceptButton = btnOK;
///////////////////////////////////////
//////////////////////////Cancel button
Button btnCancel = new Button() { Text = "Cancel", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.Cancel };
btnCancel.Click += (sender, e) =>
{
sUserInput = "cancel";
prompt.Close();
};
prompt.Controls.Add(btnCancel);
prompt.CancelButton = btnCancel;
///////////////////////////////////////
prompt.ShowDialog();
return sUserInput;
}
public void Dispose()
{prompt.Dispose();}
}
}
You will need to change the namespace to whatever you're using. The method returns a string, so here's an example of how to implement it in your calling method:
bool boolTryAgain = false;
do
{
string sTextFromUser = PopUpBox.GetUserInput("Enter your text below:", "Dialog box title");
if (sTextFromUser == "")
{
DialogResult dialogResult = MessageBox.Show("You did not enter anything. Try again?", "Error", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
boolTryAgain = true; //will reopen the dialog for user to input text again
}
else if (dialogResult == DialogResult.No)
{
//exit/cancel
MessageBox.Show("operation cancelled");
boolTryAgain = false;
}//end if
}
else
{
if (sTextFromUser == "cancel")
{
MessageBox.Show("operation cancelled");
}
else
{
MessageBox.Show("Here is the text you entered: '" + sTextFromUser + "'");
//do something here with the user input
}
}
} while (boolTryAgain == true);
This method checks the returned string for a text value, empty string, or "cancel" (the getUserInput method returns "cancel" if the cancel button is clicked) and acts accordingly. If the user didn't enter anything and clicked OK it will tell the user and ask them if they want to cancel or re-enter their text.
Post notes: In my own implementation I found that all of the other answers were missing 1 or more of the following:
Thus, I have posted my own solution. I hope someone finds it useful. Credit to Bas and Gideon + commenters for your contributions, you helped me to come up with a workable solution!
Sorry for the delay. I was with the same problem and I found a link with good answers, could that will help new guys
All credits for BinaryIntellect web site and the authors
Basically, there are four situations: using differents verbs, using routing, overload marking with [NoAction] attribute and change the action attribute name with [ActionName]
So, depends that's your requiriments and your situation.
Howsoever, follow the link:
Link: http://www.binaryintellect.net/articles/8f9d9a8f-7abf-4df6-be8a-9895882ab562.aspx
You can use pageshow
event to handle situation when browser navigates to your page through history traversal:
window.addEventListener( "pageshow", function ( event ) {
var historyTraversal = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( historyTraversal ) {
// Handle page restore.
window.location.reload();
}
});
Note that HTTP cache may be involved too. You need to set proper cache related HTTP headers on server to cache only those resources that need to be cached. You can also do forced reload to instuct browser to ignore HTTP cache: window.location.reload( true )
. But I don't think that it is best solution.
For more information check:
This problem has bothered me for 15 years, and all the solutions supplied weren't satisfactory for me. How do you create a dynamic multidimensional array contiguously in memory? Today I finally found the answer. Using the following code, you can do just that:
#include <iostream>
int main(int argc, char** argv)
{
if (argc != 3)
{
std::cerr << "You have to specify the two array dimensions" << std::endl;
return -1;
}
int sizeX, sizeY;
sizeX = std::stoi(argv[1]);
sizeY = std::stoi(argv[2]);
if (sizeX <= 0)
{
std::cerr << "Invalid dimension x" << std::endl;
return -1;
}
if (sizeY <= 0)
{
std::cerr << "Invalid dimension y" << std::endl;
return -1;
}
/******** Create a two dimensional dynamic array in continuous memory ******
*
* - Define the pointer holding the array
* - Allocate memory for the array (linear)
* - Allocate memory for the pointers inside the array
* - Assign the pointers inside the array the corresponding addresses
* in the linear array
**************************************************************************/
// The resulting array
unsigned int** array2d;
// Linear memory allocation
unsigned int* temp = new unsigned int[sizeX * sizeY];
// These are the important steps:
// Allocate the pointers inside the array,
// which will be used to index the linear memory
array2d = new unsigned int*[sizeY];
// Let the pointers inside the array point to the correct memory addresses
for (int i = 0; i < sizeY; ++i)
{
array2d[i] = (temp + i * sizeX);
}
// Fill the array with ascending numbers
for (int y = 0; y < sizeY; ++y)
{
for (int x = 0; x < sizeX; ++x)
{
array2d[y][x] = x + y * sizeX;
}
}
// Code for testing
// Print the addresses
for (int y = 0; y < sizeY; ++y)
{
for (int x = 0; x < sizeX; ++x)
{
std::cout << std::hex << &(array2d[y][x]) << ' ';
}
}
std::cout << "\n\n";
// Print the array
for (int y = 0; y < sizeY; ++y)
{
std::cout << std::hex << &(array2d[y][0]) << std::dec;
std::cout << ": ";
for (int x = 0; x < sizeX; ++x)
{
std::cout << array2d[y][x] << ' ';
}
std::cout << std::endl;
}
// Free memory
delete[] array2d[0];
delete[] array2d;
array2d = nullptr;
return 0;
}
When you invoke the program with the values sizeX=20 and sizeY=15, the output will be the following:
0x603010 0x603014 0x603018 0x60301c 0x603020 0x603024 0x603028 0x60302c 0x603030 0x603034 0x603038 0x60303c 0x603040 0x603044 0x603048 0x60304c 0x603050 0x603054 0x603058 0x60305c 0x603060 0x603064 0x603068 0x60306c 0x603070 0x603074 0x603078 0x60307c 0x603080 0x603084 0x603088 0x60308c 0x603090 0x603094 0x603098 0x60309c 0x6030a0 0x6030a4 0x6030a8 0x6030ac 0x6030b0 0x6030b4 0x6030b8 0x6030bc 0x6030c0 0x6030c4 0x6030c8 0x6030cc 0x6030d0 0x6030d4 0x6030d8 0x6030dc 0x6030e0 0x6030e4 0x6030e8 0x6030ec 0x6030f0 0x6030f4 0x6030f8 0x6030fc 0x603100 0x603104 0x603108 0x60310c 0x603110 0x603114 0x603118 0x60311c 0x603120 0x603124 0x603128 0x60312c 0x603130 0x603134 0x603138 0x60313c 0x603140 0x603144 0x603148 0x60314c 0x603150 0x603154 0x603158 0x60315c 0x603160 0x603164 0x603168 0x60316c 0x603170 0x603174 0x603178 0x60317c 0x603180 0x603184 0x603188 0x60318c 0x603190 0x603194 0x603198 0x60319c 0x6031a0 0x6031a4 0x6031a8 0x6031ac 0x6031b0 0x6031b4 0x6031b8 0x6031bc 0x6031c0 0x6031c4 0x6031c8 0x6031cc 0x6031d0 0x6031d4 0x6031d8 0x6031dc 0x6031e0 0x6031e4 0x6031e8 0x6031ec 0x6031f0 0x6031f4 0x6031f8 0x6031fc 0x603200 0x603204 0x603208 0x60320c 0x603210 0x603214 0x603218 0x60321c 0x603220 0x603224 0x603228 0x60322c 0x603230 0x603234 0x603238 0x60323c 0x603240 0x603244 0x603248 0x60324c 0x603250 0x603254 0x603258 0x60325c 0x603260 0x603264 0x603268 0x60326c 0x603270 0x603274 0x603278 0x60327c 0x603280 0x603284 0x603288 0x60328c 0x603290 0x603294 0x603298 0x60329c 0x6032a0 0x6032a4 0x6032a8 0x6032ac 0x6032b0 0x6032b4 0x6032b8 0x6032bc 0x6032c0 0x6032c4 0x6032c8 0x6032cc 0x6032d0 0x6032d4 0x6032d8 0x6032dc 0x6032e0 0x6032e4 0x6032e8 0x6032ec 0x6032f0 0x6032f4 0x6032f8 0x6032fc 0x603300 0x603304 0x603308 0x60330c 0x603310 0x603314 0x603318 0x60331c 0x603320 0x603324 0x603328 0x60332c 0x603330 0x603334 0x603338 0x60333c 0x603340 0x603344 0x603348 0x60334c 0x603350 0x603354 0x603358 0x60335c 0x603360 0x603364 0x603368 0x60336c 0x603370 0x603374 0x603378 0x60337c 0x603380 0x603384 0x603388 0x60338c 0x603390 0x603394 0x603398 0x60339c 0x6033a0 0x6033a4 0x6033a8 0x6033ac 0x6033b0 0x6033b4 0x6033b8 0x6033bc 0x6033c0 0x6033c4 0x6033c8 0x6033cc 0x6033d0 0x6033d4 0x6033d8 0x6033dc 0x6033e0 0x6033e4 0x6033e8 0x6033ec 0x6033f0 0x6033f4 0x6033f8 0x6033fc 0x603400 0x603404 0x603408 0x60340c 0x603410 0x603414 0x603418 0x60341c 0x603420 0x603424 0x603428 0x60342c 0x603430 0x603434 0x603438 0x60343c 0x603440 0x603444 0x603448 0x60344c 0x603450 0x603454 0x603458 0x60345c 0x603460 0x603464 0x603468 0x60346c 0x603470 0x603474 0x603478 0x60347c 0x603480 0x603484 0x603488 0x60348c 0x603490 0x603494 0x603498 0x60349c 0x6034a0 0x6034a4 0x6034a8 0x6034ac 0x6034b0 0x6034b4 0x6034b8 0x6034bc
0x603010: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0x603060: 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
0x6030b0: 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
0x603100: 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
0x603150: 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
0x6031a0: 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
0x6031f0: 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
0x603240: 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
0x603290: 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
0x6032e0: 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
0x603330: 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
0x603380: 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
0x6033d0: 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
0x603420: 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
0x603470: 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
As you can see, the multidimensional array lies contiguously in memory, and no two memory addresses are overlapping. Even the routine for freeing the array is simpler than the standard way of dynamically allocating memory for every single column (or row, depending on how you view the array). Since the array basically consists of two linear arrays, only these two have to be (and can be) freed.
This method can be extended for more than two dimensions with the same concept. I won't do it here, but when you get the idea behind it, it is a simple task.
I hope this code will help you as much as it helped me.
id
overviewAn Android id
is an integer commonly used to identify views; this id
can be assigned via XML (when possible) and via code (programmatically.) The id
is most useful for getting references for XML-defined View
s generated by an Inflater
(such as by using setContentView
.)
id
via XML
android:id="@+id/
somename"
to your view.android:id
will be assigned a unique int
for use in code.android:id
's int
value in code using "R.id.
somename" (effectively a constant.)int
can change from build to build so never copy an id from gen/
package.name/R.java
, just use "R.id.
somename".id
assigned to a Preference
in XML is not used when the Preference
generates its View
.)id
via code (programmatically)id
s using someView.setId(
int);
int
must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)id
sXML
-assigned id
s will be unique.id
s do not have to be uniqueid
s can (theoretically) conflict with XML
-assigned id
s.id
s won't matter if queried correctly (keep reading).id
s don't matterfindViewById(int)
will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View
it finds with a matching id
.id
s assigned before an XML-defined id
in the hierarchy, findViewById(R.id.somename)
will always return the XML-defined View so id
'd.ID
sViewGroup
with id
.LinearLayout
with android:id="@+id/placeholder"
.ViewGroup
with View
s.id
s that are convenient to each view.Query these child views using placeholder.findViewById(convenientInt);
API 17 introduced View.generateViewId()
which allows you to generate a unique ID.
If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext()
and be sure to set each reference to null in onDestroy
. Apparently leaking the Activity
(hanging onto it after is is destroyed) is wasteful.. :)
android:id
for use in codeAPI 17 introduced View.generateViewId()
which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*
If your ViewGroup
cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:
Here, values/ids.xml defines a custom id
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="reservedNamedId" type="id"/>
</resources>
Then once the ViewGroup or View has been created, you can attach the custom id
myViewGroup.setId(R.id.reservedNamedId);
id
exampleFor clarity by way of obfuscating example, lets examine what happens when there is an id
conflict behind the scenes.
layout/mylayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/placeholder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
To simulate a conflict, lets say our latest build assigned R.id.placeholder
(@+id/placeholder
) an int
value of 12
..
Next, MyActivity.java defines some adds views programmatically (via code):
int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
TextView tv = new TextView(this.getApplicationContext());
// One new TextView will also be assigned an id==12:
tv.setId(i);
placeholder.addView(tv);
}
So placeholder
and one of our new TextView
s both have an id
of 12! But this isn't really a problem if we query placeholder's child views:
// Will return a generated TextView:
placeholder.findViewById(12);
// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12:
Activity.this.findViewById(12);
*Not so bad
(for Mac, see the link in Partizano's comment below)
I know there's already an answer suggesting this, however I want to provide the explanation and instructions for this that Telerik should have provided, and also cover some of the 'gotchas', so here goes:
NOTE: For this to work, any request you want to intercept must be sent to port 8888
You do this by appending :8888 to your hostname, for example like this for an MVC route:
http://myhostname:8888/controller/action
Run Fiddler as administrator Go to Tools > Fiddler Options > Connections, and ensure that 'Allow remote computers to connect' is checked, and 'Fiddler listens on port' is set to 8888:
Configure Fiddler to forward requests received on port 8888 to port 80
That's it! Fiddler should now be set up as a reverse proxy, to intercept all requests from port 8888 (so that you can view them in Fiddler), and it will then forward them to your web server to actually be handled.
http://remoteHostname:8888/controller/action
IMPORTANT: Once you've finished viewing your request(s), go back to Tools > Fiddler Options > Connections and remove the 'Allow remote computers to connect' option, otherwise 3rd parties will be able to bounce traffic through your server
Newer versions of svn support the --show-item
argument:
svn info --show-item revision
For the revision number of your local working copy, use:
svn info --show-item last-changed-revision
You can use os.system()
to execute a command line like this:
svn info | grep "Revision" | awk '{print $2}'
I do that in my nightly build scripts.
Also on some platforms there is a svnversion
command, but I think I had a reason not to use it. Ahh, right. You can't get the revision number from a remote repository to compare it to the local one using svnversion.
Another way to applyhorizontalalignment
and rotation
to each tick label is doing a for
loop over the tick labels you want to change:
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]
hours_value = np.random.random(len(hours))
days_value = np.random.random(len(days))
fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
axs[0].plot(hours,hours_value)
axs[1].plot(days,days_value)
for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
label.set_rotation(30)
label.set_horizontalalignment("right")
And here is an example if you want to control the location of major and minor ticks:
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]
axs[0].plot(hours,np.random.random(len(hours)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.HourLocator(byhour = range(0,25,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[0].xaxis.set_major_locator(x_major_lct)
axs[0].xaxis.set_minor_locator(x_minor_lct)
axs[0].xaxis.set_major_formatter(x_fmt)
axs[0].set_xlabel("minor ticks set to every hour, major ticks start with 00:00")
axs[1].plot(days,np.random.random(len(days)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.DayLocator(bymonthday = range(0,32,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[1].xaxis.set_major_locator(x_major_lct)
axs[1].xaxis.set_minor_locator(x_minor_lct)
axs[1].xaxis.set_major_formatter(x_fmt)
axs[1].set_xlabel("minor ticks set to every day, major ticks show first day of month")
for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
label.set_rotation(30)
label.set_horizontalalignment("right")
SELECT character_set_name
FROM information_schema.character_sets
;
information_schema
From the SQL-standard schema information_schema
present in every database/catalog, use the defined view named character_sets
. This approach should be portable across all standard database systems.
SELECT *
FROM information_schema.character_sets
;
Despite the name being plural, it shows only a single row, reporting on the current database/catalog.
The third column is character_set_name
:
Name of the character set, currently implemented as showing the name of the database encoding
Use os.path.join
to concatenate the directory and file name:
for path, subdirs, files in os.walk(root):
for name in files:
print(os.path.join(path, name))
Note the usage of path
and not root
in the concatenation, since using root
would be incorrect.
In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join
would be:
pathlib.PurePath(path, name)
The advantage of pathlib
is that you can use a variety of useful methods on paths. If you use the concrete Path
variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.
If you are using gradle with spring boot and spring JPA then add the below dependency in the build.gradle file
dependencies { compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.1.3.RELEASE'
}
Underscore-java library has json builder.
String json = U.objectBuilder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", U.objectBuilder()
.add("innerKey1", "value3"))
.toJson();
If your web page has jquery in your page, then you can do it writing on chrome developers console:
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
Its jquery way of doing it!
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
string myFilePath = @"C:\MyFile.txt";
string ext = Path.GetExtension(myFilePath);
// ext would be ".txt"
Strings, by C
definition, are terminated by '\0'
. You have no "C strings"
in your program.
Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.
To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).
You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C
sense of the word.
If you run your program with input redirection, the EOF
is the actual end of file, not a make belief one
./a.out < source.c
you can try like This
ArrayList<String> dtlst = new ArrayList<String>();
String qry1 = "select dt_tracker from gs";
Statement prepst = conn.createStatement();
ResultSet rst = prepst.executeQuery(qry1);
while(rst.next())
{
String dt = "";
try
{
dt = rst.getDate("dt_tracker")+" "+rst.getTime("dt_tracker");
}
catch(Exception e)
{
dt = "0000-00-00 00:00:00";
}
dtlst.add(dt);
}
stage.getIcons().add(new Image(ClassLoader.getSystemResourceAsStream("images/icon.png")));
images folder need to be in Resource folder.
Quick solution in NetBeans 6.8.
In the Projects window right-click on the name of the project that lacks library -> Properties -> The Project Properties window opens. In Categories tree select "Libraries" node -> On the right side of the Project Properties window press button "Add JAR/Folder" -> Select jars you need.
You also can see my short Video How-To.
You can Change it from:
Menu Settings -> Style Configurator
See on screenshot:
Unfortunately we need to run docker-compose logs
separately from docker-compose run
. In order to get this to work reliably we need to suppress the docker-compose run
exit status then redirect the log and exit with the right status.
#!/bin/bash
set -euo pipefail
docker-compose run app | tee app.log || failed=yes
docker-compose logs --no-color > docker-compose.log
[[ -z "${failed:-}" ]] || exit 1
You can add to the system-path at runtime:
import sys
sys.path.insert(0, 'path/to/your/py_file')
import py_file
This is by far the easiest way to do it.
In my case, I had to change the Copy Local setting to true (right-click assembly in solution explorer, select properties, locate and change value of Copy Local property). Once this setting was changed, publication of my WCF service copied the file to the server and the error went away.
I've seen many ways of doing this on here. However I think this is a little more efficient or at least concise than the other answers.
TextField(
controller: TextEditingController(text: "Initial Text here"),
)
If the above doesn't work for you, try this:
.btn:focus {outline: none;box-shadow: none;border:2px solid transparent;}
As user1933897 pointed out, this might be specific to MacOS with Chrome.
For modern browsers, use td:nth-child(2)
for the second td
, and td:nth-child(3)
for the third. Remember that these retrieve the second and third td
for every row.
If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.
This should give you the roles, users and permissions granted on a directory:
SELECT *
FROM all_tab_privs
WHERE table_name = 'your_directory'; --> needs to be upper case
And yes, it IS in the all_TAB_privs view ;-) A better name for that view would be something like "ALL_OBJECT_PRIVS", since it also includes PL/SQL objects and their execute permissions as well.
Numpy
has the prod()
function that returns the product of a list, or in this case since it's numpy, it's the product of an array over a given axis:
import numpy
a = [1,2,3,4,5,6]
b = numpy.prod(a)
...or else you can just import numpy.prod()
:
from numpy import prod
a = [1,2,3,4,5,6]
b = prod(a)
Something along the lines of
StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();
Ought to be what you need.
Relevant documentation:
Don't put the environment configuration in catalina.bat/catalina.sh. Instead you should create a new file in CATALINA_BASE\bin\setenv.bat to keep your customizations separate of tomcat installation.
Step 1 : Go to Files. Step 2 : Go to Folders. Step 3 : Create Assets Folder.
In Assets folder just put fonts and use it if needed.
Use append method, eg:
lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)
I also don't under stand what the "-" means after the 200 140 section of the log
That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)
I tried all, but this worked for me. In a class I have another class named "crimeScene
", and want to sort by a property of "crimeScene
".
This works like a charm:
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"crimeScene.distance" ascending:YES];
[self.arrAnnotations sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
I understand the ZooKeeper in general but had problems with the terms "quorum" and "split brain" so maybe I can share my findings with you (I consider myself also a layman).
Let's say we have a ZooKeeper cluster of 5 servers. One of the servers will become the leader and the others will become followers.
These 5 servers form a quorum. Quorum simply means "these servers can vote upon who should be the leader".
So the voting is based on majority. Majority simply means "more than half" so more than half of the number of servers must agree for a specific server to become the leader.
So there is this bad thing that may happen called "split brain". A split brain is simply this, as far as I understand: The cluster of 5 servers splits into two parts, or let's call it "server teams", with maybe one part of 2 and the other of 3 servers. This is really a bad situation as if both "server teams" must execute a specific order how would you decide wich team should be preferred? They might have received different information from the clients. So it is really important to know what "server team" is still relevant and which one can/should be ignored.
Majority is also the reason you should use an odd number of servers. If you have 4 servers and a split brain where 2 servers seperate then both "server teams" could say "hey, we want to decide who is the leader!" but how should you decide which 2 servers you should choose? With 5 servers it's simple: The server team with 3 servers has the majority and is allowed to select the new leader.
Even if you just have 3 servers and one of them fails the other 2 still form the majority and can agree that one of them will become the new leader.
I realize once you think about it some time and understand the terms it's not so complicated anymore. I hope this also helps anyone in understanding these terms.
Well generally you shouldn't need to classify an element specified by id, because id is always unique, but if you really need to, the following should work:
div#content.sectionA {
/* ... */
}
Based on Wakas Bukhary answer, you could make it async by puting the last line in the response scope.
$('#myform').submit(function(event) {
event.preventDefault(); //this will prevent the default submit
var _this = $(this); //store form so it can be accessed later
$.ajax('GET', 'url').then(function(resp) {
// your code here
_this.unbind('submit').submit(); // continue the submit unbind preventDefault
})
}
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#define print_err(format, args...) printf("[%s:%d][error]" format "\n", __func__, __LINE__, ##args)
#define DATA_BUF_SIZE (64 * 1024) //limit to read maximum 64 KB data per time
int32_t get_file_size(const char *fname){
struct stat sbuf;
if (NULL == fname || strlen(fname) < 1){
return 0;
}
if (stat(fname, &sbuf) < 0){
print_err("%s, %s", fname, strerror(errno));
return 0;
}
return sbuf.st_size; /* off_t shall be signed interge types, used for file size */
}
bool copyFile(CHAR *pszPathIn, CHAR *pszPathOut)
{
INT32 fdIn, fdOut;
UINT32 ulFileSize_in = 0;
UINT32 ulFileSize_out = 0;
CHAR *szDataBuf;
if (!pszPathIn || !pszPathOut)
{
print_err(" Invalid param!");
return false;
}
if ((1 > strlen(pszPathIn)) || (1 > strlen(pszPathOut)))
{
print_err(" Invalid param!");
return false;
}
if (0 != access(pszPathIn, F_OK))
{
print_err(" %s, %s!", pszPathIn, strerror(errno));
return false;
}
if (0 > (fdIn = open(pszPathIn, O_RDONLY)))
{
print_err("open(%s, ) failed, %s", pszPathIn, strerror(errno));
return false;
}
if (0 > (fdOut = open(pszPathOut, O_CREAT | O_WRONLY | O_TRUNC, 0777)))
{
print_err("open(%s, ) failed, %s", pszPathOut, strerror(errno));
close(fdIn);
return false;
}
szDataBuf = malloc(DATA_BUF_SIZE);
if (NULL == szDataBuf)
{
print_err("malloc() failed!");
return false;
}
while (1)
{
INT32 slSizeRead = read(fdIn, szDataBuf, sizeof(szDataBuf));
INT32 slSizeWrite;
if (slSizeRead <= 0)
{
break;
}
slSizeWrite = write(fdOut, szDataBuf, slSizeRead);
if (slSizeWrite < 0)
{
print_err("write(, , slSizeRead) failed, %s", slSizeRead, strerror(errno));
break;
}
if (slSizeWrite != slSizeRead) /* verify wheter write all byte data successfully */
{
print_err(" write(, , %d) failed!", slSizeRead);
break;
}
}
close(fdIn);
fsync(fdOut); /* causes all modified data and attributes to be moved to a permanent storage device */
close(fdOut);
ulFileSize_in = get_file_size(pszPathIn);
ulFileSize_out = get_file_size(pszPathOut);
if (ulFileSize_in == ulFileSize_out) /* verify again wheter write all byte data successfully */
{
free(szDataBuf);
return true;
}
free(szDataBuf);
return false;
}
An important note about Hashtable vs Dictionary for high frequency systematic trading engineering: Thread Safety Issue
Hashtable is thread safe for use by multiple threads. Dictionary public static members are thread safe, but any instance members are not guaranteed to be so.
So Hashtable remains the 'standard' choice in this regard.
easy way is:
a = [1,2]
d = {}
for i in a:
d[i]=[i, ]
print(d)
{'1': [1, ], '2':[2, ]}
Store the double quote character in a variable:
dqt='"'
echo "Double quotes ${dqt}X${dqt} inside a double quoted string"
Output:
Double quotes "X" inside a double quoted string
Disable the button with setEnabled(false)
until it is safe for the user to click it again.
Try using Replace
to see if it will work for you. The problem as I see it which has been mentioned a few times above is the CDate function is choking on the periods. You can use replace to change them to slashes. To answer your question about a Function in vba that can parse any date format, there is not any you have very limited options.
Dim current as Date, highest as Date, result() as Date
For Each itemDate in DeliveryDateArray
Dim tempDate As String
itemDate = IIf(Trim(itemDate) = "", "0", itemDate) 'Added per OP's request.
tempDate = Replace(itemDate, ".", "/")
current = Format(CDate(tempDate),"dd/mm/yyyy")
if current > highest then
highest = current
end if
' some more operations an put dates into result array
Next itemDate
'After activating final sheet...
Range("A1").Resize(UBound(result), 1).Value = Application.Transpose(result)
So far, it looks like the answer that works is this one.
To break it out further, what worked for me was this:
Get-Variable -Name foo -Scope Global -ea SilentlyContinue | out-null
$? returns either true or false.
Here is a simple random generator with approx. equal probability of generating positive and negative values around 0:
int getNextRandom(const size_t lim)
{
int nextRand = rand() % lim;
int nextSign = rand() % lim;
if (nextSign < lim / 2)
return -nextRand;
return nextRand;
}
int main()
{
srand(time(NULL));
int r = getNextRandom(100);
cout << r << endl;
return 0;
}
I was able to use your sample to create a test page, and it worked just fine. My assumption is that there is something wrong with your svg file. Can you paste that here as well? Here is the sample I used.
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
<g>
<title>Layer 1</title>
<ellipse ry="30" rx="30" id="svg_1" cy="50" cx="50" stroke-width="5" stroke="#000000" fill="#FF0000"/>
</g>
</svg>
You can use both of these methods but there are differences:
SELECT ISNULL(col1, 0 ) FROM table1
SELECT COALESCE(col1, 0 ) FROM table1
Comparing COALESCE() and ISNULL():
The ISNULL function and the COALESCE expression have a similar purpose but can behave differently.
Because ISNULL is a function, it is evaluated only once. As described above, the input values for the COALESCE expression can be evaluated multiple times.
Data type determination of the resulting expression is different. ISNULL uses the data type of the first parameter, COALESCE follows the CASE expression rules and returns the data type of value with the highest precedence.
The NULLability of the result expression is different for ISNULL and COALESCE. The ISNULL return value is always considered NOT NULLable (assuming the return value is a non-nullable one) whereas COALESCE with non-null parameters is considered to be NULL. So the expressions ISNULL(NULL, 1) and COALESCE(NULL, 1) although equivalent have different nullability values. This makes a difference if you are using these expressions in computed columns, creating key constraints or making the return value of a scalar UDF deterministic so that it can be indexed as shown in the following example.
-- This statement fails because the PRIMARY KEY cannot accept NULL values -- and the nullability of the COALESCE expression for col2 -- evaluates to NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0) PRIMARY KEY,
col3 AS ISNULL(col1, 0)
);
-- This statement succeeds because the nullability of the -- ISNULL function evaluates AS NOT NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0),
col3 AS ISNULL(col1, 0) PRIMARY KEY
);
Validations for ISNULL and COALESCE are also different. For example, a NULL value for ISNULL is converted to int whereas for COALESCE, you must provide a data type.
ISNULL takes only 2 parameters whereas COALESCE takes a variable number of parameters.
if you need to know more here is the full document from msdn.
believe there should be a way in accessing file system.
Include node.d.ts
using npm i @types/node
. And then create a new tsconfig.json
file (npx tsc --init
) and create a .ts
file as followed:
import fs from 'fs';
fs.readFileSync('foo.txt','utf8');
You can use other functions in fs
as well : https://nodejs.org/api/fs.html
Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html
Today the most obvious approach is to save the object(s) to JSON.
Example using Gson.
Gson gson = new Gson();
Person[] persons = getArrayOfPersons();
String json = gson.toJson(persons);
System.out.println(json);
//output: [{"name":"Tom","age":11},{"name":"Jack","age":12}]
Person[] personsFromJson = gson.fromJson(json, Person[].class);
//...
class Person {
public String name;
public int age;
}
Gson allows converting List directly. Examples can be easily googled. I prefer to convert lists to arrays first.
Use Jenkins.
Jenkins is the recent fork by the core developers of Hudson. To understand why, you need to know the history of the project. It was originally open source and supported by Sun. Like much of what Sun did, it was fairly open, but there was a bit of benign neglect. The source, trackers, website, etc. were hosted by Sun on their relatively closed java.net platform.
Then Oracle bought Sun. For various reasons Oracle has not been shy about leveraging what it perceives as its assets. Those include some control over the logistic platform of Hudson, and particularly control over the Hudson name. Many users and contributors weren't comfortable with that and decided to leave.
So it comes down to what Hudson vs Jenkins offers. Both Oracle's Hudson and Jenkins have the code. Hudson has Oracle and Sonatype's corporate support and the brand. Jenkins has most of the core developers, the community, and (so far) much more actual work.
Read that post I linked up top, then read the rest of these in chronological order. For balance you can read the Hudson/Oracle take on it. It's pretty clear to me who is playing defensive and who has real intentions for the project.
You can also save as a file: rdd.saveAsTextFile("alicia.txt")
In the case of some programs, these errors are normal and should not be fixed.
I get these error messages when compiling the program phrap (for example). This program happens to contain code that modifies or replaces some built in functions, and when I include the appropriate header files to fix the warnings, GCC instead generates a bunch of errors. So fixing the warnings effectively breaks the build.
If you got the source as part of a distribution that should compile normally, the errors might be normal. Consult the documentation to be sure.
The answers are commonly found in Java books.
cloning: If you don't override clone method, the default behavior is shallow copy. If your objects have only primitive member variables, it's totally ok. But in a typeless language with another object as member variables, it's a headache.
serialization/deserialization
$new_object = unserialize(serialize($your_object))
This achieves deep copy with a heavy cost depending on the complexity of the object.
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
to start, i used the Code posted posted in the first Comment but i changed it like this:
public class LockableScrollView extends ScrollView {
public LockableScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public LockableScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public LockableScrollView(Context context)
{
super(context);
}
// true if we can scroll (not locked)
// false if we cannot scroll (locked)
private boolean mScrollable = true;
public void setScrollingEnabled(boolean enabled) {
mScrollable = enabled;
}
public boolean isScrollable() {
return mScrollable;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// if we can scroll pass the event to the superclass
if (mScrollable) return super.onTouchEvent(ev);
// only continue to handle the touch event if scrolling enabled
return mScrollable; // mScrollable is always false at this point
default:
return super.onTouchEvent(ev);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// if we can scroll pass the event to the superclass
if (mScrollable) return super.onInterceptTouchEvent(ev);
// only continue to handle the touch event if scrolling enabled
return mScrollable; // mScrollable is always false at this point
default:
return super.onInterceptTouchEvent(ev);
}
}
}
then i called it in by this way
((LockableScrollView)findViewById(R.id.scrollV)).setScrollingEnabled(false);
because i tried
((LockableScrollView)findViewById(R.id.scrollV)).setIsScrollable(false);
but it said that setIsScrollable is undefined
i hope this will help you
On the side, a trick that can be useful:
If you hold your multiple strings in a TStrings, you just have to use the Text property of the TStrings like in the following example.
Label1.Caption := Memo1.Lines.Text;
And you'll get your multi-line label...
void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}
Angular filters can only be applied to arrays and not objects, from angular's API -
"Selects a subset of items from array and returns it as a new array."
You have two options here:
1) move $scope.items
to an array or -
2) pre-filter the ng-repeat
items, like this:
<div ng-repeat="(k,v) in filterSecId(items)">
{{k}} {{v.pos}}
</div>
And on the Controller:
$scope.filterSecId = function(items) {
var result = {};
angular.forEach(items, function(value, key) {
if (!value.hasOwnProperty('secId')) {
result[key] = value;
}
});
return result;
}
jsfiddle: http://jsfiddle.net/bmleite/WA2BE/
history.pushState
pushes the current page state onto the history stack, and changes the URL in the address bar. So, when you go back, that state (the object you passed) are returned to you.
Currently, that is all it does. Any other page action, such as displaying the new page or changing the page title, must be done by you.
The W3C spec you link is just a draft, and browser may implement it differently. Firefox, for example, ignores the title
parameter completely.
Here is a simple example of pushState
that I use on my website.
(function($){
// Use AJAX to load the page, and change the title
function loadPage(sel, p){
$(sel).load(p + ' #content', function(){
document.title = $('#pageData').data('title');
});
}
// When a link is clicked, use AJAX to load that page
// but use pushState to change the URL bar
$(document).on('click', 'a', function(e){
e.preventDefault();
history.pushState({page: this.href}, '', this.href);
loadPage('#frontPage', this.href);
});
// This event is triggered when you visit a page in the history
// like when yu push the "back" button
$(window).on('popstate', function(e){
loadPage('#frontPage', location.pathname);
console.log(e.originalEvent.state);
});
}(jQuery));
Both the static and class keywords allow us to attach methods to a class rather than to instances of a class. For example, you might create a Student class with properties such as name and age, then create a static method numberOfStudents that is owned by the Student class itself rather than individual instances.
Where static and class differ is how they support inheritance. When you make a static method it becomes owned by the class and can't be changed by subclasses, whereas when you use class it may be overridden if needed.
Here is an Example code:
class Vehicle {
static func getCurrentSpeed() -> Int {
return 0
}
class func getCurrentNumberOfPassengers() -> Int {
return 0
}
}
class Bicycle: Vehicle {
//This is not allowed
//Compiler error: "Cannot override static method"
// static override func getCurrentSpeed() -> Int {
// return 15
// }
class override func getCurrentNumberOfPassengers() -> Int {
return 1
}
}
This is very simple to understand :-
id is used when we have to apply CSS property to one attribute only.
class is used when we have to use CSS property in many locations within the same page or different.
General :- for unique structure like staring div and buttons layout we use id .
for same CSS throughout the page or project we use class
id is light and class is little heavy
There is a nice script available on http://www.reddyss.com/SQLDownloads.aspx
To be able to use it on any database you can create it like in: http://nickstips.wordpress.com/2010/10/18/sql-making-a-stored-procedure-available-to-all-databases/
Not sure if there is other way.
To use it then use something like this:
use name_of_database
EXEC spUtil_SearchText 'value_searched', 0, 0
Much too late, but here is a method that works during gdb
session.
gdb <executable>
then
(gdb) apropos argument
This will return lots of matches, the useful one is set args
.
set args -- Set argument list to give program being debugged when it is started.
set args arg1 arg2 ...
then
r
This will run the program, passing to main(argc, argv) the arguments and the argument count.
You may want to look into os dependent line separators, e.g.:
import os
with open('./output.txt', 'a') as f1:
f1.write(content + os.linesep)
The most valuable thing it does is give you another string identical to the first, without requiring you to allocate memory (location and size) yourself. But, as noted, you still need to free it (but which doesn't require a quantity calculation, either.)
I know this is an old question, but I have just had a similar problem and I think what I did would work for you too.
I used the to_csv() method and wrote to stdout:
import sys
paramdata.to_csv(sys.stdout)
This should dump the whole dataframe whether it's nicely-printable or not, and you can use the to_csv parameters to configure column separators, whether the index is printed, etc.
Edit: It is now possible to use None
as the target for .to_csv()
with similar effect, which is arguably a lot nicer:
paramdata.to_csv(None)
There is no need of jQuery to do that. You could code a jQuery wrapper but it would be useless so you should better use
var str = "Hello World";
window.alert("Starts with Hello ? " + /^Hello/i.test(str));
window.alert("Ends with Hello ? " + /Hello$/i.test(str));
as the match() method is deprecated.
PS : the "i" flag in RegExp is optional and stands for case insensitive (so it will also return true for "hello", "hEllo", etc.).
Try the following
download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.
Unzip the file and Run intelhaxm-android.exe.
Run silent_install.bat.
In my computer Win10 x64 - VS2015 it worked
A good way to implement containsAny for sets is using the Guava Sets.intersection().
containsAny
would return a boolean
, so the call looks like:
Sets.intersection(set1, set2).isEmpty()
This returns true iff the sets are disjoint, otherwise false. The time complexity of this is likely slightly better than retainAll because you dont have to do any cloning to avoid modifying your original set.
If you have <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
but want this: <?xml version="1.0" encoding="UTF-8"?>
Just do:
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
Refining upon the answers found here I came up with the following:
getCurrentScript.js
var getCurrentScript = function () {
if (document.currentScript) {
return document.currentScript.src;
} else {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length-1].src;
}
};
module.exports = getCurrentScript;
getCurrentScriptPath.js
var getCurrentScript = require('./getCurrentScript');
var getCurrentScriptPath = function () {
var script = getCurrentScript();
var path = script.substring(0, script.lastIndexOf('/'));
return path;
};
module.exports = getCurrentScriptPath;
BTW: I'm using CommonJS module format and bundling with webpack.
By ID
document.querySelector('#element-id').style.display = 'none';
By Class (Single element)
document.querySelector('.element-class-name').style.display = 'none';
By Class (Multiple elements)
for (const elem of document.querySelectorAll('.element-class-name')) {
elem.style.display = 'none';
}
I had the same problem and i found the following solution to be very efficient. I hope that it will help you or everyone else who wants to do the same thing.
First of all, i would start with a "with" statement as it ensures the proper open/close of the file.
It should look something like this:
with open("filename.txt", "r+") as f:
contents = [x.strip() for x in f.readlines()]
If you want to convert those strings (every item in the contents list is a string) in integer or float you can do the following:
contents = [float(contents[i]) for i in range(len(contents))]
Use int
instead of float
if you want to convert to integer.
It's my first answer in SO, so sorry if it's not in the proper formatting.
I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session.
session_unset();
session_destroy();
I noticed some issues with this that might be useful for someone just starting, or a somewhat inexperienced user, to know. First...
CD /D "C:\Documents and Settings\%username%\Start Menu\Programs\"
two things one is that a /D after the CD may prove to be useful in making sure the directory is changed but it's not really necessary, second, if you are going to pass this from user to user you have to add, instead of your name, the code %username%, this makes the code usable on any computer, as long as they have your setup.exe file in the same location as you do on your computer. of course making sure of that is more difficult. also...
start \\filer\repo\lab\"software"\"myapp"\setup.exe
the start code here, can be set up like that, but the correct syntax is
start "\\filter\repo\lab\software\myapp\" setup.exe
This will run: setup.exe, located in: \filter\repo\lab...etc.\
what about this?
top -c -p <PID>
To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"
SELECT news.id, users.username, news.title, news.date,
news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
The only way I've figured out how to do this is to have two properties for my class. One as the boolean for the programming API which is not included in the mapping. It's getter and setter reference a private char variable which is Y/N. I then have another protected property which is included in the hibernate mapping and it's getters and setters reference the private char variable directly.
EDIT: As has been pointed out there are other solutions that are directly built into Hibernate. I'm leaving this answer because it can work in situations where you're working with a legacy field that doesn't play nice with the built in options. On top of that there are no serious negative consequences to this approach.
It's a C trigraph. ??!
is |
, so ??!??!
is the operator ||
This Facebook page has a simple tool to create various share buttons.
For example, this is some output I got:
<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v8.0" nonce="dilSYGI6"></script>
<div class="fb-share-button" data-href="https://www.mocacleveland.org/exhibitions/lee-mingwei-you-are-not-stranger" data-layout="button" data-size="small">
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.mocacleveland.org%2Fexhibitions%2Flee-mingwei-you-are-not-stranger&src=sdkpreparse" class="fb-xfbml-parse-ignore">Share</a>
</div>
I had an issue with R 2.15.3 whereby while trying to create a tree structure recursively on a shared network drive I would get a permission error.
To get around this oddity I manually create the structure;
mkdirs <- function(fp) {
if(!file.exists(fp)) {
mkdirs(dirname(fp))
dir.create(fp)
}
}
mkdirs("H:/foo/bar")
My solution:
UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, myDomain), IdentityType.SamAccountName, myUser);
List<string> UserADGroups = new List<string>();
foreach (GroupPrincipal group in user.GetGroups())
{
UserADGroups.Add(group.ToString());
}
If you get this compilation error, it means that you have not included the servlet jar in the classpath. The correct way to include this jar is to add the Server Runtime jar to your eclipse project. You should follow the steps below to address this issue: You can download the servlet-api.jar from here http://www.java2s.com/Code/Jar/s/Downloadservletapijar.htm
Save it in directory. Right click on project -> go to properties->Buildpath and follow the steps.
_x000D_
Note: The jar which are shown in the screen are not correct jar.
you can follow the step to configure.
You can use array_walk_recursive()
to get a general-case solution for your problem (the one when each inner array can possibly have unique keys).
$final = array();
array_walk_recursive($input, function($item, $key) use (&$final){
$final[$key] = isset($final[$key]) ? $item + $final[$key] : $item;
});
Example with array_walk_recursive()
for the general case
Also, since PHP 5.5 you can use the array_column()
function to achieve the result you want for the exact key, [gozhi]
, for example :
array_sum(array_column($input, 'gozhi'));
Example with array_column()
for the specified key
If you want to get the total sum of all inner arrays with the same keys (the desired result that you've posted), you can do something like this (bearing in mind that the first inner array must have the same structure as the others) :
$final = array_shift($input);
foreach ($final as $key => &$value){
$value += array_sum(array_column($input, $key));
}
unset($value);
Example with array_column()
in case all inner arrays have the same keys
If you want a general-case solution using array_column()
then at first you may consider to get all unique keys , and then get the sum for each key :
$final = array();
foreach($input as $value)
$final = array_merge($final, $value);
foreach($final as $key => &$value)
$value = array_sum(array_column($input, $key));
unset($value);
Using changeit for the password is important too.
This command finally worked for me(with jetty):
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass changeit -validity 360 -keysize 2048
install mbstring and restart your apache:
sudo apt-get install php-mbstring
sudo service apache restart
then remove ; from your php.ini file:
;extension=php_mbstring.dll
to
extension=php_mbstring.dll
If it still doesn't work..remove your php setup, without removing the databases from your phpmyadmin. Reinstall it.
NB: * if you want to remove all, all mention the one you need to.
sudo apt-get remove php*
Then install the php and modules of the php version that you need. here, php 7.1:
sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-fpm php7.1-curl php7.1-gd php7.1-bz2 php7.1-mcrypt php7.1-json php7.1-tidy php7.1-mbstring php-redis php-memcached
restart your apache and check the php version.
sudo service apache restart
php -v
when all this is done, execute the following command to enable mbstring forcefully and restart your apache.
sudo phpenmod mbstring
sudo service apache restart
Hope it helps. It did to me :)
The #!
line tells the kernel (specifically, the implementation of the execve
system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46
(^?ELF) that identifies them as such.
You can put an absolute path to any program you want after the #!
, as long as that program is not itself a #!
script. The kernel rewrites an invocation of
./script arg1 arg2 arg3 ...
where ./script
starts with, say, #! /usr/bin/perl
, as if the command line had actually been
/usr/bin/perl ./script arg1 arg2 arg3
Or, as you have seen, you can use #! /bin/sh
to write a script intended to be interpreted by sh
.
The #!
line is only processed if you directly invoke the script (./script
on the command line); the file must also be executable (chmod +x script
). If you do sh ./script
the #!
line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/*
-- you will discover that a great many stock programs are in fact using this feature.)
Here are some rules for using this feature:
#!
must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #!
script.#!
must be an absolute path (starts with /
). It cannot contain space, tab, or newline characters.#!
and the /
. Do not put more than one space there.#!
line, they will not be expanded.#! /usr/bin/awk -f
), sometimes it's just useful (#! /usr/bin/perl -Tw
). Unfortunately, you cannot put two or more arguments after the absolute path.#! /usr/bin/env interpreter
instead of #! /absolute/path/to/interpreter
. This is almost always a mistake. It makes your program's behavior depend on the $PATH
variable of the user who invokes the script. And not all systems have env
in the first place.setuid
or setgid
privileges can't use #!
; they have to be compiled to machine code. (If you don't know what setuid
is, don't worry about this.)Regarding csh
, it relates to sh
roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh
have caught up) a number of advantages over sh
for interactive usage, but using it (or its descendant tcsh
) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh
. If you are using a csh
relative as your login shell, switch to bash
or zsh
, so that the interactive command language will be the same as the scripting language you're learning.
This worked for me -
HTML -
<div id="sideNote" class="col-sm-3" style="float:right;">
</div>
<div class="footer-wrap">
<div id="footer-div">
</div>
</div>
CSS -
#sideNote{right:0; margin-top:10px; position:fixed; bottom:0; margin-bottom:5px;}
#footer-div{margin:0 auto; text-align:center; min-height:300px; margin-top:100px; padding:100px 50px;}
JQuery -
function isVisible(elment) {
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elment).offset().top;
return y <= (vpH + st);
}
function setSideNotePos(){
$(window).scroll(function() {
if (isVisible($('.footer-wrap'))) {
$('#sideNote').css('position','absolute');
$('#sideNote').css('top',$('.footer-wrap').offset().top - $('#sideNote').outerHeight() - 100);
} else {
$('#sideNote').css('position','fixed');
$('#sideNote').css('top','auto');
}
});
}
Now call this function like this -
$(document).ready(function() {
setSideNotePos();
});
PS - The Jquery functions are copied from an answer to another similar question on stackoverflow, but it wasn't working for me fully. So I modified it to these functions, as they are shown here. I think the position etc attributes to your divs will depend on how the divs are structured, who their parents and siblings are.
The above function works when both sideNote and footer-wraps are direct siblings.
Do you mean finding a stack trace of the thrown exception location? That's either Debug/Exceptions, or better - Ctrl-Alt-E. Set filters for the exceptions you want to break on.
There's even a way to reconstruct the thrower stack after the exception was caught, but it's really unpleasant. Much, much easier to set a break on the throw.
def check_availability(element, collection: iter):
return element in collection
Usage
check_availability('a', [1,2,3,4,'a','b','c'])
I believe this is the fastest way to know if a chosen value is in an array.
You did not do anything wrong here, it will any other thing that is overriding the image size.
You can check this working fiddle.
And in this fiddle I have alter the image size using %
, and it is working.
Also try using this code:
<img src="image.jpg" style="width: 50%; height: 50%"/>?
Here is the example fiddle.
You can also use org.apache.commons.lang.ArrayUtils.isEquals()
require 'date'
current_time = DateTime.now
current_time.strftime "%d/%m/%Y %H:%M"
# => "14/09/2011 17:02"
current_time.next_month.strftime "%d/%m/%Y %H:%M"
# => "14/10/2011 17:02"
Thanks for your answers, @mvp, @xero, I get what I want base on both of your answers.
git log --name-only
or
git log --name-only --oneline
for short.
Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs
module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export
// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()
var str = "This-is-a-news-item-";
while (str.contains("-")) {
str = str.replace("-", ' ');
}
alert(str);
I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.
This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.
There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.
You can create a custom serializer inline in the mixin. Then annotate a field with it. See example below that appends " - something else " to lang field. This is kind of hackish - if your serializer requires something like a repository or anything injected by spring, this is going to be a problem. Probably best to use a custom deserializer/serializer instead of a mixin.
package com.test;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.test.Argument;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//Serialize only fields explicitly mentioned by this mixin.
@JsonAutoDetect(
fieldVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
creatorVisibility = Visibility.NONE
)
@JsonPropertyOrder({"lang", "name", "value"})
public abstract class V2ArgumentMixin {
@JsonProperty("name")
private String name;
@JsonSerialize(using = LangCustomSerializer.class, as=String.class)
@JsonProperty("lang")
private String lang;
@JsonProperty("value")
private Object value;
public static class LangCustomSerializer extends JsonSerializer<String> {
@Override
public void serialize(String value,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
jsonGenerator.writeObject(value.toString() + " - something else");
}
}
}
std::copy (b.begin(), b.end(), std::back_inserter(a));
This can be used in case the items in vector a have no assignment operator (e.g. const member).
In all other cases this solution is ineffiecent compared to the above insert solution.
Here's one approach using a regular expression:
$string =~ s/^\s+|\s+$//g ; # remove both leading and trailing whitespace
Perl 6 will include a trim function:
$string .= trim;
Source: Wikipedia
That's not really a question of aesthetics, but indeed a technical difference. The directory thinking of it is totally correct and pretty much explaining everything. Let's work it out:
You have a fixed directory structure on your web server and only static files like images, html and so on — no server side scripts or whatsoever.
A browser requests /index.htm
, it exists and is delivered to the client. Later you have lots of - let's say - DVD movies reviewed and a html page for each of them in the /dvd/
directory. Now someone requests /dvd/adams_apples.htm
and it is delivered because it is there.
At some day, someone just requests /dvd/
- which is a directory and the server is trying to figure out what to deliver. Besides access restrictions and so on there are two possibilities: Show the user the directory content (I bet you already have seen this somewhere) or show a default file (in Apache it is: DirectoryIndex: sets the file that Apache will serve if a directory is requested.
)
So far so good, this is the expected case. It already shows the difference in handling, so let's get into it:
(Which is by the way completely understandable.) So, you did something entirely wrong and instead of uploading /dvd/the_big_lebowski.htm
you uploaded that file as dvd
(with no extension) to /
.
Someone bookmarked your /dvd/
directory listing (of course you didn't want to create and always update that nifty index.htm
) and is visiting your web-site. Directory content is delivered - all fine.
Someone heard of your list and is typing /dvd
. And now it is screwed. Instead of your DVD directory listing the server finds a file with that name and is delivering your Big Lebowski file.
So, you delete that file and tell the guy to reload the page. Your server looks for the /dvd
file, but it is gone. Most servers will then notice that there is a directory with that name and tell the client that what it was looking for is indeed somewhere else. The response will most likely be be:
Status Code:301 Moved Permanently
with Location: http://[...]/dvd/
So, totally ignoring what you think about directories or files, the server only can handle such stuff and - unless told differently - decides for you about the meaning of "slash or not".
Finally after receiving this response, the client loads /dvd/
and everything is fine.
Is it fine? No.
You have some dynamic page where everything is passed to /index.php
and gets processed. Everything worked quite good until now, but that entire thing starts to feel slower and you investigate.
Soon, you'll notice that /dvd/list
is doing exactly the same: Redirecting to /dvd/list/
which is then internally translated into index.php?controller=dvd&action=list
. One additional request - but even worse! customer/login
redirects to customer/login/
which in turn redirects to the HTTPS URL of customer/login/
. You end up having tons of unnecessary HTTP redirects (= additional requests) that make the user experience slower.
Most likely you have a default directory index here, too: index.php?controller=dvd
with no action
simply internally loads index.php?controller=dvd&action=list
.
If it ends with /
it can never be a file. No server guessing.
Slash or no slash are entirely different meanings. There is a technical/resource difference between "slash or no slash", and you should be aware of it and use it accordingly. Just because the server most likely loads /dvd/index.htm
- or loads the correct script stuff - when you say /dvd
: It does it, but not because you made the right request. Which would have been /dvd/
.
Omitting the slash even if you indeed mean the slashed version gives you an additional HTTP request penalty. Which is always bad (think of mobile latency) and has more weight than a "pretty URL" - especially since crawlers are not as dumb as SEOs believe or want you to believe ;)
Firefox contains a dns cache. To disable the DNS cache:
When disabled, Firefox will use the DNS cache provided by the OS.
string
is a reference type, a class. You can only use Nullable<T>
or the T?
C# syntactic sugar with non-nullable value types such as int
and Guid
.
In particular, as string
is a reference type, an expression of type string
can already be null:
string lookMaNoText = null;
Simple functions to get Date and Time separated and with compatible format with Time and Date HTML input
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
function formatTime(date) {
var hours = new Date().getHours() > 9 ? new Date().getHours() : '0' + new Date().getHours()
var minutes = new Date().getMinutes() > 9 ? new Date().getMinutes() : '0' + new Date().getMinutes()
return hours + ':' + minutes
}
The solution I opted for was to format the date with the mysql query :
String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));
I had the exact same issue.
Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50
String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));
was returning a date formatted as such :
2017-01-01 21:02:50.0
Check out also the --sig-proxy
option:
docker attach --sig-proxy=false 304f5db405ec
Then use CTRL+c to detach
I think you can try this:
<a th:href="${'/category/edit/' + {category.id}}">view</a>
Or if you have "idCategory" this:
<a th:href="${'/category/edit/' + {category.idCategory}}">view</a>
@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical
instead of ==
.
test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")
Or use isTRUE
:
test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")
For use in command line:
for /f "tokens=5" %a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %a
For use in bat-file:
for /f "tokens=5" %%a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %%a
If you assume that 0 is not a valid item in the array then the following code should work:
public static void main( String[] args )
{
int[] theArray = new int[20];
theArray[0] = 1;
theArray[1] = 2;
System.out.println(count(theArray));
}
private static int count(int[] array)
{
int count = 0;
for(int i : array)
{
if(i > 0)
{
count++;
}
}
return count;
}
you can use Android Asset in android studio , and android Asset will give you image in this size as a drawable and the application will automatically use the size based on screen of device or emulate
This twisted async web client goes pretty fast.
#!/usr/bin/python2.7
from twisted.internet import reactor
from twisted.internet.defer import Deferred, DeferredList, DeferredLock
from twisted.internet.defer import inlineCallbacks
from twisted.web.client import Agent, HTTPConnectionPool
from twisted.web.http_headers import Headers
from pprint import pprint
from collections import defaultdict
from urlparse import urlparse
from random import randrange
import fileinput
pool = HTTPConnectionPool(reactor)
pool.maxPersistentPerHost = 16
agent = Agent(reactor, pool)
locks = defaultdict(DeferredLock)
codes = {}
def getLock(url, simultaneous = 1):
return locks[urlparse(url).netloc, randrange(simultaneous)]
@inlineCallbacks
def getMapping(url):
# Limit ourselves to 4 simultaneous connections per host
# Tweak this number, but it should be no larger than pool.maxPersistentPerHost
lock = getLock(url,4)
yield lock.acquire()
try:
resp = yield agent.request('HEAD', url)
codes[url] = resp.code
except Exception as e:
codes[url] = str(e)
finally:
lock.release()
dl = DeferredList(getMapping(url.strip()) for url in fileinput.input())
dl.addCallback(lambda _: reactor.stop())
reactor.run()
pprint(codes)
I'd like to propose
np.min(np.append(np.where(aa>5)[0],np.inf))
This will return the smallest index where the condition is met, while returning infinity if the condition is never met (and where
returns an empty array).
Try std::find
vector<int>::iterator it = std::find(v.begin(), v.end(), 123);
if(it==v.end()){
std::cout<<"Element not found";
}
React.JS People, remember allowFullScreen
and frameBorder="0"
Without camel-case, react strips these tags out!
Basic example. First-half builds the frequency-map, second-half reduces it to a filtered list. Probably not as efficient as Dave's answer, but more versatile (like if you want to detect exactly two etc.)
List<Integer> duplicates = IntStream.of( 1, 2, 3, 2, 1, 2, 3, 4, 2, 2, 2 )
.boxed()
.collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) )
.entrySet()
.stream()
.filter( p -> p.getValue() > 1 )
.map( Map.Entry::getKey )
.collect( Collectors.toList() );
Personally I would go with:
DataTable tbl = Gridview1.DataSource as DataTable;
This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.
Supporting Documentation: MSDN Documentation on "as"
I used this solution: in TableRow
, I created for every cell LinearLayout
with vertical line and actual cell in it, and after every TableRow
, I added a horizontal line.
Look at the code below:
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:shrinkColumns="1">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_weight="1">
<View
android:layout_height="match_parent"
android:layout_width="1dp"
android:background="#BDCAD2"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
</TableRow>
<View
android:layout_height="1dip"
android:background="#BDCAD2" />
<!-- More TableRows -->
</TableLayout>
Hope it will help.
java.exe
is the console app while javaw.exe
is windows app (console-less). You can't have Console
with javaw.exe
.
The problem is that an isin does not identify the exchange, only an issuer.
Let's say your isin is US4592001014
(IBM), one way to do it would be:
get the ticker (in A1):
=BDP("US4592001014 ISIN", "TICKER") => IBM
get a proper symbol (in A2)
=BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
where XX
depends on your terminal settings, which you can check on CNDF <Go>
.
get the main exchange composite ticker, or whatever suits your need (in A3):
=BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
and finally:
=BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
After checking catalina.sh (for windows use the .bat versions of everything mentioned below)
# Do not set the variables in this script. Instead put them into a script
# setenv.sh in CATALINA_BASE/bin to keep your customizations separate.
Also this
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# Include here and not in JAVA_OPTS all options, that should
# only be used by Tomcat itself, not by the stop process,
# the version command etc.
# Examples are heap size, GC logging, JMX ports etc
So create a setenv.sh under CATALINA_BASE/bin (same dir where the catalina.sh resides). Edit the file and set the arguments to CATALINA_OPTS
For e.g. the file would look like this if you wanted to change the heap size
CATALINA_OPTS=-Xmx512m
Or in your case since you're using windows setenv.bat would be
set CATALINA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
To clear the added options later just delete setenv.bat/sh
wget -r ftp://url
Work perfectly for Redhat and Ubuntu
Explain what video describe to resolve problem
After Changing Password of root (Mysql Account). Accessing to phpmyadmin page will be denied because phpMyAdmin use root/''(blank) as default username/password. To resolve this problem, you need to reconfig phpmyadmin. Edit file config.inc.php in folder %wamp%\apps\phpmyadmin4.1.14 (Not in %wamp%)
$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
If you have more than 1 DB server, add "i++" to file and continue add new config as above
For your design, it is common practice to use divs rather than a table. This way, your layout will be more maintainable and changeable through proper styling. It does take some getting used to, but it will help you a ton in the long run and you will learn a lot about how styling works. However, I will provide you with a solution to the problem at hand.
In your stylesheets you have margins and padding set to 0 pixels. This overrides your align="center"
attribute. I would recommend taking these settings out of your CSS as you don't normally want all of your elements to be affected in this manner. If you already know what's going on in the CSS, and you want to keep it that way, then you have to apply a style to your table to override the previous sets. You could either give the table a class
or you can put the style inline with the HTML. Here are the two options:
With a class:
<table class="centerTable"></table>
In your style.css file you would have something like this:
.centerTable { margin: 0px auto; }
Inline with your HTML:
<table style="margin: 0px auto;"></table>
If you decide to wipe out the margins and padding being set to 0px, then you can keep align="center"
on your <td>
tags for whatever column you wish to align.
I'm aware this question is fairly old by now, and you've most likely fixed it by now, but I'd like to post here as reference for anyone that finds this post while troubleshooting this issue is that this sort of thing won't work if your Anchor tags are in the Index.html. It needs to be in one of the components
If to use disabled
form input elements (like suggested in correct answer
how to disable input) validation for them will be also disabled, take attention for that!
(And if you are using on submit button like [disabled]="!form.valid"
it will exclude your field from validation)
I've always used it on the command line and not as a library, but HTMLDOC gives me excellent results, and it handles at least some CSS (I couldn't easily see how much).
Here's a sample command line
htmldoc --webpage -t pdf --size letter --fontsize 10pt index.html > index.pdf
You can't. That's because that's what browsers were designed to do: Serve content. But you can make it harder to download.
First thing's first, you could disable the contextmenu
event, aka "the right click". That would prevent your regular skiddie from blatantly ripping your video by right clicking and Save As. But then they could just disable JS and get around this or find the video source via the browser's debugger. Plus this is bad UX. There are lots of legitimate things in a context menu than just Save As.
You could also use custom video player libraries. Most of them implement video players that customize the context menu to your liking. So you don't get the default browser context menu. And if ever they do serve a menu item similar to Save As, you can disable it. But again, this is a JS workaround. Weaknesses are similar to the previous option.
Another way to do it is to serve the video using HTTP Live Streaming. What it essentially does is chop up the video into chunks and serve it one after the other. This is how most streaming sites serve video. So even if you manage to Save As, you only save a chunk, not the whole video. It would take a bit more effort to gather all the chunks and stitch them using some dedicated software.
Another technique is to paint <video>
on <canvas>
. In this technique, with a bit of JavaScript, what you see on the page is a <canvas>
element rendering frames from a hidden <video>
. And because it's a <canvas>
, the context menu will use an <img>
's menu, not a <video>
's. You'll get a Save Image As instead of a Save Video As.
You could also use CSRF tokens to your advantage. You'd have your sever send down a token on the page. You then use that token to fetch your video. Your server checks to see if it's a valid token before it serves the video, or get an HTTP 401. The idea is that you can only ever get a video by having a token which you can only ever get if you came from the page, not directly visiting the video url.
At the end of the day, I'd just upload my video to a third-party video site, like YouTube or Vimeo. They have good video management tools, optimizes playback to the device, and they make efforts in preventing their videos from being ripped with zero effort on your end.
The Key Disappears, whether it is numeric or not. Try out the test script below.
<?php
$t = array( 'a', 'b', 'c', 'd' );
foreach($t as $k => $v)
echo($k . ": " . $v . "<br/>");
// Output: 0: a, 1: b, 2: c, 3: d
unset($t[1]);
foreach($t as $k => $v)
echo($k . ": " . $v . "<br/>");
// Output: 0: a, 2: c, 3: d
?>
It is Vb.Net version:
Public Class Test
Public Property id As Integer
Public Property name As String
Public Property address As String
Public Property createdDate As Date
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim x As Date = Now
Debug.WriteLine("Begin: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)
Dim dt As New DataTable
dt.Columns.Add("id")
dt.Columns.Add("name")
dt.Columns.Add("address")
dt.Columns.Add("createdDate")
For i As Integer = 0 To 100000
dt.Rows.Add(i, "name - " & i, "address - " & i, DateAdd(DateInterval.Second, i, Now))
Next
Debug.WriteLine("Datatable created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)
Dim items As IList(Of Test) = dt.AsEnumerable().[Select](Function(row) New _
Test With {
.id = row.Field(Of String)("id"),
.name = row.Field(Of String)("name"),
.address = row.Field(Of String)("address"),
.createdDate = row.Field(Of String)("createdDate")
}).ToList()
Debug.WriteLine("List created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)
Debug.WriteLine("Complated")
End Sub
Duplicate name Classes
like
class BackGroundTask extends AsyncTask<String, Void, Void> {
and
class BackgroundTask extends AsyncTask<String, Void, Void> {
Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes
https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task
If you're working with PHP, check out the Pear packages at pear.php.net and see if you find anything useful to you. I've used the RSS packages effectively and it saves a lot of time, provided you can follow how they implement their code via their examples.
Specifically take a look at Sax 3 and see if it will work for your needs. Sax 3 is no longer updated but it might be sufficient.
Some of what is explained above is meant only for placing an SMS in a 'ready to launch' state.
as Senthil Mg said you can use sms manager to send the sms directly but SMSManager
has been moved to android.telephony.SmsManager
I know it's not a lot of more info, but it might help someone some day.
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
Another way to achieve the same goal: flex boxes. Make the container a column flex box, and then you have all freedom to allow some elements to have fixed-size (default behavior) or to fill-up/shrink-down to the container space (with flex-grow:1 and flex-shrink:1).
#wrap {
display:flex;
flex-direction:column;
}
.extendOrShrink {
flex-shrink:1;
flex-grow:1;
overflow:auto;
}
See https://jsfiddle.net/2Lmodwxk/ (try to extend or reduce the window to notice the effect)
Note: you may also use the shorthand property:
flex:1 1 auto;
Use Comparable
if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this.
Use Comparator
if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.
Don't grant control to the user, it's totally unnecessay. Select permission on the database is enough. After you have created the login and the user on master (see above answers):
use YourDatabase
go
create user [YourDomain\YourUser] for login [YourDomain\YourUser] with default_schema=[dbo]
go
alter role [db_datareader] add member [YourDomain\YourUser]
go
I found that by shutting down a Console and a running Simulator allowed XCode to see my iPhone again. I'd make sure other related programs aren't running if you don't need them.
Delete locally:
To delete a local branch, you can use:
git branch -d <branch_name>
To delete a branch forcibly, use -D
instead of -d
.
git branch -D <branch_name>
Delete remotely:
There are two options:
git push origin :branchname
git push origin --delete branchname
I would suggest you use the second way as it is more intuitive.
I had let this go for a good while but revisited it later. Since this question is viewed regularly. This is eventually what I ended up using that worked for me.
define("DOC_ROOT","/path/to/html");
//username and password of account
$username = trim($values["email"]);
$password = trim($values["password"]);
//set the directory for the cookie using defined document root var
$path = DOC_ROOT."/ctemp";
//build a unique path with every request to store. the info per user with custom func. I used this function to build unique paths based on member ID, that was for my use case. It can be a regular dir.
//$path = build_unique_path($path); // this was for my use case
//login form action url
$url="https://www.example.com/login/action";
$postinfo = "email=".$username."&password=".$password;
$cookie_file_path = $path."/cookie.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
//set the cookie the site has for certain features, this is optional
curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
curl_exec($ch);
//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/page/");
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);
Update: This code was never meant to be a copy and paste. It was to show how I used it for my specific use case. You should adapt it to your code as needed. Such as directories, vars etc
That's the reason not to put configuration into webapp
.
As far as I know, there are no good ways to access files in webapp
folder from the unit tests. You can put your configuration into src/main/resources
instead, so that you can access it from your unit tests (as described in the docs), as well as from the webapp (using classpath:
prefix in contextConfigLocation
).
See also:
Rising to @Ankan-Zerob's challenge, this is my estimate of the maximum length which can be stored in each text type measured in words:
Type | Bytes | English words | Multi-byte words
-----------+---------------+---------------+-----------------
TINYTEXT | 255 | ±44 | ±23
TEXT | 65,535 | ±11,000 | ±5,900
MEDIUMTEXT | 16,777,215 | ±2,800,000 | ±1,500,000
LONGTEXT | 4,294,967,295 | ±740,000,000 | ±380,000,000
In English, 4.8 letters per word is probably a good average (eg norvig.com/mayzner.html), though word lengths will vary according to domain (e.g. spoken language vs. academic papers), so there's no point being too precise. English is mostly single-byte ASCII characters, with very occasional multi-byte characters, so close to one-byte-per-letter. An extra character has to be allowed for inter-word spaces, so I've rounded down from 5.8 bytes per word. Languages with lots of accents such as say Polish would store slightly fewer words, as would e.g. German with longer words.
Languages requiring multi-byte characters such as Greek, Arabic, Hebrew, Hindi, Thai, etc, etc typically require two bytes per character in UTF-8. Guessing wildly at 5 letters per word, I've rounded down from 11 bytes per word.
CJK scripts (Hanzi, Kanji, Hiragana, Katakana, etc) I know nothing of; I believe characters mostly require 3 bytes in UTF-8, and (with massive simplification) they might be considered to use around 2 characters per word, so they would be somewhere between the other two. (CJK scripts are likely to require less storage using UTF-16, depending).
This is of course ignoring storage overheads etc.
Be consistent! JOIN-ing a VARCHAR to NVARCHAR has a big performance hit.
To define Optional
Protocol
in swift you should use @objc
keyword before Protocol
declaration and attribute
/method
declaration inside that protocol.
Below is a sample of Optional Property of a protocol.
@objc protocol Protocol {
@objc optional var name:String?
}
class MyClass: Protocol {
// No error
}
ng-bind-html-unsafe
only renders the content as HTML. It doesn't bind Angular scope to the resulted DOM. You have to use $compile
service for that purpose. I created this plunker to demonstrate how to use $compile
to create a directive rendering dynamic HTML entered by users and binding to the controller's scope. The source is posted below.
demo.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="[email protected]" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Compile dynamic HTML</h1>
<div ng-controller="MyController">
<textarea ng-model="html"></textarea>
<div dynamic="html"></div>
</div>
</body>
</html>
script.js
var app = angular.module('app', []);
app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
function MyController($scope) {
$scope.click = function(arg) {
alert('Clicked ' + arg);
}
$scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}
You can use:
f.Controls[name];
Where f
is your form variable. That gives you the control with name name
.
As described by the link I've given in comment, this
$('p[MyTag]').each(function(index) {
document.write(index + ': ' + $(this).text() + "<br>");});
works (playable example).
Try xcorr
, it's a built-in function in MATLAB for cross-correlation:
c = xcorr(A_1, A_2);
However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef
command instead.
So I think the answer is simpler than many misleading answers above.
To start an existing container which is stopped
docker start <container-name/ID>
To stop a running container
docker stop <container-name/ID>
Then to login to the interactive shell of a container
docker exec -it <container-name/ID> bash
To start an existing container and attach to it in one command
docker start -ai <container-name/ID>
Beware, this will stop the container on exit. But in general, you need to start the container, attach and stop it after you are done.
Since you are the only user:
git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}
( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )
Without doing any changes to your local repo, you can also do something like:
git push -f origin <sha_of_previous_commit>:master
Generally, in published repos, it is safer to do git revert
and then git push