either (plain js)
this.checked = false;
or (jQuery)
$(this).prop('checked', false);
// Note that the pre-jQuery 1.6 idiom was
// $(this).attr('checked', false);
See jQuery prop() help page for an explanation on the difference between attr() and prop() and why prop() is now preferable.
prop() was introduced with jQuery 1.6 in May 2011.
I recommend using DateTime objects instead of strings, because you cannot easily compare strings, which is required for sorting. You also get additional advantages for working with dates.
Once you have the DateTime objects, sorting is quite easy:
usort($array, function($a, $b) {
return ($a['date'] < $b['date']) ? -1 : 1;
});
where are you trying to return the value? to console in dev tools is better for debugging
<script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
if(ask==false){
return false;
} else {
return true;
}
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>
I also was having this error when trying to clone a repository from Github on a Windows Subsystem from Linux console:
fatal: unable to access 'http://github.com/docker/getting-started.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
The solution from @VonC on this thread didn't work for me.
The solution from this Fabian Lee's article solved it for me:
openssl s_client -showcerts -servername github.com -connect github.com:443 </dev/null 2>/dev/null | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p' > github-com.pem
cat github-com.pem | sudo tee -a /etc/ssl/certs/ca-certificates.crt
npm install -g npm-install-peers
it will add all the missing peers and remove all the error
I shear the point made by user2237829. The table names in the create_tables script used a double underscore while the table names in the xampp example uses a single underscore.
In my case, adding the dll as a reference gave the type or namespace name could not be found
error. However, copying and pasting the dll file directly in bin folder resolved the error.
No idea why this worked.
You may have your answer however till this day it's difficult to judge whether to put null=True or blank=True or both to a field. I personally think it's pretty useless and confusing to provide so many options to developers. Let the handle the nulls or blanks however they want.
I follow this table, from Two Scoops of Django:
For me the cause was incorrect url for jcenter
. To solve it I simply changed url for app and proect level build.gradle
from
jcenter { url "http://jcenter.bintray.com/"}
to
jcenter()
I personally prefer Confucious.
It is nice, as it doesn't require any external dependencies, it's tiny - only 16K, and automatically loads your ini file on initialization. E.g.
Configurable config = Configuration.getInstance();
String host = config.getStringValue("host");
int port = config.getIntValue("port");
new Connection(host, port);
I think the strictSSL: false
should (should have worked, even in 2013) work. So in short are three possible ways:
request
object: const myRequest = require('request').defaults({strictSSL: false})
node-request
internally also allow a request
-object to be injected, so you can make them use your modified instance.NODE_TLS_REJECT_UNAUTHORIZED=0
for the Node.js process.This can also happen if data model is out of date.
Hopefully this will save someone else frustration :)
You can use this but there remains a security issue
<script type="text/javascript">
function fnc1()
{
var a=window.location.href;
username="p";
password=1234;
window.open(a+'?username='+username+'&password='+password,"");
}
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext" />
If you just want to inspect the variables manually to help debug, just fire up the debugger:
debugger;
Straight into the browser console.
Here is Microsoft Suggestion for this http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800
On the gridview add a command button and convert it into a template, then give it a commandname in this case "AddToCart" and also add CommandArgument "<%# ((GridViewRow) Container).RowIndex %>"
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
Then for create on the RowCommand event of the gridview identify when the "AddToCart" command is triggered, and do whatever you want from there
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here to add the item to the shopping cart.
}
}
**One mistake I was making is that I wanted to add the actions on my template button instead of doing it directly on the RowCommand Event.
Also you can define ids.xml
in res/values
. You can see an exact example in android's sample code.
samples/ApiDemos/src/com/example/android/apis/RadioGroup1.java
samples/ApiDemp/res/values/ids.xml
tl;dr: JavaScript doesn't support associative arrays, therefore neither does JSON.
After all, it's JSON, not JSAAN. :)
So PHP has to convert your array into an object in order to encode into JSON.
HTTPie is a recommended alternative to curl
because you can do just
$ http POST http://example.com/some/endpoint name=value name1=value1
It speaks JSON by default and will handle both setting the necessary header for you as well encoding data as valid JSON. There is also:
Some-Header:value
for headers, and
name==value
for query string parameters. If you have a large chunk of data, you can also read it from a file have it be JSON encoded:
[email protected]
Try adding the profile
attribute to your head
tag and use "image/x-icon"
for the type
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">
If the above code doesn't work, try using the full icon path for the href
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">
just run git log origin/$BRANCH_NAME
Not answering for browser compatibility but to also mention the new Grid and the not so new Flexbox feature.
Grid
From: Mozilla - Grid Documentation - Align Div Vertically
Browser Support: Grid Browser Support
CSS:
.wrapper {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
grid-auto-rows: 200px;
grid-template-areas:
". a a ."
". a a .";
}
.item1 {
grid-area: a;
align-self: center;
justify-self: center;
}
HTML:
<div class="wrapper">
<div class="item1">Item 1</div>
</div>
Flexbox
Browser Support: Flexbox Browser Support
CSS:
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;
Change the lines
if(nodeValue!=null)
fop.write(nodeValue.getBytes());
fop.flush();
to
if(nodeValue!=null) {
fop.write(nodeValue.getBytes());
fop.write(System.getProperty("line.separator").getBytes());
}
fop.flush();
Update to address your edit:
In order to write each word on a different line, you need to split up your input string and then write each word separately.
private static void GetText(String nodeValue) throws IOException {
if(!file3.exists()) {
file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null)
for(final String s : nodeValue.split(" ")){
fop.write(s.getBytes());
fop.write(System.getProperty("line.separator").getBytes());
}
}
fop.flush();
fop.close();
}
In my case I had multiple elements to hide on document.ready. This is the function (filter) that worked for me so far:
$('[name="_invisibleIfEmpty"]').filter(function () {
return $.trim($(this).html()).length == 0;
}).hide();
or .remove() rather than .hide(), whatever you prefer.
FYI: This, in particular, is the solution I am using to hide annoying empty table cells in SharePoint (in addition with this condition "|| $(this).children("menu").length".
For performance, especially when you're iterating over a large range, xrange()
is usually better. However, there are still a few cases why you might prefer range()
:
In python 3, range()
does what xrange()
used to do and xrange()
does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use xrange()
.
range()
can actually be faster in some cases - eg. if iterating over the same sequence multiple times. xrange()
has to reconstruct the integer object every time, but range()
will have real integer objects. (It will always perform worse in terms of memory however)
xrange()
isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.
[Edit] There are a couple of posts mentioning how range()
will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of range()
and xrange()
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@
for x in range(20):
- a=range(20)
+ a=list(range(20))
b=list(range(20))
c=[x for x in range(20)]
d=(x for x in range(20))
- e=xrange(20)
+ e=range(20)
As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.
There is no standardized name.
Libraries like jquery and lodash refer it as kebab-case
. So does Vuejs javascript framework. However, I am not sure whether it's safe to declare that it's referred as kebab-case
in javascript world.
For the earlier versions:
history.push('/path', yourData);
And get the data in the related component just like below:
this.props.location.state // it is equal to yourData
For the newer versions the above way works well but there is a new way:
history.push({
pathname: '/path',
customNameData: yourData,
});
And get the data in the related component just like below:
this.props.location.customNameData // it is equal to yourData
Hint: the state
key name was used in the earlier versions and for newer versions, you can use your custom name to pass data and using state
name is not essential.
Use the built in type cast functionality, simply type
$realArray = (array)$stdClass;
Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.
*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.
I used this code to write directly to the event log Application:
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1);
}
As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):
Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
You got the order of the arguments to mysqli_select_db()
backwards. And mysqli_error()
requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.
Note also that with mysqli you can specify the DB in mysqli_connect()
:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error();
}
You must use mysqli_connect_error()
, not mysqli_error()
, to get the error from mysqli_connect()
, since the latter requires you to supply a valid connection.
Check out this jsfiddle.
// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
})()
The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup()
which I think makes it more convenient for usability.
Solutions suggested above will work only if data is aligned..
See solution in the link using PythonScript Notepad++ plugin, It Works great!
String strJson="{\"Employee\":
[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},
{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},
{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";
This is an example of a JSON string with Employee
as object, then multiple strings and values in an array as a reference to @cregox
...
A bit complicated but can explain a lot in a single JSON string.
To bind the data to ComboBox
List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });
cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";
cbotest.SelectedValue = "2";
ComboData
looks like:
public class ComboData
{
public int Id { get; set; }
public string Value { get; set; }
}
(note that Id
and Value
have to be properties, not class fields)
I did this way:
Add this method to check whether email address is valid or not:
private boolean isValidEmailId(String email){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
}
Now check with String of EditText:
if(isValidEmailId(edtEmailId.getText().toString().trim())){
Toast.makeText(getApplicationContext(), "Valid Email Address.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "InValid Email Address.", Toast.LENGTH_SHORT).show();
}
Done
Use doc.childNodes
to iterate through each span
, and then filter the one whose className
equals 4
:
var doc = document.getElementById("test");
var notes = null;
for (var i = 0; i < doc.childNodes.length; i++) {
if (doc.childNodes[i].className == "4") {
notes = doc.childNodes[i];
break;
}
}
?
Because anything else is part of the implementation, and interfaces cannot contain any implementation.
File from = new File(Environment.getExternalStorageDirectory().getAbsolutePath().getAbsolutePath()+"/kaic1/imagem.jpg");
File to = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kaic2/imagem.jpg");
from.renameTo(to);
As other answers have pointed, on UNIX systems the numbers represent CPU load averages over 1/5/15 minute periods. But on Linux (and consequently Android), what it represents is something different.
After a kernel patch dating back to 1993 (a great in-depth article on the subject), in Linux the load average numbers no longer strictly represent the CPU load: as the calculation accounts not only for CPU bound processes, but also for processes in uninterruptible wait state - the original goal was to account for I/O bound processes this way, to represent more of a "system load" than just CPU load. The issue is that since 1993 the usage of uninterruptible state has grown in Linux kernel, and it no longer typically represents an I/O bound process. The problem is further exacerbated by some Linux devs using uninterruptible waits as an easy wait to avoid accommodating signals in their implementations. As a result, in Linux (and Android) we can see skewed high load average numbers that do not objectively represent the real load. There are Android user reports about unreasonable high load averages contrasting low CPU utilization. For example, my old Android phone (with 2 CPU cores) normally shown average load of ~12 even when the system and CPUs were idle. Hence, average load numbers in Linux (Android) does not turn out to be a reliable performance metric.
If you want to use text word wrap in your Visual Studio Code editor, you have to press button Alt + Z for text word wrap. Its word wrap is toggled between text wrap or unwrap.
It is better to do this on the design surface (Visual Studio 2012 is shown but can be done in other versions) first before calculating any maths when editing an SSRS document.
Below the following numbers in red circles that map to these following steps:
page
which is larger than the actual controls; hence the ghost area being printed. Also in some circumstances one can just change a property of the report page by setting ConsumeContainerWhitespace
to true
to automatically consume the spaces.
After running the repair I was able to start the mongod proccessor but as root, which meant that service mongod start
would not work. To repair this issue, I needed to make sure that all the files inside the database folder were owned and grouped to mongod. I did this by the following:
/var/lib/mongo
I went to cd /var/lib
ls -l mongo
chown -R mongod:mongod mongo
. This changed the owner and group of every file in the folder to mongod. (If using the mongodb package, chown -R mongodb:mongodb mongodb
)I hope this helps someone else in the future.
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
}
There's several things you can improve upon here. To start, there's no reason to use an <a>
(anchor) tag since you don't have a link.
Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.
I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?
== EDIT ==
The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.
It is allow as TD can contain inline- AND block-elements.
Here you can find it in the reference: http://xhtml.com/en/xhtml/reference/td/#td-contains
I'm only familiar with Mongo and Couch, but there's also one named Persistence.
You can simply traverse through the object and return if a match is found.
Here is the code:
returnKeyforValue : function() {
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
for (key in JsonObj) {
if(JsonObj[key] === "Keyvalue") {
return key;
}
}
}
You need to search for OWNER_NAME.
cat -v dumpfile.dmp | grep -o '<OWNER_NAME>.*</OWNER_NAME>' | uniq -u
cat -v turn the dumpfile into visible text.
grep -o shows only the match so we don't see really long lines
uniq -u removes duplicate lines so you see less output.
This works pretty well, even on large dump files, and could be tweaked for usage in a script.
For those arriving here after updating phpunit to version 6 or greater released on 2017-02-03 (e.g. with composer), you may be getting this error because phpunit code is now namespaced (check changelog).
You will need to refactor things like \PHPUnit_Framework_TestCase
to \PHPUnit\Framework\TestCase
Within the view you want to bring to the top... (in swift)
superview?.bringSubviewToFront(self)
i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is,
imho, a killer feature.
Also the code can be kept cleaner.
$(function(){
var tablerows = new Array();
$.each(['result1', 'result2', 'result3'], function( index, value ) {
tablerows.push('<tr><td>' + value + '</td></tr>');
});
var table = $('<table/>', {
html: tablerows
});
var div = $('<div/>', {
id: 'here_table',
html: table
});
$('body').append(div);
});
Addon: passing more than one "html" tag you've to use array notation like: e.g.
var div = $('<div/>', {
id: 'here_table',
html: [ div1, div2, table ]
});
best Rgds.
Franz
You use goto in C for similar error handling situations.
That is the closest equivalent of exceptions you can get in C.
Why nobody suggested this, its simple.
Path.GetFileName(Application.ExecutablePath)
I prefer to use regular expressions:
Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");
According to this bug, the issue was fixed in Workbench 5.2.38 for some people and perhaps 5.2.39 for others—can you upgrade to the latest version (5.2.40)?
Alternatively, it is possible to workaround with:
SELECT *,'' FROM my_table
A little late but I did run across this thread when trying out solutions for myself. Assuming you're using modern browsers nowadays, I came up with a solution using CSS calc() to help guarantee widths met up.
.table-fixed-left table,_x000D_
.table-fixed-right table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
.table-fixed-right td,_x000D_
.table-fixed-right th,_x000D_
.table-fixed-left td,_x000D_
.table-fixed-left th {_x000D_
border: 1px solid #ddd;_x000D_
padding: 5px 5px;_x000D_
}_x000D_
.table-fixed-left {_x000D_
width: 120px;_x000D_
float: left;_x000D_
position: fixed;_x000D_
overflow-x: scroll;_x000D_
white-space: nowrap;_x000D_
text-align: left;_x000D_
border: 1px solid #ddd;_x000D_
z-index: 2;_x000D_
}_x000D_
.table-fixed-right {_x000D_
width: calc(100% - 145px);_x000D_
right: 15px;_x000D_
position: fixed;_x000D_
overflow-x: scroll;_x000D_
border: 1px solid #ddd;_x000D_
white-space: nowrap;_x000D_
}_x000D_
.table-fixed-right td,_x000D_
.table-fixed-right th {_x000D_
padding: 5px 10px;_x000D_
}
_x000D_
<div class="table-fixed-left">_x000D_
<table>_x000D_
<tr>_x000D_
<th>Normal Header</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Header with extra line_x000D_
<br/> </th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Normal Header</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Normal with extra line_x000D_
<br/> </th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Normal Header</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Normal Header</th>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<div class="table-fixed-right">_x000D_
<table>_x000D_
<tr>_x000D_
<th>Header</th>_x000D_
<th>Another header</th>_x000D_
<th>Header</th>_x000D_
<th>Header really really really really long</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Info Long</td>_x000D_
<td>Info_x000D_
<br/>with second line</td>_x000D_
<td>Info_x000D_
<br/>with second line</td>_x000D_
<td>Info Long</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Info Long</td>_x000D_
<td>Info Long</td>_x000D_
<td>Info Long</td>_x000D_
<td>Info Long</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Info_x000D_
<br/>with second line</td>_x000D_
<td>Info_x000D_
<br/>with second line</td>_x000D_
<td>Info_x000D_
<br/>with second line</td>_x000D_
<td>Info</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Info</td>_x000D_
<td>Info</td>_x000D_
<td>Info</td>_x000D_
<td>Info</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Info</td>_x000D_
<td>Info</td>_x000D_
<td>Info</td>_x000D_
<td>Info</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
Hope this helps someone!
It might be worth mentioning that you can also create a .dockerignore
file, to exclude the files that you don't want to copy:
https://docs.docker.com/engine/reference/builder/#dockerignore-file
Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.
It’s not really answering your question, but just on this part:
[3] requires both an id and a name... having both is somewhat redundant
You’ll most likely need to have an id
attribute on each form field anyway, so that you can associate its <label>
element with it, like this:
<label for="foo">Foo:</label>
<input type="text" name="foo" id="foo" />
This is required for accessibility (i.e. if you don’t associate form labels and controls, why do you hate blind people so much?).
It is somewhat redundant, although less so when you have checkboxes/radio buttons, where several of them can share a name
. Ultimately, id
and name
are for different purposes, even if both are often set to the same value.
Depends on what you have. If your svg icon is just a path, then it's easy enough to add that glyph by just copying the 'd' attribute to a new <glyph> element. However, the path needs to be scaled to the font's coordinate system (the EM-square, which typically is [0,0,2048,2048] - the standard for Truetype fonts) and aligned with the baseline you want.
Not all browsers support svg fonts however, so you're going to have to convert it to other formats too if you want it to work everywhere.
Fontforge can import svg files (select a glyph slot, File > Import and then select your svg image), and you can then convert to all the relevant font formats (svg, truetype, woff etc).
Do you mean you want Class C to be the base class for A & B in that case.
public abstract class C
{
public abstract void Method1();
public abstract void Method2();
}
public class A : C
{
public override void Method1()
{
throw new NotImplementedException();
}
public override void Method2()
{
throw new NotImplementedException();
}
}
public class B : C
{
public override void Method1()
{
throw new NotImplementedException();
}
public override void Method2()
{
throw new NotImplementedException();
}
}
I haven't tested the email part of this (my test box does not send email) but I think it will work.
<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s
{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>
I think that this is the correct way:
class Game extends Eloquent {
// many more stuff here
// relation without any constraints ...works fine
public function videos() {
return $this->hasMany('Video');
}
// results in a "problem", se examples below
public function available_videos() {
return $this->videos()->where('available','=', 1);
}
}
And then you'll have to
$game = Game::find(1);
var_dump( $game->available_videos()->get() );
You can use "+" for returning extend, instead of extending in place.
l1=range(10)
l1+[11]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
l2=range(10,1,-1)
l1+l2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]
Similarly +=
for in place behavior, but with slight differences from append
& extend
. One of the biggest differences of +=
from append
and extend
is when it is used in function scopes, see this blog post.
Or you can:
hadoop fs -rm -r PATH
Hint: if you enter:
hadoop fs -rmr PATH
you would mostly get:Please use 'rm -r' instead.
For all those who are reading this but do not have problem with application.css
and instead with their custom CSS classes e.g. admin.css
, base.css
etc.
Solution is to use as mentioned
bundle exec rake assets:precompile
And in stylesheets references just reference application.css
<%= stylesheet_link_tag "application", :media => "all" %>
Since assets pipeline will precompile all of your stylesheets in application.css. This also happens in development so using any other references is wrong when using assets pipeline.
Another option which doesn't require numpy is:
precision = 2
myRoundedList = [int(elem*(10**precision)+delta)/(10.0**precision) for elem in myList]
# delta=0 for floor
# delta = 0.5 for round
# delta = 1 for ceil
If you don't wish to mess with IFS (perhaps for the code within the loop) this might help.
If know that your string will not have whitespace, you can substitute the ';' with a space and use the for/in construct:
#local str
for str in ${STR//;/ } ; do
echo "+ \"$str\""
done
But if you might have whitespace, then for this approach you will need to use a temp variable to hold the "rest" like this:
#local str rest
rest=$STR
while [ -n "$rest" ] ; do
str=${rest%%;*} # Everything up to the first ';'
# Trim up to the first ';' -- and handle final case, too.
[ "$rest" = "${rest/;/}" ] && rest= || rest=${rest#*;}
echo "+ \"$str\""
done
Based on some of the answers here, I have written a CustomConstructorResolver
for use in a current project, and I thought it might help somebody else.
It supports the following resolution mechanisms, all configurable:
Newtonsoft.Json.JsonConstructorAttribute
.public class CustomConstructorResolver : DefaultContractResolver
{
public string ConstructorAttributeName { get; set; } = "JsonConstructorAttribute";
public bool IgnoreAttributeConstructor { get; set; } = false;
public bool IgnoreSinglePrivateConstructor { get; set; } = false;
public bool IgnoreMostSpecificConstructor { get; set; } = false;
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
// Use default contract for non-object types.
if (objectType.IsPrimitive || objectType.IsEnum) return contract;
// Look for constructor with attribute first, then single private, then most specific.
var overrideConstructor =
(this.IgnoreAttributeConstructor ? null : GetAttributeConstructor(objectType))
?? (this.IgnoreSinglePrivateConstructor ? null : GetSinglePrivateConstructor(objectType))
?? (this.IgnoreMostSpecificConstructor ? null : GetMostSpecificConstructor(objectType));
// Set override constructor if found, otherwise use default contract.
if (overrideConstructor != null)
{
SetOverrideCreator(contract, overrideConstructor);
}
return contract;
}
private void SetOverrideCreator(JsonObjectContract contract, ConstructorInfo attributeConstructor)
{
contract.OverrideCreator = CreateParameterizedConstructor(attributeConstructor);
contract.CreatorParameters.Clear();
foreach (var constructorParameter in base.CreateConstructorParameters(attributeConstructor, contract.Properties))
{
contract.CreatorParameters.Add(constructorParameter);
}
}
private ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{
var c = method as ConstructorInfo;
if (c != null)
return a => c.Invoke(a);
return a => method.Invoke(null, a);
}
protected virtual ConstructorInfo GetAttributeConstructor(Type objectType)
{
var constructors = objectType
.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(c => c.GetCustomAttributes().Any(a => a.GetType().Name == this.ConstructorAttributeName)).ToList();
if (constructors.Count == 1) return constructors[0];
if (constructors.Count > 1)
throw new JsonException($"Multiple constructors with a {this.ConstructorAttributeName}.");
return null;
}
protected virtual ConstructorInfo GetSinglePrivateConstructor(Type objectType)
{
var constructors = objectType
.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
return constructors.Length == 1 ? constructors[0] : null;
}
protected virtual ConstructorInfo GetMostSpecificConstructor(Type objectType)
{
var constructors = objectType
.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.OrderBy(e => e.GetParameters().Length);
var mostSpecific = constructors.LastOrDefault();
return mostSpecific;
}
}
Here is the complete version with XML documentation as a gist: https://gist.github.com/maverickelementalch/80f77f4b6bdce3b434b0f7a1d06baa95
Feedback appreciated.
This is the best way, because if user not back more than two seconds then reset backpressed value.
declare one global variable.
private boolean backPressToExit = false;
Override
onBackPressed
Method.
@Override
public void onBackPressed() {
if (backPressToExit) {
super.onBackPressed();
return;
}
this.backPressToExit = true;
Snackbar.make(findViewById(R.id.yourview), getString(R.string.exit_msg), Snackbar.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
backPressToExit = false;
}
}, 2000);
}
See if the following works
Dim objShell
Set objShell = Wscript.CreateObject("WScript.Shell")
objShell.Run "TestScript.vbs"
' Using Set is mandatory
Set objShell = Nothing
You can learn more about AUROC in this blog post by Miron Kursa:
He provides a fast function for AUROC:
# By Miron Kursa https://mbq.me
auroc <- function(score, bool) {
n1 <- sum(!bool)
n2 <- sum(bool)
U <- sum(rank(score)[!bool]) - n1 * (n1 + 1) / 2
return(1 - U / n1 / n2)
}
Let's test it:
set.seed(42)
score <- rnorm(1e3)
bool <- sample(c(TRUE, FALSE), 1e3, replace = TRUE)
pROC::auc(bool, score)
mltools::auc_roc(score, bool)
ROCR::performance(ROCR::prediction(score, bool), "auc")@y.values[[1]]
auroc(score, bool)
0.51371668847094
0.51371668847094
0.51371668847094
0.51371668847094
auroc()
is 100 times faster than pROC::auc()
and computeAUC()
.
auroc()
is 10 times faster than mltools::auc_roc()
and ROCR::performance()
.
print(microbenchmark(
pROC::auc(bool, score),
computeAUC(score[bool], score[!bool]),
mltools::auc_roc(score, bool),
ROCR::performance(ROCR::prediction(score, bool), "auc")@y.values,
auroc(score, bool)
))
Unit: microseconds
expr min
pROC::auc(bool, score) 21000.146
computeAUC(score[bool], score[!bool]) 11878.605
mltools::auc_roc(score, bool) 5750.651
ROCR::performance(ROCR::prediction(score, bool), "auc")@y.values 2899.573
auroc(score, bool) 236.531
lq mean median uq max neval cld
22005.3350 23738.3447 22206.5730 22710.853 32628.347 100 d
12323.0305 16173.0645 12378.5540 12624.981 233701.511 100 c
6186.0245 6495.5158 6325.3955 6573.993 14698.244 100 b
3019.6310 3300.1961 3068.0240 3237.534 11995.667 100 ab
245.4755 253.1109 251.8505 257.578 300.506 100 a
var obj = db.Items.Where...
var orderBYItemId = obj.OrderByDescending(c => Convert.ToInt32(c.ID));
Another approach to test just for a JSON response (not that the content within contains an expected value), is to parse the response using ActiveSupport:
ActiveSupport::JSON.decode(response.body).should_not be_nil
If the response is not parsable JSON an exception will be thrown and the test will fail.
Here is code for getting value return from Store procedure
Stored procedure:
alter proc [dbo].[UserlogincheckMVC]
@username nvarchar(max),
@password nvarchar(max)
as
begin
if exists(select Username from Adminlogin where Username =@username and Password=@password)
begin
return 1
end
else
begin
return 0
end
end
Code:
var parameters = new DynamicParameters();
string pass = EncrytDecry.Encrypt(objUL.Password);
conx.Open();
parameters.Add("@username", objUL.Username);
parameters.Add("@password", pass);
parameters.Add("@RESULT", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
var RS = conx.Execute("UserlogincheckMVC", parameters, null, null, commandType: CommandType.StoredProcedure);
int result = parameters.Get<int>("@RESULT");
I like Open DBDiff.
While not the most complete tool, it works great, it's free, and it's very easy to use.
Try to replace the
padding: 2px 30px 2px 2px;
with
padding: 2px 2px 2px 2px;
It should work.
It seems that Microsoft finally is addressing this problem. Current versions in the Insider Editions of Explorer allows creating files with a dot at the front.
Tested with Build 19541
I couldn't find an actual working PHP example to "invisibly" (without URL parameters) return client screen size, and other properties, to server-side PHP, so I put this example together.
JS populates and submits a hidden form (scripted by PHP from an array of JS properties), POST
ing to itself (the data now available in PHP) and returns the data in a table.
(Tested in "several" browsers.)
<!DOCTYPE html>
<html>
<head>
<title>*Client Info*</title>
<style>table,tr{border:2px solid gold;border-collapse:collapse;}td{padding:5px;}</style>
</head>
<body>
<?php
$clientProps=array('screen.width','screen.height','window.innerWidth','window.innerHeight',
'window.outerWidth','window.outerHeight','screen.colorDepth','screen.pixelDepth');
if(! isset($_POST['screenheight'])){
echo "Loading...<form method='POST' id='data' style='display:none'>";
foreach($clientProps as $p) { //create hidden form
echo "<input type='text' id='".str_replace('.','',$p)."' name='".str_replace('.','',$p)."'>";
}
echo "<input type='submit'></form>";
echo "<script>";
foreach($clientProps as $p) { //populate hidden form with screen/window info
echo "document.getElementById('" . str_replace('.','',$p) . "').value = $p;";
}
echo "document.forms.namedItem('data').submit();"; //submit form
echo "</script>";
}else{
echo "<table>";
foreach($clientProps as $p) { //create output table
echo "<tr><td>".ucwords(str_replace('.',' ',$p)).":</td><td>".$_POST[str_replace('.','',$p)]."</td></tr>";
}
echo "</table>";
}
?>
<script>
window.history.replaceState(null,null); //avoid form warning if user clicks refresh
</script>
</body>
</html>
The returned data is extract
'd into variables. For example:
window.innerWidth
is returned in $windowinnerWidth
When you are inside an activity and need to go to a fragment use below
getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();
But when you are inside a fragment and need to go to a fragment then just add a getActivity().
before, so it would become
getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();
as simple as that.
The *TO_BE_REPLACED_LAYOUT_ID*
can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout
.
You can use result.className = 'red';
, but you can also use result.classList.add('red');
. The .classList.add(str)
way is usually easier if you need to add a class in general, and don't want to check if the class is already in the list of classes.
'JavaType' works !!
I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution.
Code:
JsonMarshallerUnmarshaller<T> {
T targetClass;
public ArrayList<T> unmarshal(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper.getDeserializationConfig()
.withAnnotationIntrospector(introspector);
mapper.getSerializationConfig()
.withAnnotationIntrospector(introspector);
JavaType type = mapper.getTypeFactory().
constructCollectionType(
ArrayList.class,
targetclass.getClass());
try {
Class c1 = this.targetclass.getClass();
Class c2 = this.targetclass1.getClass();
ArrayList<T> temp = (ArrayList<T>)
mapper.readValue(jsonString, type);
return temp ;
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
}
From the jinja docs section HTML Escaping:
When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.
Example:
<div class="info">
{{data.email_content|safe}}
</div>
If You are more into programming with templates, You may also do it this way...
template<typename _Tp>
... some algo ...
cv::Mat mat = cv::Mat_<_Tp>::zeros(rows, cols);
mat.at<_Tp>(i, j) = val;
Since I like a couple of the answers - one for using string.Create
and therefore high performance and low allocation and another for correctness - using the StringInfo
class, I decided a combined approach is needed. This is the ultimate string reversal method :)
private static string ReverseString(string str)
{
return string.Create(str.Length, str, (chars, state) =>
{
var enumerator = StringInfo.GetTextElementEnumerator(state);
var position = state.Length;
while (enumerator.MoveNext())
{
var cluster = ((string)enumerator.Current).AsSpan();
cluster.CopyTo(chars.Slice(position - cluster.Length));
position -= cluster.Length;
}
});
}
There's an even better way using a method of the StringInfo class which skips a lot of string allocations by the Enumerator by returning just the indexes.
private static string ReverseString(string str)
{
return string.Create(str.Length, str, (chars, state) =>
{
var position = 0;
var indexes = StringInfo.ParseCombiningCharacters(state); // skips string creation
var stateSpan = state.AsSpan();
for (int len = indexes.Length, i = len - 1; i >= 0; i--)
{
var index = indexes[i];
var spanLength = i == len - 1 ? state.Length - index : indexes[i + 1] - index;
stateSpan.Slice(index, spanLength).CopyTo(chars.Slice(position));
position += spanLength;
}
});
}
Some benchmarks compared to the LINQ solution:
String length 20:
LINQ Mean: 2,355.5 ns Allocated: 1440 B
string.Create Mean: 851.0 ns Allocated: 720 B
string.Create with indexes Mean: 466.4 ns Allocated: 168 B
String length 450:
LINQ Mean: 34.33 us Allocated: 22.98 KB
string.Create Mean: 19.13 us Allocated: 14.98 KB
string.Create with indexes Mean: 10.32 us Allocated: 2.69 KB
I didn't have the name in my Input ... my request was empty... glad that is finished and I can keep coding. Thanks everyone!
Answer I used by Jason Kim:
So instead of
<input type="password" class="form-control" id="password">
I have this
<input type="password" class="form-control" id="password" name="password">
I like to use Action in place of MethodInvoker, it is shorter and looks cleaner.
Invoke((Action)(() => {
DoSomething();
}));
// OR
Invoke((Action)delegate {
DoSomething();
});
Eg.
// Thread-safe update on a form control
public void DisplayResult(string text){
if (txtResult.InvokeRequired){
txtResult.Invoke((Action)delegate {
DisplayResult(text);
});
return;
}
txtResult.Text += text + "\r\n";
}
Client use convert File to ToBase64String
, after use Xml to promulgate
to Server call, this server use File.WriteAllBytes(path,Convert.FromBase64String(dataFile_Client_sent))
.
Good lucky!
If dt is your datetime column, then
For 1:
SUBSTRING(CONVERT(varchar, dt, 13), 1, 2)
+ UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3))
For 2:
SUBSTRING(CONVERT(varchar, dt, 100), 13, 2)
+ SUBSTRING(CONVERT(varchar, dt, 100), 16, 3)
You can get access to the environment variables in either the command line or in the registry.
Command Line
If you want a specific environment variable, then just type the name of it (e.g. PATH
), followed by a >
, and the filename to write to. The following will dump the PATH environment variable to a file named path.txt.
C:\> PATH > path.txt
Registry Method
The Windows Registry holds all the environment variables, in different places depending on which set you are after. You can use the registry Import/Export commands to shift them into the other PC.
For System Variables:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
For User Variables:
HKEY_CURRENT_USER\Environment
Just generate ID and check whether it is already present or not in your list of generated IDs.
In Visual Studio 2010, right click the project, choose Properties, click the configuring properties section on the left pane, then click Debugging, then on the right pane there is a box for command arguments.
In that enter the command line arguments. You are good to go. Now debug and see the result. If you are tired of changing in the properties then temporarily give the input directly in the program.
For those of you who would prefer an Object
as opposed to a serialized string (like the one returned by $(form).serialize()
, and a slight improvement on $(form).serializeArray()
), feel free to use the code below:
var Form = {
_form: null,
_validate: function(){
if(!this._form || this._form.tagName.toLowerCase() !== "form") return false;
if(!this._form.elements.length) return false;
}, _loopFields: function(callback){
var elements = this._form.elements;
for(var i = 0; i < elements.length; i++){
var element = form.elements[i];
if(name !== ""){
callback(this._valueOfField(element));
}
}
}, _valueOfField: function(element){
var type = element.type;
var name = element.name.trim();
var nodeName = element.nodeName.toLowerCase();
switch(nodeName){
case "input":
if(type === "radio" || type === "checkbox"){
if(element.checked){
return element.value;
}
}
return element.value;
break;
case "select":
if(type === "select-multiple"){
for(var i = 0; i < element.options.length; i++){
if(options[i].selected){
return element.value;
}
}
}
return element.value;
break;
case "button":
switch(type){
case "reset":
case "submit":
case "button":
return element.value;
break;
}
break;
}
}, serialize: function(form){
var data = {};
this._form = form;
if(this._validate()){
this._loopFields(function(value){
if(value !== null) data[name] = value;
});
}
return data;
}
};
To execute it, just use Form.serialize(form)
and the function will return an Object
similar to this:
<!-- { username: "username", password: "password" } !-->
<input type="text" value="username">
<input type="password" value="password">
As a bonus, it means you don't have to install the entire bundle of jQuery just for one serialize function.
Nested fragments are not currently supported. Try Support Package, revision 11.
If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:
$scope.Users = ["Suresh","Mahesh","Ramesh"];
$scope.selectedUser = $scope.Users[0];
Your HTML
<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>
complex example
Inside Controller:
$scope.JSON = {
"ResponseObject":
[{
"Name": "Suresh",
"userID": 1
},
{
"Name": "Mahesh",
"userID": 2
}]
};
$scope.selectedUser = $scope.JSON.ResponseObject[0];
Your HTML
<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>
Can't you just create a static method that does exactly this?
private static <K, V> V getOrDefault(Map<K,V> map, K key, V defaultValue) {
return map.containsKey(key) ? map.get(key) : defaultValue;
}
You can do it without jQuery!
Example:
document.querySelector('button').setAttribute('disabled', '');
_x000D_
<button>My disabled button!</button>
_x000D_
To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.
What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.
Using the same key you can generate, & reverify, edit, etc.
For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.
Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length
you can use online generator, or manually write
I prefer using openssl
C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg
generate, then encode with base 64
C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20
The generated value is saved inside the file named "openssl-secret.txt"
generate, & store into a file.
One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.
I recommend reading this article
This solves the problem:
df['newcolumn'] = df.A * df.B
You could also do:
def fab(row):
return row['A'] * row['B']
df['newcolumn'] = df.apply(fab, axis=1)
There are little difference in command of adding AND changing DNS-IPs:
To Add:
Syntax:
netsh interface ipv4 add dnsserver "Network Interface Name" dns.server.ip index=1(for primary)2(for secondary)
Eg:
netsh interface ipv4 add dnsserver "Ethernet" 8.8.8.8 index=1
netsh interface show interface
To Set/Change: (as OP asked this)
Syntax:
netsh interface ipv4 set dnsservers "Network Interface Name" static dns.server.ip primary
Eg:
netsh interface ipv4 set dnsservers "Wi-Fi" static 8.8.4.4 primary
netsh interface ipv4 set dnsservers "Wi-Fi" dhcp
Last parameter can be none
:disable DNS, both
:set for primary and secondary DNS both, primary: for primary DNS only. You can notice here we are not using index-parameter as we did in adding DNS.
In the place of static
you can type dhcp
to make DNS setting automatic, but further parameter will not be required.
Note: Tested in windows 8,8.1 & 10.
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
A particularly feisty example is when you decide to show a managed Dialog from an Activity using showDialog()
. If the user rotates the screen while the dialog is still open (we call this a "configuration change"), then the main Activity will go through all the ending lifecycle calls up untill onDestroy()
, will be recreated, and go back up through the lifecycles. What you might not expect however, is that onCreateDialog()
and onPrepareDialog()
(the methods that are called when you do showDialog()
and now again automatically to recreate the dialog - automatically since it is a managed dialog) are called between onStart()
and onResume()
. The pointe here is that the dialog does not cover the full screen and therefore leaves part of the main activity visible. It's a detail but it does matter!
If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.
Vagrant provides a way to execute a command over ssh instead of logging in, so for Linux host and guest you can use:
cat ~/file_on_host.txt | vagrant ssh -c 'cat - > ~/file_on_guest.txt'
vagrant ssh -c 'cat ~/file_on_guest.txt' > ~/file_on_host.txt
No need for plugins or guest reloads. Just make sure to provide vagrant box ID to 'vagrant ssh' if you are not in the same dir as the Vagrantfile. Tested on Vagrant v1.8.1.
Know the master key yourself. Don't hard code it.
Use py-bcrypt
(bcrypt), powerful hashing technique to generate a password yourself.
Basically you can do this (an idea...)
import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)
save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.
This is basically how login should work these days.
Normally the code request should be made through a constructor parameter, as in
public MyConsumingClass(IDependency dependency)
I wanted to point out in @akazemis's answer that "services" in the context of DI does not imply RESTful services; services are implementations of dependencies that provide functionality.
Well the closest thing I've been able to get with the StyledMarker is this.
The bullet in the middle isn't quite a big as the default one though. The StyledMarker class simply builds this url and asks the google api to create the marker.
From the class use example use "%E2%80%A2" as your text, as in:
var styleMaker2 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{text:"%E2%80%A2"},styleIconClass),position:new google.maps.LatLng(37.263477473067, -121.880502070713),map:map});
You will need to modifiy StyledMarker.js to comment out the lines:
if (text_) {
text_ = text_.substr(0,2);
}
as this will trim the text string to 2 characters.
Alternatively you could create custom marker images based on the default one with the colors you desire and override the default marker with code such as this:
marker = new google.maps.Marker({
map:map,
position: latlng,
icon: new google.maps.MarkerImage(
'http://www.gettyicons.com/free-icons/108/gis-gps/png/24/needle_left_yellow_2_24.png',
new google.maps.Size(24, 24),
new google.maps.Point(0, 0),
new google.maps.Point(0, 24)
)
});
Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/
HTML
<h2>TableHeadFixer Fix Left Column</h2>
<div id="parent">
<table id="fixTable" class="table">
<thead>
<tr>
<th>Ano</th>
<th>Jan</th>
<th>Fev</th>
<th>Mar</th>
<th>Abr</th>
<th>Maio</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
</tbody>
</table>
</div>
JS
$(document).ready(function() {
$("#fixTable").tableHeadFixer({"head" : false, "right" : 1});
});
CSS
#parent {
height: 300px;
}
#fixTable {
width: 1800px !important;
}
You are looking for Java generics
List<MyClass> list = new ArrayList<MyClass>();
Here's a tutorial http://docs.oracle.com/javase/tutorial/java/generics/index.html
You should be able to use normal C methods in math.
#include <cmath>
pow(2,3)
if you're on a unix-like system, man cmath
Is that what you're asking?
Sujal
Try to create a file using the code, so you will get to know the path of the file where the system create
File test=new File("check.txt");
if (test.createNewFile()) {
System.out.println("File created: " + test.getName());
}
If you are deeply in recursion inside recursive method, throwing and catching exception may be an option.
Unlike Return that returns only one level up, exception would break out of recursive method as well into the code that initially called it, where it can be catched.
I don't know any language where subclasses inherit constructors (but then, I am not much of a programming polyglott).
Here's a discussion about the same question concerning C#. The general consensus seems to be that it would complicate the language, introduce the potential for nasty side effects to changes in a base class, and generally shouldn't be necessary in a good design.
I have observed a similar issue in my project. The issue was solved when the jar with the missing class definition was pasted into the lib directory of tomcat.
Use convert with style 101.
select convert(datetime, Remarks, 101)
If your column is really text
you need to convert to varchar before converting to datetime
select convert(datetime, convert(varchar(30), Remarks), 101)
<input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />
Or you can modify it from outside the form, with javascript the normal way:
document.getElementById('form_id').action = 'somethingelse';
import difflib
lines1 = '''
dog
cat
bird
buffalo
gophers
hound
horse
'''.strip().splitlines()
lines2 = '''
cat
dog
bird
buffalo
gopher
horse
mouse
'''.strip().splitlines()
# Changes:
# swapped positions of cat and dog
# changed gophers to gopher
# removed hound
# added mouse
for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm=''):
print line
Outputs the following:
--- file1
+++ file2
@@ -1,7 +1,7 @@
+cat
dog
-cat
bird
buffalo
-gophers
-hound
+gopher
horse
+mouse
This diff gives you context -- surrounding lines to help make it clear how the file is different. You can see "cat" here twice, because it was removed from below "dog" and added above it.
You can use n=0 to remove the context.
for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
print line
Outputting this:
--- file1
+++ file2
@@ -0,0 +1 @@
+cat
@@ -2 +2,0 @@
-cat
@@ -5,2 +5 @@
-gophers
-hound
+gopher
@@ -7,0 +7 @@
+mouse
But now it's full of the "@@" lines telling you the position in the file that has changed. Let's remove the extra lines to make it more readable.
for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
for prefix in ('---', '+++', '@@'):
if line.startswith(prefix):
break
else:
print line
Giving us this output:
+cat
-cat
-gophers
-hound
+gopher
+mouse
Now what do you want it to do? If you ignore all removed lines, then you won't see that "hound" was removed. If you're happy just showing the additions to the file, then you could do this:
diff = difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0)
lines = list(diff)[2:]
added = [line[1:] for line in lines if line[0] == '+']
removed = [line[1:] for line in lines if line[0] == '-']
print 'additions:'
for line in added:
print line
print
print 'additions, ignoring position'
for line in added:
if line not in removed:
print line
Outputting:
additions:
cat
gopher
mouse
additions, ignoring position:
gopher
mouse
You can probably tell by now that there are various ways to "print the differences" of two files, so you will need to be very specific if you want more help.
I've got a solution that should work in IE6 (and definitely works in 7+ & FireFox/Chrome).
You were on the right track using a span
, but the use of a ul
was wrong and the css wasn't right.
<a class="htooltip" href="#">
Notes
<span>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
</span>
</a>
.htooltip, .htooltip:visited, .tooltip:active {
color: #0077AA;
text-decoration: none;
}
.htooltip:hover {
color: #0099CC;
}
.htooltip span {
display : none;
position: absolute;
background-color: black;
color: #fff;
padding: 5px 10px 5px 40px;
text-decoration: none;
width: 350px;
z-index: 10;
}
.htooltip:hover span {
display: block;
}
Everyone was going about this the wrong way. The code isn't valid, ul
's cant go in a
's, p
's can't go in a
's, div
's cant go in a
's, just use a span
(remembering to make it display
as a block
so it will wrap as if it were a div
/p
etc).
Hello Googlers from the future.
On MacOS >= High Sierra, the SSH key is no longer saved to the KeyChain because of reasons.
Using ssh-add -K
no longer survives restarts as well.
Here are 3 possible solutions.
I've used the first method successfully. I've created a file called config
in ~/.ssh
:
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
I'm using this solution and works in IE8 or greater.
if (typeof Element.prototype.addEventListener === 'undefined') {
Element.prototype.addEventListener = function (e, callback) {
e = 'on' + e;
return this.attachEvent(e, callback);
};
}
And then:
<button class="click-me">Say Hello</button>
<script>
document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
console.log('Hello');
});
</script>
This will work both IE8 and Chrome, Firefox, etc.
I used string.js's latinise() method, which lets you do it like this:
var output = S(input).latinise().toString();
Interesting one. I love collecting quotes about quotes handling in cmd/command.
Your particular scripts gets fixed by using %1 instead of "%1" !!!
By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.
For Android 10 Following code is working for me.
val uid: String = Settings.Secure.getString(ctx.applicationContext.contentResolver, Settings.Secure.ANDROID_ID)
if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
imei = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
uid
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
telephonyManager.imei
}
else -> {
telephonyManager.deviceId
}
}
}
elementwise compare ? what about
public void Linq78a()
{
int[] numbers1 = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
bool bb = numbers.Zip(numbers1, (a, b) => (a == b)).Any(p => !p);
if (!bb) Console.WriteLine("Lists are equal (bb)");
else Console.WriteLine("Lists are not equal (bb)");
}
Replace the (a==b) condition by anything you'd like to compare in a and b.
(this combines two examples from MSDN developer Linq samples)
as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?
"This is my string with date in specified format $($theDate.ToString('u'))"
or
"This is my string with date in specified format $(Get-Date -format 'u')"
The sub-expression ($(...)
) can include arbitrary expressions calls.
MSDN Documents both standard and custom DateTime
format strings.
Try this
<?php
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) &&
recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
?>
I know the question is how to generate QR codes using PHP, but for others who are looking for a way to generate codes for websites doing this in pure javascript is a good way to do it. The jquery-qrcode jquery plugin does it well.
you can use BCP in and out for small tables.
BCP OUT command:-
BCP "SELECT * FROM [Dinesh].[dbo].[Invoices]" QUERYOUT C:\av\Invoices1.txt -S MC0XENTC -T -c -r c:\error.csv
BCP IN command:- Create table structure for Invoicescopy1.
BCP [Dinesh].[dbo].[Invoicescopy1] IN C:\av\Invoices.txt -S MC0XENTC -T -c
AFAIK, you can't do it with CSS alone. CSS has content
rule but even that can be used to insert content before or after an element using pseudo selectors. You need to resort to javascript for that OR use placeholder
attribute if you are using HTML5 as pointed out by @Blender.
We recently had the issue when trying to run the code from Visual Studio. In that case you need to do
TOOLS > OPTIONS > Projects and Solutions > WEB PROJECTS and check the "Use the 64 bit version of IIS Express for web sites and projects".
One more cause for the "secret key not available" message: GPG version mismatch.
Practical example: I had been using GPG v1.4. Switching packaging systems, the MacPorts supplied gpg was removed, and revealed another gpg binary in the path, this one version 2.0. For decryption, it was unable to locate the secret key and gave this very error. For encryption, it complained about an unusable public key. However, gpg -k and -K both listed valid keys, which was the cause of major confusion.
Can also be called as
@Html.Partial("_PartialView", (ModelClass)View.Data)
The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS
$(document).ready(function(){
$("#a").mouseover(function(){
$("#b").css("background-color", "red");
});
});
var list = new List<string>(1) { "hello" };
Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially.
Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once.
Remove the below code it will work
super.onReceivedSslError(view, handler, error);
I had an issue with connected repository. What's how I fixed:
I deleted manually .git folder under my project folder, run git init and then it all worked.
Steps using XAMPP GUI:
Step-1: Click on Config button
Step-2: Click on Service and Port Settings button
Final step: Change your port and Save
This answer refers to an older version of Java. You may want to look at ccleve's answer.
Here is the traditional way to do this:
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static String getText(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}
public static void main(String[] args) throws Exception {
String content = URLConnectionReader.getText(args[0]);
System.out.println(content);
}
}
As @extraneon has suggested, ioutils allows you to do this in a very eloquent way that's still in the Java spirit:
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
System.out.println( IOUtils.toString( in ) );
} finally {
IOUtils.closeQuietly(in);
}
If you just have a plain url string (and therefore don't have a hash attribute) you can also use a regular expression:
var url = "www.example.com/task1/1.3.html#a_1"
var anchor = url.match(/#(.*)/)[1]
Go to terminal type:
alias python=python3.x
This will setup default python as python3.x
You assert that a queue exists (and create it if it does not) by using queue.declare. If you originally set auto-delete to false, calling queue.declare again with autodelete true will result in a soft error and the broker will close the channel.
You need to use queue.delete now in order to delete it.
See the API documentation for details:
If you use another client, you'll need to find the equivalent method. Since it's part of the protocol, it should be there, and it's probably part of Channel or the equivalent.
You might also want to have a look at the rest of the documentation, in particular the Geting Started section which covers a lot of common use cases.
Finally, if you have a question and can't find the answer elsewhere, you should try posting on the RabbitMQ Discuss mailing list. The developers do their best to answer all questions asked there.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:
In child add:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
In parent add:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
Just because no-one else has posted this opinion, I would say
avoid
else
clauses intry/excepts
because they're unfamiliar to most people
Unlike the keywords try
, except
, and finally
, the meaning of the else
clause isn't self-evident; it's less readable. Because it's not used very often, it'll cause people that read your code to want to double-check the docs to be sure they understand what's going on.
(I'm writing this answer precisely because I found a try/except/else
in my codebase and it caused a wtf moment and forced me to do some googling).
So, wherever I see code like the OP example:
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
else:
# do some more processing in non-exception case
return something
I would prefer to refactor to
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
return # <1>
# do some more processing in non-exception case <2>
return something
<1> explicit return, clearly shows that, in the exception case, we are finished working
<2> as a nice minor side-effect, the code that used to be in the else
block is dedented by one level.
You can install OpenCV by running these commands in the Anaconda command prompt:
conda config --add channels conda-forge
conda install libopencv opencv py-opencv
Source:
I m using the followung code and its working fine for me .
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("GCM Notification")
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt
To fix, open your script with vi or vim and enter in vi command mode (key Esc), then type this:
:set fileformat=unix
Finally save it
:x!
or :wq!
The Pattern.quote(String s)
sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E
.
There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:
regex.replaceAll("[\\W]", "\\\\$0")
Why does this work? Well, the documentation for Pattern
specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:
It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
For example, ;
is not a special character in a regular expression. However, if you escape it, Pattern
will still interpret \;
as ;
. Here are a few more examples:
>
becomes \>
which is equivalent to >
[
becomes \[
which is the escaped form of [
8
is still 8
.\)
becomes \\\)
which is the escaped forms of \
and (
concatenated. Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9]
.
I had the same problem. You want to look the connection object supplied by the entity manager:
$conn = $em->getConnection();
You can then query/execute directly against it:
$statement = $conn->query('select foo from bar');
$num_rows_effected = $conn->exec('update bar set foo=1');
See the docs for the connection object at http://www.doctrine-project.org/api/dbal/2.0/doctrine/dbal/connection.html
You could use use max
and min
with dict.get
:
maximum = max(mydict, key=mydict.get) # Just use 'min' instead of 'max' for minimum.
print(maximum, mydict[maximum])
# D 87
Depending on the size of your list, it may be most efficient if you use list.remove() rather than create a new list:
l = ["1", "", "3", ""]
while True:
try:
l.remove("")
except ValueError:
break
This has the advantage of not creating a new list, but the disadvantage of having to search from the beginning each time, although unlike using while '' in l
as proposed above, it only requires searching once per occurrence of ''
(there is certainly a way to keep the best of both methods, but it is more complicated).
String tokenizer this code should put you in the right direction.
int main(void) {
char st[] ="Where there is will, there is a way.";
char *ch;
ch = strtok(st, " ");
while (ch != NULL) {
printf("%s\n", ch);
ch = strtok(NULL, " ,");
}
getch();
return 0;
}
shuf -i 2000-65000 -n 1
Enjoy!
Edit: The range is inclusive.
The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document
) and will be executed when an event reaches that element having originated on an element matching the selector.
This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id
element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.
The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.
By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id
element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.
You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting
countByType.entrySet()
.stream()
.sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
.map(e -> e.getKey())
.collect(Collectors.toList());
to make the difference between a refresh and a closed tab or navigator, here is how I fixed it :
<script>_x000D_
function endSession() {_x000D_
// Browser or Broswer tab is closed_x000D_
// Write code here_x000D_
}_x000D_
</script>_x000D_
_x000D_
<body onpagehide="endSession();">_x000D_
_x000D_
</body>
_x000D_
For those who are getting to this question via google... this error can also happen if you try to rename a field that is acting as a foreign key.
(extending the other answers)
Note, git check-ignore
uses the committed .gitignore
and not the one in your working tree! To play with it without polluting your git history, you might freely try to edit it, and then commit with a git commit --amend
.
This problem happens mainly if you need a workaround of the problem, that git doesn't follow directories. Enter in the .gitignore
:
dirtokeep/**
!dirtokeep/.keep
.keep
should be a zero-length file in dirtokeep
.
The result will be that everything in dirtokeep
will be ignored, except dirtokeep/.keep
, which will result that also the dirtokeep
directory will be constructed on clone/checkout.
Try this
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String userName = authentication.getName();
Add a hidden reset button :
<input id="Reset1" type="reset" value="reset" class="hidden" />
Click the reset button to clear the input.
$("#Reset1").click();
If you want the view to have the translucent nav bar (which is kind of nice) you have to setup a contentInset or similar.
Here is how I do it:
// Check if we are running on ios7
if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;
myContentView.contentInset = UIEdgeInsetsMake(heightPadding, 0.0, 0.0, 0.0);
}
It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py
in the same directory.
wp_trim_words
This function trims text to a certain number of words and returns the trimmed text.
echo wp_trim_words( get_the_content(), 40, '...' );
If you are okay with using the built in Visual Studio Development server or you don't want to or cannot install IIS, you can change the web server the project uses by going into
Project Properties (right click project in solution explorer and select properties)
select Web tab
select "Use Visual Studio Development Server".
I don't know how it happened to me, but somehow this option was changed to "Use Local IIS Web Server" for one of my projects.
When you say:
$user = $_POST["username"];
You're asking the PHP interpreter to assign $user
the value of the $_POST
array that has a key (or index) of username
. If it doesn't exist, PHP throws a fit.
Use isset($_POST['user'])
to check for the existence of that variable:
if (isset($_POST['user'])) {
$user = $_POST["username"];
...
In Ruby and other languages that support POSIX character classes in bracket expressions, you can do simply:
/\A[[:alpha:]]+\z/i
That will match alpha-chars in all Unicode alphabet languages. Easy peasy.
More info: http://en.wikipedia.org/wiki/Regular_expression#Character_classes http://ruby-doc.org/core-2.0/Regexp.html
All you have to do is to delete the "0" in the cells that contain just that and try again. That should work.
Just replace
& with &
And for other characters:
> with >
< with <
\" with "
' with '
val currentTime = Calendar.getInstance().time
SimpleDateFormat("MMMM", Locale.getDefault()).format(date.time)
Thank you for the answer, i would like to add onto hfern's(above) Python version to include the Sending function if any one is interested.
def DecodedWebsockRecieve(stringStreamIn):
byteArray = stringStreamIn
datalength = byteArray[1] & 127
indexFirstMask = 2
if datalength == 126:
indexFirstMask = 4
elif datalength == 127:
indexFirstMask = 10
masks = [m for m in byteArray[indexFirstMask : indexFirstMask+4]]
indexFirstDataByte = indexFirstMask + 4
decodedChars = []
i = indexFirstDataByte
j = 0
while i < len(byteArray):
decodedChars.append( chr(byteArray[i] ^ masks[j % 4]) )
i += 1
j += 1
return ''.join(decodedChars)
def EncodeWebSockSend(socket,data):
bytesFormatted = []
bytesFormatted.append(129)
bytesRaw = data.encode()
bytesLength = len(bytesRaw)
if bytesLength <= 125 :
bytesFormatted.append(bytesLength)
elif bytesLength >= 126 and bytesLength <= 65535 :
bytesFormatted.append(126)
bytesFormatted.append( ( bytesLength >> 8 ) & 255 )
bytesFormatted.append( bytesLength & 255 )
else :
bytesFormatted.append( 127 )
bytesFormatted.append( ( bytesLength >> 56 ) & 255 )
bytesFormatted.append( ( bytesLength >> 48 ) & 255 )
bytesFormatted.append( ( bytesLength >> 40 ) & 255 )
bytesFormatted.append( ( bytesLength >> 32 ) & 255 )
bytesFormatted.append( ( bytesLength >> 24 ) & 255 )
bytesFormatted.append( ( bytesLength >> 16 ) & 255 )
bytesFormatted.append( ( bytesLength >> 8 ) & 255 )
bytesFormatted.append( bytesLength & 255 )
bytesFormatted = bytes(bytesFormatted)
bytesFormatted = bytesFormatted + bytesRaw
socket.send(bytesFormatted)
Usage for reading:
bufSize = 1024
read = DecodedWebsockRecieve(socket.recv(bufSize))
Usage for writing:
EncodeWebSockSend(sock,"hellooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo")
A good object oriented design should not need many publicly available constants. Most constants should be encapsulated in the class that needs them to do its job.
you really don't need quotes if let say use are using the image from your css file it can be
{background-image: url(your image.png/jpg etc);}
a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.
if you want real difference
select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);
if you want absolute difference
select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));
I had the same doubt, but see the PHP docu:
https://www.php.net/manual/en/function.file-exists.php
https://www.php.net/manual/en/function.is-dir.php
You will see that is_dir()
has both properties.
Return Values is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.
I have used Netbeans for java, and it works great. Not sure how it works with C++, though.
I agree with Levik as the parent container is set to 100% if you have sidebars and want them to fill the space to meet up with the footer you cannot set them to 100% because they will be 100 percent of the parent height as well which means that the footer ends up getting pushed down when using the clear function.
Think of it this way if your header is say 50px height and your footer is 50px height and the content is just autofitted to the remaining space say 100px for example and the page container is 100% of this value its height will be 200px. Then when you set the sidebar height to 100% it is then 200px even though it is supposed to fit snug in between the header and footer. Instead it ends up being 50px + 200px + 50px so the page is now 300px because the sidebars are set to the same height as the page container. There will be a big white space in the contents of the page.
I am using internet Explorer 9 and this is what I am getting as the effect when using this 100% method. I havent tried it in other browsers and I assume that it may work in some of the other options. but it will not be universal.
More formats:
require 'date'
date = "01/07/2016 09:17AM"
DateTime.parse(date).strftime("%A, %b %d")
#=> Friday, Jul 01
DateTime.parse(date).strftime("%m/%d/%Y")
#=> 07/01/2016
DateTime.parse(date).strftime("%m-%e-%y %H:%M")
#=> 07- 1-16 09:17
DateTime.parse(date).strftime("%b %e")
#=> Jul 1
DateTime.parse(date).strftime("%l:%M %p")
#=> 9:17 AM
DateTime.parse(date).strftime("%B %Y")
#=> July 2016
DateTime.parse(date).strftime("%b %d, %Y")
#=> Jul 01, 2016
DateTime.parse(date).strftime("%a, %e %b %Y %H:%M:%S %z")
#=> Fri, 1 Jul 2016 09:17:00 +0200
DateTime.parse(date).strftime("%Y-%m-%dT%l:%M:%S%z")
#=> 2016-07-01T 9:17:00+0200
DateTime.parse(date).strftime("%I:%M:%S %p")
#=> 09:17:00 AM
DateTime.parse(date).strftime("%H:%M:%S")
#=> 09:17:00
DateTime.parse(date).strftime("%e %b %Y %H:%M:%S%p")
#=> 1 Jul 2016 09:17:00AM
DateTime.parse(date).strftime("%d.%m.%y")
#=> 01.07.16
DateTime.parse(date).strftime("%A, %d %b %Y %l:%M %p")
#=> Friday, 01 Jul 2016 9:17 AM
I found out that (bootstrap 4) putting your own CSS behind bootstrap.css
and .js is the best solution.
Find the item you want to change (inspect element) and use the exact same declaration then it will override.
It took me some little time to figure this out.
AnimationSets don't appear to work as expected at all. In the end I gave up and used the Handler class's postDelayed() to sequence animations.
Basically the same PictureBox solution above, but this time with the code-behind to use an Embedded Resource in your project:
In XAML:
<WindowsFormsHost x:Name="_loadingHost">
<Forms:PictureBox x:Name="_loadingPictureBox"/>
</WindowsFormsHost>
In Code-Behind:
public partial class ProgressIcon
{
public ProgressIcon()
{
InitializeComponent();
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("My.Namespace.ProgressIcon.gif");
var image = System.Drawing.Image.FromStream(stream);
Loaded += (s, e) => _loadingPictureBox.Image = image;
}
}
For those who need the answer at work and creating function is forbidden by your DBA, the following solution will work:
select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-1), YourDate) as DATE) as WeekStart
From.....
This gives the start of that week. Here I assume that Sundays are the start of weeks. If you think that Monday is the start, you should use:
select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-2), YourDate) as DATE) as WeekStart
From.....
Edit 2: See @flodel's answer. Much better.
Try:
# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))
Edit: or as @ CarlWitthoft suggested in the comments:
matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))
Use
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return shouldOverrideUrlLoading(view, request.getUrl().toString());
}
//create TreeMap instance
TreeMap treeMap = new TreeMap();
//add key value pairs to TreeMap
treeMap.put("1","One");
treeMap.put("2","Two");
treeMap.put("3","Three");
/*
get Collection of values contained in TreeMap using
Collection values()
*/
Collection c = treeMap.values();
//obtain an Iterator for Collection
Iterator itr = c.iterator();
//iterate through TreeMap values iterator
while(itr.hasNext())
System.out.println(itr.next());
or:
for (Map.Entry<K,V> entry : treeMap.entrySet()) {
V value = entry.getValue();
K key = entry.getKey();
}
or:
// Use iterator to display the keys and associated values
System.out.println("Map Values Before: ");
Set keys = map.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
Integer key = (Integer) i.next();
String value = (String) map.get(key);
System.out.println(key + " = " + value);
}
You mean this?
from string import punctuation, digits
takeout = punctuation + digits
turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis
Typescript has a JavaScript runtime because it gets compiled to JS. This means JS objects which are built in as part of the language such as JSON
, Object
, and Math
are also available in TS. Therefore we can just use the JSON.parse
method to parse the JSON string.
const JSONStr = '{"name": "Bob", "error": false}'
// The JSON object is part of the runtime
const parsedObj = JSON.parse(JSONStr);
console.log(parsedObj);
// [LOG]: {
// "name": "Bob",
// "error": false
// }
// The Object object is also part of the runtime so we can use it in TS
const objKeys = Object.keys(parsedObj);
console.log(objKeys);
// [LOG]: ["name", "error"]
The only thing now is that parsedObj is type any
which is generally a bad practice in TS. We can type the object if we are using type guards. Here is an example:
const JSONStr = '{"name": "Bob", "error": false}'
const parsedObj = JSON.parse(JSONStr);
interface nameErr {
name: string;
error: boolean;
}
function isNameErr(arg: any): arg is nameErr {
if (typeof arg.name === 'string' && typeof arg.error === 'boolean') {
return true;
} else {
return false;
}
}
if (isNameErr(parsedObj)) {
// Within this if statement parsedObj is type nameErr;
parsedObj
}
You need to test $?
instead, which is the exit status of the previous command. passwd
exits with 0 if everything worked ok, and non-zero if the passwd change failed (wrong password, password mismatch, etc...)
passwd
while [ $? -ne 0 ]; do
passwd
done
With your backtick version, you're comparing passwd's output, which would be stuff like Enter password
and confirm password
and the like.
$('#title').keyup(function () {
var replaceSpace = $(this).val();
var result = replaceSpace.replace(/\s/g, ";");
$("#keyword").val(result);
});
Since the javascript replace function do not replace 'all', we can make use the regular expression for replacement. As per your need we have to replace all space ie the \s in your string globally. The g character after the regular expressions represents the global replacement. The seond parameter will be the replacement character ie the semicolon.
Works for Dynamic and Static File Element
Javascript Only Solution
function ValidateSize(file) {
var FileSize = file.files[0].size / 1024 / 1024; // in MiB
if (FileSize > 2) {
alert('File size exceeds 2 MiB');
// $(file).val(''); //for clearing with Jquery
} else {
}
}
_x000D_
<input onchange="ValidateSize(this)" type="file">
_x000D_
If you add -chain to your command line, it will export any chained certificates.
I would recommend to use date->diff function, as in example below:
$dStart = new DateTime('2012-07-26');
$dEnd = new DateTime('2012-08-26');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater
This is a bit old, but I came here because I had the same issue. I'm using JUnit but this time in a Kotlin app with mockk. I'm posting a sample here for reference and comparison with the Java counterpart:
@Test
fun demo() {
// mock a sample function
val aMock: (String) -> (String) = mockk()
// make it return the same as the argument on every invocation
every {
aMock.invoke(any())
} answers {
firstArg()
}
// test it
assertEquals("senko", aMock.invoke("senko"))
assertEquals("senko1", aMock.invoke("senko1"))
assertNotEquals("not a senko", aMock.invoke("senko"))
}
if (strtotime($date) > mktime(0,0,0))
should do the job.
I solved this by using a small function to convert version strings to plain integer values that can be compared:
function versionToInt() {
local IFS=.
parts=($1)
let val=1000000*parts[0]+1000*parts[1]+parts[2]
echo $val
}
This makes two important assumptions:
For example
versionToInt 12.34.56 # --> 12034056
versionToInt 1.2.3 # --> 1002003
Example testing whether npm
command meets minimum requirement ...
NPM_ACTUAL=$(versionToInt $(npm --version)) # Capture npm version
NPM_REQUIRED=$(versionToInt 4.3.0) # Desired version
if [ $NPM_ACTUAL \< $NPM_REQUIRED ]; then
echo "Please update to npm@latest"
exit 1
fi
My answer to this is the same as in an answer to your earlier question. For a probability density function, the integral over the entire space is 1. Dividing by the sum will not give you the correct density. To get the right density, you must divide by the area. To illustrate my point, try the following example.
[f, x] = hist(randn(10000, 1), 50); % Create histogram from a normal distribution.
g = 1 / sqrt(2 * pi) * exp(-0.5 * x .^ 2); % pdf of the normal distribution
% METHOD 1: DIVIDE BY SUM
figure(1)
bar(x, f / sum(f)); hold on
plot(x, g, 'r'); hold off
% METHOD 2: DIVIDE BY AREA
figure(2)
bar(x, f / trapz(x, f)); hold on
plot(x, g, 'r'); hold off
You can see for yourself which method agrees with the correct answer (red curve).
Another method (more straightforward than method 2) to normalize the histogram is to divide by sum(f * dx)
which expresses the integral of the probability density function, i.e.
% METHOD 3: DIVIDE BY AREA USING sum()
figure(3)
dx = diff(x(1:2))
bar(x, f / sum(f * dx)); hold on
plot(x, g, 'r'); hold off