You need to put the last()
indexing on the nodelist result, rather than as part of the selection criteria. Try:
(//element[@name='D'])[last()]
mysql -uusername -ppassword database-name < file.sql
You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.
After having it defined in your manifest file, a friendlier alternative to the native solution would be using Aaper: https://github.com/LikeTheSalad/aaper like so:
@EnsurePermissions(permissions = [Manifest.permission.ACCESS_FINE_LOCATION])
private fun scanForLocation() {
// Your code that needs the location permission granted.
}
Disclaimer, I'm the creator of Aaper.
If you are using java 8, you can create Comparator by this method:
Comparator.comparingInt(i -> i);
if you would like to compare with reversed order:
Comparator.comparingInt(i -> -i);
Based on Bootstrap doc:
As of v3.1.0, .pull-right is deprecated on dropdown menus. use .dropdown-menu-right
eg:
<ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dLabel">
table.foobar
{
padding:30px; /* if border is not collapsed */
}
or
table.foobar
{
border-spacing:0;
}
table.foobar>tbody
{
display:table;
border-spacing:0; /* or other preferred */
border:30px solid transparent; /* 30px is the "padding" */
}
Works in Firefox, Chrome, IE11, Edge.
Swift:
extension Double {
func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
return dateFormatter.string(from: Date(timeIntervalSince1970: self))
}
}
train_test_split is now in model_selection. Just type:
from sklearn.model_selection import train_test_split
it should work
1: Prototype.observe
uses Element.addEventListener (see the source code)
2: You can override Element.addEventListener
to remember the added listeners (handy property EventListenerList
was removed from DOM3 spec proposal). Run this code before any event is attached:
(function() {
Element.prototype._addEventListener = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(a,b,c) {
this._addEventListener(a,b,c);
if(!this.eventListenerList) this.eventListenerList = {};
if(!this.eventListenerList[a]) this.eventListenerList[a] = [];
this.eventListenerList[a].push(b);
};
})();
Read all the events by:
var clicks = someElement.eventListenerList.click;
if(clicks) clicks.forEach(function(f) {
alert("I listen to this function: "+f.toString());
});
And don't forget to override Element.removeEventListener
to remove the event from the custom Element.eventListenerList
.
3: the Element.onclick
property needs special care here:
if(someElement.onclick)
alert("I also listen tho this: "+someElement.onclick.toString());
4: don't forget the Element.onclick
content attribute: these are two different things:
someElement.onclick = someHandler; // IDL attribute
someElement.setAttribute("onclick","otherHandler(event)"); // content attribute
So you need to handle it, too:
var click = someElement.getAttribute("onclick");
if(click) alert("I even listen to this: "+click);
The Visual Event bookmarklet (mentioned in the most popular answer) only steals the custom library handler cache:
It turns out that there is no standard method provided by the W3C recommended DOM interface to find out what event listeners are attached to a particular element. While this may appear to be an oversight, there was a proposal to include a property called eventListenerList to the level 3 DOM specification, but was unfortunately been removed in later drafts. As such we are forced to looked at the individual Javascript libraries, which typically maintain a cache of attached events (so they can later be removed and perform other useful abstractions).
As such, in order for Visual Event to show events, it must be able to parse the event information out of a Javascript library.
Element overriding may be questionable (i.e. because there are some DOM specific features like live collections, which can not be coded in JS), but it gives the eventListenerList support natively and it works in Chrome, Firefox and Opera (doesn't work in IE7).
Another approach using RegExp
const list = [1, 2, 3, 5, 2, 8, 9, 2]
const d = 2;
const counter = (`${list.join()},`.match(new RegExp(`${d}\\,`, 'g')) || []).length
console.log(counter)
_x000D_
The Steps follows as below
//
implements "floor division", regardless of your type. So
1.0/2.0
will give 0.5
, but both 1/2
, 1//2
and 1.0//2.0
will give 0
.
See https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator for details
You can just go with:
if(!$strings{$string}) ....
import subprocess
cmd = "vsish -e ls /vmkModules/lsom/disks/ | cut -d '/' -f 1 | while read diskID ; do echo $diskID; vsish -e cat /vmkModules/lsom/disks/$diskID/virstoStats | grep -iE 'Delete pending |trims currently queued' ; echo '====================' ;done ;"
def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
for line in proc_stdout.decode().split('\n'):
print (line)
subprocess_cmd(cmd)
Sorry, I wasn't sure which SQL platform you're talking about:
In MySQL:
$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");
in MSSQL
$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");
The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.
Edit
I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.
So, for MySQL there's the CHAR_LENGTH()
. The following example highlights the difference between LENGTH()
an CHAR_LENGTH()
:
CREATE TABLE words (
word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;
INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');
SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;
+--------+-----------+----------------+
| word | num_bytes | num_characters |
+--------+-----------+----------------+
| ?? | 6 | 2 |
| happy | 5 | 5 |
| hayir | 6 | 5 |
+--------+-----------+----------------+
Be careful if you're dealing with multi-byte characters.
Use jQTouch instead - its jQuery's mobile version
firefox: 18
.squaredcorners {
-moz-appearance: none;
}
You could use an onclick
event handler in order to get the input value for the text field. Make sure you give the field an unique id
attribute so you can refer to it safely through document.getElementById()
:
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">
. Create new elements by means of document.createElement()
, and use appendChild()
to append each of them to the container. You might be interested in outputting a meaningful name
attribute (e.g. name="member"+i
for each of the dynamically generated <input>
s if they are to be submitted in a form.
Notice you could also create <br/>
elements with document.createElement('br')
. If you want to just output some text, you can use document.createTextNode()
instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes()
and removeChild()
together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Number of inputs to create
var number = document.getElementById("member").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
<div id="container"/>
</body>
</html>
_x000D_
See a working sample in this JSFiddle.
Faced the same issue. To solve it,
$ sdk install gradle
using the package manager or $ brew install gradle
for mac. You might need to first install brew if not yet. You are probably looking for get_attribute()
. An example is shown here as well
def test_chart_renders_from_url(self):
url = 'http://localhost:8000/analyse/'
self.browser.get(url)
org = driver.find_element_by_id('org')
# Find the value of org?
val = org.get_attribute("attribute name")
If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type
git status -- it will show the files with changes
then if you want to know what changes are to be made it can be checked in ways ,
git diff -- will show all the changes in all files
it is good only when only one file is modified
and if you want to check particular file then use
git diff
Assuming you are dealing with a JSON-string in the input, you can parse it using the json
package, see the documentation.
In the specific example you posted you would need
x = json.loads("""{
"accountWide": true,
"criteria": [
{
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0
}
]
}""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']
To Hex:
string hex = intValue.ToString("X");
To int:
int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
There is a new way to solve this and it's by using async/await.
async function myFunction() {
while(/* my condition */) {
const res = await db.getUser(email);
logger.log(res);
}
}
myFunction().then(() => {
/* do other stuff */
})
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://ponyfoo.com/articles/understanding-javascript-async-await
-eq
is a mathematical comparison operator. I've never used it for string comparison, relying on ==
and !=
for compares.
if [ 'XYZ' == 'ABC' ]; then # Double equal to will work in Linux but not on HPUX boxes it should be if [ 'XYZ' = 'ABC' ] which will work on both
echo "Match"
else
echo "No Match"
fi
You could do this:
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;
Reference:
I had this issue with the Jenkins Git plugin after authentication issues with GitLab. Jenkins was reporting 'hudson.plugins.git.GitException:[...]stderr: GitLab: The project you were looking for could not be found. fatal: Could not read from remote repository.'
However if I did a 'git clone' or 'git fetch' direct from the Jenkins box (command line) it worked without issue.
The issue was resolved by deleting the entire /workspace directory in the Jenkins jobs folder for that particular job, e.g.
rm -Rf $JENKINS_HOME/jobs/myJenkinsJob/workspace/
Presumably the local .git folder had got stale/corrupted ?
You don't need an IIF() at all here. The comparisons return true or false anyway.
Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.
=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0
But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:
=Sum(
IIF(
Fields!OpeningStock.Value=0 AND
Fields!GrossDispatched.Value=0 AND
Fields!TransferOutToMW.Value=0 AND
Fields!TransferOutToDW.Value=0 AND
Fields!TransferOutToOW.Value=0 AND
Fields!NetDispatched.Value=0 AND
Fields!QtySold.Value=0 AND
Fields!StockAdjustment.Value=0 AND
Fields!ClosingStock.Value=0,
0,
1
)
) = 0
This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.
if the type is list, use len(list) and len(list[0]) to get the row and column.
l = [[1,2,3,4], [0,1,3,4]]
len(l) will be 2 len(l[0]) will be 4
Powershell + Curl + Zimbra SOAP API
${my_xml} = @"
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">
<soapenv:Body>
<GetFolderRequest xmlns=\"urn:zimbraMail\">
<folder>
<path>Folder Name</path>
</folder>
</GetFolderRequest>
</soapenv:Body>
</soapenv:Envelope>
"@
${my_curl} = "c:\curl.exe"
${cookie} = "c:\cookie.txt"
${zimbra_soap_url} = "https://zimbra:7071/service/admin/soap"
${curl_getfolder_args} = "-b", "${cookie}",
"--header", "Content-Type: text/xml;charset=UTF-8",
"--silent",
"--data-raw", "${my_xml}",
"--url", "${zimbra_soap_url}"
[xml]${my_response} = & ${my_curl} ${curl_getfolder_args}
${my_response}.Envelope.Body.GetFolderResponse.folder.id
PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');
Try this out.
I had the exact same issue where jquery ajax only gave me cors issues on post requests where get requests worked fine - I tired everything above with no results. I had the correct headers in my server etc. Changing over to use XMLHTTPRequest instead of jquery fixed my issue immediately. No matter which version of jquery I used it didn't fix it. Fetch also works without issues if you don't need backward browser compatibility.
var xhr = new XMLHttpRequest()
xhr.open('POST', 'https://mywebsite.com', true)
xhr.withCredentials = true
xhr.onreadystatechange = function() {
if (xhr.readyState === 2) {// do something}
}
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(json)
Hopefully this helps anyone else with the same issues.
Every single persons suggestion to run a query in Oracle to find records whose specific field is just blank, (this is not including (null) or any other field just a blank line) did not work. I tried every single suggested code. Guess I will keep searching online.
*****UPDATE*****
I tried this and it worked, not sure why it would not work if < 1 but for some reason < 2 worked and only returned records whose field is just blank
select [columnName] from [tableName] where LENGTH(columnName) < 2 ;
I am guessing whatever script that was used to convert data over has left something in the field even though it shows blank, that is my guess anyways as to why the < 2 works but not < 1
However, if you have any other values in that column field that is less than two characters then you might have to come up with another solution. If there are not a lot of other characters then you can single them out.
Hope my solution helps someone else out there some day.
you can do something like this:
DataTable dt = new DataTable();
for (int i = 0; i < GridView1.Columns.Count; i++)
{
dt.Columns.Add("column"+i.ToString());
}
foreach (GridViewRow row in GridView1.Rows)
{
DataRow dr = dt.NewRow();
for(int j = 0;j<GridView1.Columns.Count;j++)
{
dr["column" + j.ToString()] = row.Cells[j].Text;
}
dt.Rows.Add(dr);
}
And that will show that it works.
GridView6.DataSource = dt;
GridView6.DataBind();
Here's a good example of something I just got working:
update cac c
set ga_meth_id = (
select cim.ga_meth_id
from cci ci, ccim cim
where ci.cus_id_key_n = cim.cus_id_key_n
and ci.cus_set_c = cim.cus_set_c
and ci.cus_set_c = c.cus_set_c
and ci.cps_key_n = c.cps_key_n
)
where exists (
select 1
from cci ci2, ccim cim2
where ci2.cus_id_key_n = cim2.cus_id_key_n
and ci2.cus_set_c = cim2.cus_set_c
and ci2.cus_set_c = c.cus_set_c
and ci2.cps_key_n = c.cps_key_n
)
I'm not sure whether it works with two syncing but for the --delete to work you also need to add the --recursive parameter as well.
import base64
from PIL import Image
import io
image = base64.b64decode(str('stringdata'))
fileName = 'test.jpeg'
imagePath = ('D:\\base64toImage\\'+"test.jpeg")
img = Image.open(io.BytesIO(image))
img.save(imagePath, 'jpeg')
I will suggest something totally different, we used it at work for many years ago on real computers and it worked perfect.
Boot both old and new machine on linux rescue Cd.
read the disk from one, and write it down to the other one, block by block, effectively copying the dist over the network.
You have to play around a little bit with the command line, but it worked so well that both machine complained about IP-conflict when they both booted :-) :-)
cat /dev/sda | ssh user@othermachine cat - > /dev/sda
After using session_destroy()
, the session is destroyed behind the scenes. For some reason this doesn't affect the values in $_SESSION
, which was already populated for this request, but it will be empty in future requests.
You can manually clear $_SESSION
if you so desire ($_SESSION = [];
).
If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto
Vertical centering is a bit tricker, but possible.
Font myFont = new Font("Serif", Font.BOLD, 12);
, then use a setFont method on your components like
JButton b = new JButton("Hello World");
b.setFont(myFont);
Here is the code to clean file name in python.
import unicodedata
def clean_name(name, replace_space_with=None):
"""
Remove invalid file name chars from the specified name
:param name: the file name
:param replace_space_with: if not none replace space with this string
:return: a valid name for Win/Mac/Linux
"""
# ref: https://en.wikipedia.org/wiki/Filename
# ref: https://stackoverflow.com/questions/4814040/allowed-characters-in-filename
# No control chars, no: /, \, ?, %, *, :, |, ", <, >
# remove control chars
name = ''.join(ch for ch in name if unicodedata.category(ch)[0] != 'C')
cleaned_name = re.sub(r'[/\\?%*:|"<>]', '', name)
if replace_space_with is not None:
return cleaned_name.replace(' ', replace_space_with)
return cleaned_name
The title bar can be removed in two ways as mentioned on the developer Android page:
In the manifest.xml
file:
Add the following in application
if you want to remove it for all the activities in an app:
<application android:theme="@android:style/Theme.Black.NoTitleBar">
Or for a particular activity:
<activity android:theme="@android:style/Theme.Black.NoTitleBar">
This error was showing up in the logs sometimes when I was using a buggy/crashy Cordova iOS version. It went away when I upgraded or downgraded cordova iOS.
The server I was connecting to was using TLSv1.2 SSL so I knew that was not the problem.
This traverses into the concept of REST and how the web was kinda intended on being used. There is an excellent podcast on Software Engineering radio that gives an in depth talk about the use of Get and Post.
Get is used to pull data from the server, where an update action shouldn't be needed. The idea being is that you should be able to use the same GET request over and over and have the same information returned. The URL has the get information in the query string, because it was meant to be able to be easily sent to other systems and people like a address on where to find something.
Post is supposed to be used (at least by the REST architecture which the web is kinda based on) for pushing information to the server/telling the server to perform an action. Examples like: Update this data, Create this record.
I wanted to create a new enumerable object or list and be able to add to it.
This comment changes everything. You can't add to a generic IEnumerable<T>
. If you want to stay with the interfaces in System.Collections.Generic
, you need to use a class that implements ICollection<T>
like List<T>
.
It's been a while since this question was asked. As of today (matplotlib 2.2.2
) and after some reading and trials, I think the best/proper way is the following:
Matplotlib has a module named ticker
that "contains classes to support completely configurable tick locating and formatting". To modify a specific tick from the plot, the following works for me:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
def update_ticks(x, pos):
if x == 0:
return 'Mean'
elif pos == 6:
return 'pos is 6'
else:
return x
data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=25, edgecolor='black')
ax.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
plt.show()
Caveat! x
is the value of the tick and pos
is its relative position in order in the axis. Notice that pos
takes values starting in 1
, not in 0
as usual when indexing.
In my case, I was trying to format the y-axis
of a histogram with percentage values. mticker
has another class named PercentFormatter
that can do this easily without the need to define a separate function as before:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
weights = np.ones_like(data) / len(data)
ax.hist(data, bins=25, weights=weights, edgecolor='black')
ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.0, decimals=1))
plt.show()
In this case xmax
is the data value that corresponds to 100%. Percentages are computed as x / xmax * 100
, that's why we fix xmax=1.0
. Also, decimals
is the number of decimal places to place after the point.
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
I'd definitely go with System.Data.SQLite (as previously mentioned: http://sqlite.phxsoftware.com/)
It is coherent with ADO.NET (System.Data.*), and is compiled into a single DLL. No sqlite3.dll - because the C code of SQLite is embedded within System.Data.SQLite.dll. A bit of managed C++ magic.
I don't know why
cfg_name_unique NOT LIKE '%categories%'
still returns those two values, but maybe exclude them explicit:
SELECT *
FROM developer_configurations_cms
WHERE developer_configurations_cms.cat_id = '1'
AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
AND developer_configurations_cms.cfg_name_unique NOT LIKE '%categories%'
AND developer_configurations_cms.cfg_name_unique NOT IN ('categories_posts', 'categories_news')
Please note that in upcoming version of C# which is 8, the answers are not true.
All the reference types are non-nullable by default
and you can actually do the following:
public string? MyNullableString;
this.MyNullableString = null; //Valid
However,
public string MyNonNullableString;
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning.
The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.
I had the same problem but got round it by setting AutoPostBack to true and in an update panel set the trigger to the dropdownlist control id and event name to SelectedIndexChanged e.g.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" enableViewState="true">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl1" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:DropDownList ID="ddl1" runat="server" ClientIDMode="Static" OnSelectedIndexChanged="ddl1_SelectedIndexChanged" AutoPostBack="true" ViewStateMode="Enabled">
<asp:ListItem Text="--Please select a item--" Value="0" />
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
On CentOS 7, the following works:
yum install php-soap
This will automatically create a soap.ini under /etc/php.d.
The extension itself for me lives in /usr/lib64/php/modules. You can confirm your extension directory by doing:
php -i | grep extension_dir
Once this has been installed, you can simply restart Apache using the new service manager like so:
systemctl restart httpd
Thanks to Matt Browne for the info about /etc/php.d.
It would be a lot more simple just to do this;
name = input("What's your name? ")
age = int(input("How old are you? "))
print ("Hi,{0} you will be 21 in {1} years.".format(name, 21 - age))`
I tried to do this with System.Environment back when I was learning extension methods and was not successful. The reason is, as others mention, because extension methods require an instance of the class.
You can use my plugin for this purpose.
JQuery:
(function() {_x000D_
$.pseudoElements = {_x000D_
length: 0_x000D_
};_x000D_
_x000D_
var setPseudoElement = function(parameters) {_x000D_
if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {_x000D_
for (var element of parameters.elements.get()) {_x000D_
if (!element.pseudoElements) element.pseudoElements = {_x000D_
styleSheet: null,_x000D_
before: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
after: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
id: null_x000D_
};_x000D_
_x000D_
var selector = (function() {_x000D_
if (element.pseudoElements.id !== null) {_x000D_
if (Number(element.getAttribute('data-pe--id')) !== element.pseudoElements.id) element.setAttribute('data-pe--id', element.pseudoElements.id);_x000D_
return '[data-pe--id="' + element.pseudoElements.id + '"]::' + parameters.pseudoElement;_x000D_
} else {_x000D_
var id = $.pseudoElements.length;_x000D_
$.pseudoElements.length++_x000D_
_x000D_
element.pseudoElements.id = id;_x000D_
element.setAttribute('data-pe--id', id);_x000D_
_x000D_
return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;_x000D_
};_x000D_
})();_x000D_
_x000D_
if (!element.pseudoElements.styleSheet) {_x000D_
if (document.styleSheets[0]) {_x000D_
element.pseudoElements.styleSheet = document.styleSheets[0];_x000D_
} else {_x000D_
var styleSheet = document.createElement('style');_x000D_
_x000D_
document.head.appendChild(styleSheet);_x000D_
element.pseudoElements.styleSheet = styleSheet.sheet;_x000D_
};_x000D_
};_x000D_
_x000D_
if (element.pseudoElements[parameters.pseudoElement].properties && element.pseudoElements[parameters.pseudoElement].index) {_x000D_
element.pseudoElements.styleSheet.deleteRule(element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
_x000D_
if (typeof parameters.argument === 'object') {_x000D_
parameters.argument = $.extend({}, parameters.argument);_x000D_
_x000D_
if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;_x000D_
_x000D_
element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;_x000D_
};_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in parameters.argument) {_x000D_
if (typeof parameters.argument[property] === 'function')_x000D_
element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();_x000D_
else_x000D_
element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];_x000D_
};_x000D_
_x000D_
for (var property in element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);_x000D_
} else if (parameters.argument !== undefined && parameters.property !== undefined) {_x000D_
if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;_x000D_
_x000D_
element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
element.pseudoElements[parameters.pseudoElement].properties = {};_x000D_
};_x000D_
_x000D_
if (typeof parameters.property === 'function')_x000D_
element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();_x000D_
else_x000D_
element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
};_x000D_
_x000D_
return $(parameters.elements);_x000D_
} else if (parameters.argument !== undefined && parameters.property === undefined) {_x000D_
var element = $(parameters.elements).get(0);_x000D_
_x000D_
var windowStyle = window.getComputedStyle(_x000D_
element, '::' + parameters.pseudoElement_x000D_
).getPropertyValue(parameters.argument);_x000D_
_x000D_
if (element.pseudoElements) {_x000D_
return $(parameters.elements).get(0).pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;_x000D_
} else {_x000D_
return windowStyle || null;_x000D_
};_x000D_
} else {_x000D_
console.error('Invalid values!');_x000D_
return false;_x000D_
};_x000D_
};_x000D_
_x000D_
$.fn.cssBefore = function(argument, property) {_x000D_
return setPseudoElement({_x000D_
elements: this,_x000D_
pseudoElement: 'before',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
};_x000D_
$.fn.cssAfter = function(argument, property) {_x000D_
return setPseudoElement({_x000D_
elements: this,_x000D_
pseudoElement: 'after',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
};_x000D_
})();_x000D_
_x000D_
$(function() {_x000D_
$('.element').cssBefore('content', '"New before!"');_x000D_
});
_x000D_
.element {_x000D_
width: 480px;_x000D_
margin: 0 auto;_x000D_
border: 2px solid red;_x000D_
}_x000D_
_x000D_
.element::before {_x000D_
content: 'Old before!';_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="element"></div>
_x000D_
The values should be specified, as in the normal function of jQuery.css
In addition, you can also get the value of the pseudo-element parameter, as in the normal function of jQuery.css:
console.log( $(element).cssBefore(parameter) );
JS:
(function() {_x000D_
document.pseudoElements = {_x000D_
length: 0_x000D_
};_x000D_
_x000D_
var setPseudoElement = function(parameters) {_x000D_
if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {_x000D_
if (!parameters.element.pseudoElements) parameters.element.pseudoElements = {_x000D_
styleSheet: null,_x000D_
before: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
after: {_x000D_
index: null,_x000D_
properties: null_x000D_
},_x000D_
id: null_x000D_
};_x000D_
_x000D_
var selector = (function() {_x000D_
if (parameters.element.pseudoElements.id !== null) {_x000D_
if (Number(parameters.element.getAttribute('data-pe--id')) !== parameters.element.pseudoElements.id) parameters.element.setAttribute('data-pe--id', parameters.element.pseudoElements.id);_x000D_
return '[data-pe--id="' + parameters.element.pseudoElements.id + '"]::' + parameters.pseudoElement;_x000D_
} else {_x000D_
var id = document.pseudoElements.length;_x000D_
document.pseudoElements.length++_x000D_
_x000D_
parameters.element.pseudoElements.id = id;_x000D_
parameters.element.setAttribute('data-pe--id', id);_x000D_
_x000D_
return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;_x000D_
};_x000D_
})();_x000D_
_x000D_
if (!parameters.element.pseudoElements.styleSheet) {_x000D_
if (document.styleSheets[0]) {_x000D_
parameters.element.pseudoElements.styleSheet = document.styleSheets[0];_x000D_
} else {_x000D_
var styleSheet = document.createElement('style');_x000D_
_x000D_
document.head.appendChild(styleSheet);_x000D_
parameters.element.pseudoElements.styleSheet = styleSheet.sheet;_x000D_
};_x000D_
};_x000D_
_x000D_
if (parameters.element.pseudoElements[parameters.pseudoElement].properties && parameters.element.pseudoElements[parameters.pseudoElement].index) {_x000D_
parameters.element.pseudoElements.styleSheet.deleteRule(parameters.element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
_x000D_
if (typeof parameters.argument === 'object') {_x000D_
parameters.argument = (function() {_x000D_
var cloneObject = typeof parameters.argument.pop === 'function' ? [] : {};_x000D_
_x000D_
for (var property in parameters.argument) {_x000D_
cloneObject[property] = parameters.argument[property];_x000D_
};_x000D_
_x000D_
return cloneObject;_x000D_
})();_x000D_
_x000D_
if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;_x000D_
_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;_x000D_
};_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in parameters.argument) {_x000D_
if (typeof parameters.argument[property] === 'function')_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();_x000D_
else_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];_x000D_
};_x000D_
_x000D_
for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);_x000D_
} else if (parameters.argument !== undefined && parameters.property !== undefined) {_x000D_
if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {_x000D_
var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;_x000D_
_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties = {};_x000D_
};_x000D_
_x000D_
if (typeof parameters.property === 'function')_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();_x000D_
else_x000D_
parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;_x000D_
_x000D_
var properties = '';_x000D_
_x000D_
for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {_x000D_
properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';_x000D_
};_x000D_
_x000D_
parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);_x000D_
};_x000D_
} else if (parameters.argument !== undefined && parameters.property === undefined) {_x000D_
var windowStyle = window.getComputedStyle(_x000D_
parameters.element, '::' + parameters.pseudoElement_x000D_
).getPropertyValue(parameters.argument);_x000D_
_x000D_
if (parameters.element.pseudoElements) {_x000D_
return parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;_x000D_
} else {_x000D_
return windowStyle || null;_x000D_
};_x000D_
} else {_x000D_
console.error('Invalid values!');_x000D_
return false;_x000D_
};_x000D_
};_x000D_
_x000D_
Object.defineProperty(Element.prototype, 'styleBefore', {_x000D_
enumerable: false,_x000D_
value: function(argument, property) {_x000D_
return setPseudoElement({_x000D_
element: this,_x000D_
pseudoElement: 'before',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
}_x000D_
});_x000D_
Object.defineProperty(Element.prototype, 'styleAfter', {_x000D_
enumerable: false,_x000D_
value: function(argument, property) {_x000D_
return setPseudoElement({_x000D_
element: this,_x000D_
pseudoElement: 'after',_x000D_
argument: argument,_x000D_
property: property_x000D_
});_x000D_
}_x000D_
});_x000D_
})();_x000D_
_x000D_
document.querySelector('.element').styleBefore('content', '"New before!"');
_x000D_
.element {_x000D_
width: 480px;_x000D_
margin: 0 auto;_x000D_
border: 2px solid red;_x000D_
}_x000D_
_x000D_
.element::before {_x000D_
content: 'Old before!';_x000D_
}
_x000D_
<div class="element"></div>
_x000D_
GitHub: https://github.com/yuri-spivak/managing-the-properties-of-pseudo-elements/
Incrementing on the answer by MarvinLabs to make it cleaner:
var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
It is not necessary to check the lower end of the range because the break
statements will cause execution to skip remaining cases, so by the time execution gets to checking e.g. (x < 9) we know the value must be 5 or greater.
Of course the output is only correct if the cases stay in the original order, and we assume integer values (as stated in the question) - technically the ranges are between 5 and 8.999999999999 or so since all numbers in js are actually double-precision floating point numbers.
If you want to be able to move the cases around, or find it more readable to have the full range visible in each case statement, just add a less-than-or-equal check for the lower range of each case:
var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x >= 5 && x < 9):
alert("between 5 and 8");
break;
case (x >= 9 && x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
Keep in mind that this adds an extra point of human error - someone may try to update a range, but forget to change it in both places, leaving an overlap or gap that is not covered. e.g. here the case of 8 will now not match anything when I just edit the case that used to match 8.
case (x >= 5 && x < 8):
alert("between 5 and 7");
break;
case (x >= 9 && x < 12):
alert("between 9 and 11");
break;
I aso find this extremely confusing. as @EricMartinez points out Renderer2 listen() returns the function to remove the listener:
ƒ () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); }
If i´m adding a listener
this.listenToClick = this.renderer.listen('document', 'click', (evt) => {
alert('Clicking the document');
})
I´d expect my function to execute what i intended, not the total opposite which is remove the listener.
// I´d expect an alert('Clicking the document');
this.listenToClick();
// what you actually get is removing the listener, so nothing...
In the given scenario, It´d actually make to more sense to name it like:
// Add listeners
let unlistenGlobal = this.renderer.listen('document', 'click', (evt) => {
console.log('Clicking the document', evt);
})
let removeSimple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
console.log('Clicking the button', evt);
});
There must be a good reason for this but in my opinion it´s very misleading and not intuitive.
This is how I managed to sort and populate:
Model.find()
.sort('date', -1)
.populate('authors')
.exec(function(err, docs) {
// code here
})
The only guaranteed secure method of retrieving the current domain is to store it in a secure location yourself.
Most frameworks take care of storing the domain for you, so you will want to consult the documentation for your particular framework. If you're not using a framework, consider storing the domain in one of the following places:
Secure methods of storing the domain | Used By |
---|---|
A config file | Joomla, Drupal/Symfony |
The database | WordPress |
An environmental variable | Laravel |
A service registry | Kubernetes DNS |
Hackers can make the following variables output whatever domain they want. This can lead to cache poisoning and barely noticeable phishing attacks.
$_SERVER['HTTP_HOST']
This gets the domain from the request headers which are open to manipulation by hackers. Same with:
$_SERVER['SERVER_NAME']
This one can be made better if the Apache setting usecanonicalname is turned off; in which case $_SERVER['SERVER_NAME']
will no longer be allowed to be populated with arbitrary values and will be secure. This is, however, non-default and not as common of a setup.
Below is how you can get the current domain in the following frameworks/systems:
WordPress
$urlparts = parse_url(home_url());
$domain = $urlparts['host'];
If you're constructing a URL in WordPress, just use home_url or site_url, or any of the other URL functions.
Laravel
request()->getHost()
The request()->getHost
function is inherited from Symfony, and has been secure since the 2013 CVE-2013-4752 was patched.
Drupal
The installer does not yet take care of making this secure (issue #2404259). But in Drupal 8 there is documentation you can you can follow at Trusted Host Settings to secure your Drupal installation after which the following can be used:
\Drupal::request()->getHost();
Other frameworks
Feel free to edit this answer to include how to get the current domain in your favorite framework. When doing so, please include a link to the relevant source code or to anything else that would help me verify that the framework is doing things securely.
Exploitation examples:
Cache poisoning can happen if a botnet continuously requests a page using the wrong hosts header. The resulting HTML will then include links to the attackers website where they can phish your users. At first the malicious links will only be sent back to the hacker, but if the hacker does enough requests, the malicious version of the page will end up in your cache where it will be distributed to other users.
A phishing attack can happen if you store links in the database based on the hosts header. For example, let say you store the absolute URL to a user's profiles on a forum. By using the wrong header, a hacker could get anyone who clicks on their profile link to be sent a phishing site.
Password reset poisoning can happen if a hacker uses a malicious hosts header when filling out the password reset form for a different user. That user will then get an email containing a password reset link that leads to a phishing site. Another more complex form of this skips the user having to do anything by getting the email to bounce and resend to one of the hacker's SMTP servers (for example CVE-2017-8295.)
Here are some more malicious examples
Additional Caveats and Notes:
$_SERVER['SERVER_NAME']
is populated with the same header $_SERVER['HTTP_HOST']
would have used anyways (plus the port). This is Apache's default setup. If you or devops turns this on then you're okay -- ish -- but do you really want to rely on a separate team, or yourself three years in the future, to keep what would appear to be a minor configuration at a non-default value? Even though this makes things secure, I would caution against relying on this setup.$_SERVER['SERVER_NAME']
will not return the current domain, but will return the value of the serverName directive.Little Rant:
This question received hundreds of thousands of views without a single mention of the security problems at hand! It shouldn't be this way, but just because a Stack Overflow answer is popular, that doesn't mean it is secure.
You can use inline styling to limit the height:
<img src="" class="img-responsive" alt="" style="max-height: 400px;">
Chrome print is usually an extension page so there is no dom attachment happening in your existing page. You can trigger the print command using command line apis(window.print()) but then they have not provided apis for closing it becoz of vary reason like choosing print options, print machine,count etc.
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
You are missing a comma in your statement.
Try this:
data[data[, "Var1"]>10, ]
Or:
data[data$Var1>10, ]
Or:
subset(data, Var1>10)
As an example, try it on the built-in dataset, mtcars
data(mtcars)
mtcars[mtcars[, "mpg"]>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
mtcars[mtcars$mpg>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
subset(mtcars, mpg>25)
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
I've got a similar message and my problem were some proxy preferences in my settings.xml. So i disabled them and everything works fine.
This works for me (Excel 2013):
Public Sub StartExeWithArgument()
Dim strProgramName As String
Dim strArgument As String
strProgramName = "C:\Program Files\Test\foobar.exe"
strArgument = "/G"
Call Shell("""" & strProgramName & """ """ & strArgument & """", vbNormalFocus)
End Sub
With inspiration from here https://stackoverflow.com/a/3448682.
In Safari, you can use synchronous requests to avoid the browser to display the popup. Of course, synchronous requests should only be used in this case to check user credentials... You can use a such request before sending the actual request which may cause a bad user experience if the content (sent or received) is quite heavy.
var xmlhttp=new XMLHttpRequest;
xmlhttp.withCredentials=true;
xmlhttp.open("POST",<YOUR UR>,false,username,password);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
I found a post suggesting a solution for that. It's about to run:
svn resolve --accept working <YourPath>
which will claim the local version files as OK.
You can run it for single file or entire project catalogues.
I prefer creating a reverse plug-in eg
jQuery.fn.reverse = function(fn) {
var i = this.length;
while(i--) {
fn.call(this[i], i, this[i])
}
};
Usage eg:
$('#product-panel > div').reverse(function(i, e) {
alert(i);
alert(e);
});
labelname.ForeColor = Color.Colorname;
If you want the View
, make sure to access the itemView
property of the ViewHolder like so: myRecyclerView.findViewHolderForAdapterPosition(pos).itemView;
Check out Smaz:
Smaz is a simple compression library suitable for compressing very short strings.
I've found the best implementation. It's in the Google I/O 2014 app.
They use the same approach as Kevin's. If you can abstract yourself from all unneeded stuff in I/O app, you could extract everything you need and it is assured by Google that it's a correct usage of navigation drawer pattern.
Each activity optionally has a DrawerLayout
as its main layout. The interesting part is how the navigation to other screens is done. It is implemented in BaseActivity
like this:
private void goToNavDrawerItem(int item) {
Intent intent;
switch (item) {
case NAVDRAWER_ITEM_MY_SCHEDULE:
intent = new Intent(this, MyScheduleActivity.class);
startActivity(intent);
finish();
break;
This differs from the common way of replacing current fragment by a fragment transaction. But the user doesn't spot a visual difference.
frame.setContentPane(newContents());
frame.revalidate(); // frame.pack() if you want to resize.
Remember, Java use 'copy reference by value' argument passing. So changing a variable wont change copies of the reference passed to other methods.
Also note JFrame
is very confusing in the name of usability. Adding a component or setting a layout (usually) performs the operation on the content pane. Oddly enough, getting the layout really does give you the frame's layout manager.
Compile :
This is the phase where Angular actually compiles your directive. This compile function is called just once for each references to the given directive. For example, say you are using the ng-repeat directive. ng-repeat will have to look up the element it is attached to, extract the html fragment that it is attached to and create a template function.
If you have used HandleBars, underscore templates or equivalent, its like compiling their templates to extract out a template function. To this template function you pass data and the return value of that function is the html with the data in the right places.
The compilation phase is that step in Angular which returns the template function. This template function in angular is called the linking function.
Linking phase :
The linking phase is where you attach the data ( $scope ) to the linking function and it should return you the linked html. Since the directive also specifies where this html goes or what it changes, it is already good to go. This is the function where you want to make changes to the linked html, i.e the html that already has the data attached to it. In angular if you write code in the linking function its generally the post-link function (by default). It is kind of a callback that gets called after the linking function has linked the data with the template.
Controller :
The controller is a place where you put in some directive specific logic. This logic can go into the linking function as well, but then you would have to put that logic on the scope to make it "shareable". The problem with that is that you would then be corrupting the scope with your directives stuff which is not really something that is expected. So what is the alternative if two Directives want to talk to each other / co-operate with each other? Ofcourse you could put all that logic into a service and then make both these directives depend on that service but that just brings in one more dependency. The alternative is to provide a Controller for this scope ( usually isolate scope ? ) and then this controller is injected into another directive when that directive "requires" the other one. See tabs and panes on the first page of angularjs.org for an example.
Add the framework in Embedded Binaries
Then Clean and Build.
I had the same thing happen to me as Tiguero (thank you for your answer, it gave me hope), but here is a way to get rid of the "valid signing identity not found" error without having to delete all your provisioning profiles.
If you are on a new system and cannot retrieve your keys from another system, you do indeed have to delete and regenerate new Development and Distribution certificates for Xcode. You can do this via Xcode, or the old-fashioned way using Keychain Access.
Then what you can do is go into Provisioning
, and in each tab, Development
, and Distribution
, click Edit
next to the profile you want to update, and then Modify
.
You will see a list of certificates, and you must check off the box next to the one you just made, then Submit
.
Once you do this, go into your Xcode (I'm using 4.3.3)
Organizer > Devices > Library > Provisioning Profiles
where you are getting the error message, and click Refresh
. Once you answer the prompt to enter your developer login, Organizer
will re-download the profiles, and the error message should go away.
It is a bad idea to select * from anything, period. This is why SSMS adds every field name, even if there are hundreds, instead of select *. It is extremely inefficient regardless of how large the table is. If you don't know what the fields are, its still more efficient to pull them out of the INFORMATION_SCHEMA database than it is to select *.
A better query would be:
SELECT
COLUMN_NAME,
Case
When DATA_TYPE In ('varchar', 'char', 'nchar', 'nvarchar', 'binary')
Then convert(varchar(MAX), CHARACTER_MAXIMUM_LENGTH)
When DATA_TYPE In ('numeric', 'int', 'smallint', 'bigint', 'tinyint')
Then convert(varchar(MAX), NUMERIC_PRECISION)
When DATA_TYPE = 'bit'
Then convert(varchar(MAX), 1)
When DATA_TYPE IN ('decimal', 'float')
Then convert(varchar(MAX), Concat(Concat(NUMERIC_PRECISION, ', '), NUMERIC_SCALE))
When DATA_TYPE IN ('date', 'datetime', 'smalldatetime', 'time', 'timestamp')
Then ''
End As DATALEN,
DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
Where
TABLE_NAME = ''
I used this for breadcrums in the category template page:
$cat_obj = $wp_query->get_queried_object();
$thiscat_id = $cat_obj->term_id;
$thiscat = get_category($thiscat_id);
$parentcat = get_category($thiscat->parent);
Set the Credentials property before sending the message.
If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.
But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application
class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application
instead.
I'd suggest reading this article about context to better figure it out what context you need.
An alternative way without the [<-
function:
A sample data frame dat
(shamelessly copied from @Chase's answer):
dat
x y
1 0 2
2 1 2
3 1 1
4 2 1
5 0 0
Zeroes can be replaced with NA
by the is.na<-
function:
is.na(dat) <- !dat
dat
x y
1 NA 2
2 1 2
3 1 1
4 2 1
5 NA NA
Pyspark does include a dropDuplicates()
method, which was introduced in 1.4. https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.dropDuplicates
>>> from pyspark.sql import Row
>>> df = sc.parallelize([ \
... Row(name='Alice', age=5, height=80), \
... Row(name='Alice', age=5, height=80), \
... Row(name='Alice', age=10, height=80)]).toDF()
>>> df.dropDuplicates().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 5| 80|Alice|
| 10| 80|Alice|
+---+------+-----+
>>> df.dropDuplicates(['name', 'height']).show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 5| 80|Alice|
+---+------+-----+
joshrathke is right.
In angular.io docs is written that URLSearchParams from @angular/http is deprecated. Instead you should use HttpParams from @angular/common/http. The code is quite similiar and identical to what joshrathke have written. For multiple parameters that are saved for instance in a object like
{
firstParam: value1,
secondParam, value2
}
you could also do
for(let property in objectStoresParams) {
if(objectStoresParams.hasOwnProperty(property) {
params = params.append(property, objectStoresParams[property]);
}
}
If you need inherited properties then remove the hasOwnProperty accordingly.
Lets say you have 17 mod 6.
what total of 6 will get you the closest to 17, it will be 12 because if you go over 12 you will have 18 which is more that the question of 17 mod 6. You will then take 12 and minus from 17 which will give you your answer, in this case 5.
17 mod 6=5
I used all above changes but still I was getting same issue on my web application.
Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.
They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application is able to download the file.
Hope this answer will help someone.This is what worked for me
I am surprised that none of the answers mentioned the insertAdjacentHTML()
method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.
Basic usage:
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');
You might have a lower project language level than your JDK.
Check if: "Projeckt structure/project/Project-> language level" is lower than your JDK. I had the same problem with JDK 9 and the language level was per default set to 6.
I set the Project Language Level to 9 and everything worked fine after that.
You might have the same issue.
The query below returns the timezone of the current session.
select timediff(now(),convert_tz(now(),@@session.time_zone,'+00:00'));
client.user.setStatus('dnd', 'Made by KwinkyWolf')
And change 'dnd' to whatever status you want it to have. And then the next field 'Made by KwinkyWolf' is where you change the game. Hope this helped :)
List of status':
Not sure if they're still the same, or if there's more but hope that helped too :)
This happens because the provisioning profile can't find the file for the certificate it is linked to.
To fix:
The error should be gone now.
Problem
I was running into the same error message while calling a third party API from my ASP.NET Core MVC project.
Could not establish secure channel for SSL/TLS with authority '{base_url_of_WS}'.
Solution
It turned out that the third party API's server required TLS 1.2. To resolve this issue, I added the following line of code to my controller's constructor:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
*In all instances the # refers to the cell number
You really don't need the datedif functions; for example:
I'm working on a spreadsheet that tracks benefit eligibility for employees.
I have their hire dates in the "A" column and in column B is =(TODAY()-A#)
And you just format the cell to display a general number instead of date.
It also works very easily the other way: I also converted that number into showing when the actual date is that they get their benefits instead of how many days are left, and that is simply
=(90-B#)+TODAY()
Just make sure you're formatting cells as general numbers or dates accordingly.
Hope this helps.
Yes. In the javascript code:
window.location.href = "http://new.website.com/that/you/want_to_go_to.html";
The concept of passing data from parent to child and vice versa is explained.
import React, { Component } from "react";_x000D_
import ReactDOM from "react-dom";_x000D_
_x000D_
// taken refrence from https://gist.github.com/sebkouba/a5ac75153ef8d8827b98_x000D_
_x000D_
//example to show how to send value between parent and child_x000D_
_x000D_
// props is the data which is passed to the child component from the parent component_x000D_
_x000D_
class Parent extends Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
_x000D_
this.state = {_x000D_
fieldVal: ""_x000D_
};_x000D_
}_x000D_
_x000D_
onUpdateParent = val => {_x000D_
this.setState({_x000D_
fieldVal: val_x000D_
});_x000D_
};_x000D_
_x000D_
render() {_x000D_
return (_x000D_
// To achieve the child-parent communication, we can send a function_x000D_
// as a Prop to the child component. This function should do whatever_x000D_
// it needs to in the component e.g change the state of some property._x000D_
//we are passing the function onUpdateParent to the child_x000D_
<div>_x000D_
<h2>Parent</h2>_x000D_
Value in Parent Component State: {this.state.fieldVal}_x000D_
<br />_x000D_
<Child onUpdate={this.onUpdateParent} />_x000D_
<br />_x000D_
<OtherChild passedVal={this.state.fieldVal} />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
class Child extends Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
_x000D_
this.state = {_x000D_
fieldValChild: ""_x000D_
};_x000D_
}_x000D_
_x000D_
updateValues = e => {_x000D_
console.log(e.target.value);_x000D_
this.props.onUpdate(e.target.value);_x000D_
// onUpdateParent would be passed here and would result_x000D_
// into onUpdateParent(e.target.value) as it will replace this.props.onUpdate_x000D_
//with itself._x000D_
this.setState({ fieldValChild: e.target.value });_x000D_
};_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
<h4>Child</h4>_x000D_
<input_x000D_
type="text"_x000D_
placeholder="type here"_x000D_
onChange={this.updateValues}_x000D_
value={this.state.fieldVal}_x000D_
/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
class OtherChild extends Component {_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
<h4>OtherChild</h4>_x000D_
Value in OtherChild Props: {this.props.passedVal}_x000D_
<h5>_x000D_
the child can directly get the passed value from parent by this.props{" "}_x000D_
</h5>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
This is with jQuery.
$('#selectFormElement').change( function() {
$('#hiddenFormElement').val('newValue');
} );
In the html
<select id="selectFormElement" name="..."> ... </select>
<input type="hidden" name="..." id="hiddenFormElement" />
Here is the answer from @mvanle, converted to Scala:
scala> val Array(javaVerPrefix, javaVerMajor, javaVerMinor, _, _) = System.getProperty("java.runtime.version").split("\\.|_|-b")
javaVerPrefix: String = 1
javaVerMajor: String = 8
javaVerMinor: String = 0
self.view.backgroundColor = UIColor.redColor()
In Swift 3:
self.view.backgroundColor = UIColor.red
If you have not made this working, you better put
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)
into one file and run it.
there is component ready to use (rc5 compatible)
ng2-steps
which uses Compiler
to inject component to step container
and service for wiring everything together (data sync)
import { Directive , Input, OnInit, Compiler , ViewContainerRef } from '@angular/core';
import { StepsService } from './ng2-steps';
@Directive({
selector:'[ng2-step]'
})
export class StepDirective implements OnInit{
@Input('content') content:any;
@Input('index') index:string;
public instance;
constructor(
private compiler:Compiler,
private viewContainerRef:ViewContainerRef,
private sds:StepsService
){}
ngOnInit(){
//Magic!
this.compiler.compileComponentAsync(this.content).then((cmpFactory)=>{
const injector = this.viewContainerRef.injector;
this.viewContainerRef.createComponent(cmpFactory, 0, injector);
});
}
}
If you are using vagrant ensure that the file is on the server and then use the path to the file. e.g if the file is stored in the public folder you will have
sql> source /var/www/public/xxx.sql
Where xxx is the name of the file
You can also do this
d = [20, 30, 10]
e = Array.from(d)
e.sort()
This way d will not get mutated.
function sorted(arr) {
temp = Array.from(arr)
return temp.sort()
}
//Use it like this
x = [20, 10, 100]
console.log(sorted(x))
I believe you could try something like this:
var postData =
{
"bid":bid,
"location1":"1","quantity1":qty1,"price1":price1,
"location2":"2","quantity2":qty2,"price2":price2,
"location3":"3","quantity3":qty3,"price3":price3
}
$.ajax({
type: "POST",
dataType: "json",
url: "add_cart.php",
data: postData,
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
the json encode should happen automatically, and a dump of your post should give you something like:
array(
"bid"=>bid,
"location1"=>"1",
"quantity1"=>qty1,
"price1"=>price1,
"location2"=>"2",
"quantity2"=>qty2,
"price2"=>price2,
"location3"=>"3",
"quantity3"=>qty3,
"price3"=>price3
)
Keep the secret in firebase database
and get from it when app starts ,
It is far better than calling a web service .
Please be VERY careful with using the registry key approach. These are machine-wide keys and forcibily migrate ALL applications to .NET 4.0.
Many products do not work if forcibily migrated and this is a testing aid and not a production quality mechanism. Visual Studio 2008 and 2010, MSBuild, turbotax, and a host of websites, SharePoint and so on should not be automigrated.
If you need to use PowerShell with 4.0, this should be done on a per-application basis with a configuration file, you should check with the PowerShell team on the precise recommendation. This is likely to break some existing PowerShell commands.
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);
Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});
Implement your own extension of DataGridViewTextBoxCell and override Paint method like this:
class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
if (value != null)
{
if ((bool) value)
{
cellStyle.BackColor = Color.LightGreen;
}
else
{
cellStyle.BackColor = Color.OrangeRed;
}
}
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}
}
Then in the code set CellTemplate property of your column to instance of your class
columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});
Very similar to this question, and I would suggest the same formula in column D, albeit a few changes to the ranges:
=IFERROR(VLOOKUP(C1, A:B, 2, 0), "")
If you wanted to use match, you'd have to use INDEX
as well, like so:
=IFERROR(INDEX(B:B, MATCH(C1, A:A, 0)), "")
but this is really lengthy to me and you need to know how to properly use two functions (or three, if you don't know how IFERROR
works)!
Note: =IFERROR()
can be a substitute of =IF()
and =ISERROR()
in some cases :)
It is also possible to create a div element in the following way:
var my_div = document.createElement('div');
add class
my_div.classList.add('col-10');
also can perform append()
and appendChild()
You have not defined a method around your code.
import java.io.*;
public class details
{
public static void main( String[] args )
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
In this case, I have assumed that you want your code to be executed in the main
method of the class. It is, of course, possible that this code goes in any other method.
This is what I do to retain type info:
class Helper {
public static createRaw<T>(TCreator: { new (): T; }, data: any): T
{
return Object.assign(new TCreator(), data);
}
public static create<T>(TCreator: { new (): T; }, data: T): T
{
return this.createRaw(TCreator, data);
}
}
...
it('create helper', () => {
class A {
public data: string;
}
class B {
public data: string;
public getData(): string {
return this.data;
}
}
var str = "foobar";
var a1 = Helper.create<A>(A, {data: str});
expect(a1 instanceof A).toBeTruthy();
expect(a1.data).toBe(str);
var a2 = Helper.create(A, {data: str});
expect(a2 instanceof A).toBeTruthy();
expect(a2.data).toBe(str);
var b1 = Helper.createRaw(B, {data: str});
expect(b1 instanceof B).toBeTruthy();
expect(b1.data).toBe(str);
expect(b1.getData()).toBe(str);
});
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
php artisan dump-autoload
Notepad++ only has column editing. This is not completely the same as multiple cursors.
Sublime Text has a marvelous implementation of this, might be worth checking out...
It's a relatively new editor (2011) that is gaining popularity quite fast:
http://www.google.com/trends/explore#q=Notepad%2B%2B%2C%20Sublime%20Text&cmpt=q
Edit: Apparently somewhere around Notepad++ version 6.x multi-cursor editing got added, but there are still a few more advanced features for it in Sublime, like "select next occurrence".
The default
keyword works for me:
mysql> insert into user_table (user_id, ip, partial_ip, source, user_edit_date, username) values
(default, '39.48.49.126', null, 'user signup page', now(), 'newUser');
---
Query OK, 1 row affected (0.00 sec)
I'm running mysql --version
5.1.66:
mysql Ver 14.14 Distrib **5.1.66**, for debian-linux-gnu (x86_64) using readline 6.1
On a recent project we had the challenge of working with and manipulating a large collection of data. Our client provided us with a 50 CSV files ranging from 30 MB to 350 MB in size and all in all containing approximately 20 million rows of data and 15 columns of data. Our end goal was to import and manipulate the data into a MySQL relational database to be used to power a front-end PHP script that we also developed. Now, working with a dataset this large or larger is not the simplest of tasks and in working on it we wanted to take a moment to share some of the things you should consider and know when working with large datasets like this.
Analyze Your Dataset Pre-Import
I can’t stress this first step enough! Make sure that you take the time to analyze the data you are working with before importing it at all. Getting an understand of what all of the data represents, what columns related to what and what type of manipulation you need to will end up saving you time in the long run.
LOAD DATA INFILE is Your Friend
Importing large data files like the ones we worked with (and larger ones) can be tough to do if you go ahead and try a regular CSV insert via a tool like PHPMyAdmin. Not only will it fail in many cases because your server won’t be able to handle a file upload as large as some of your data files due to upload size restrictions and server timeouts, but even if it does succeed, the process could take hours depending our your hardware. The SQL function LOAD DATA INFILE was created to handle these large datasets and will significantly reduce the time it takes to handle the import process. Of note, this can be executed through PHPMyAdmin, but you may still have file upload issues. In that case you can upload the files manually to your server and then execute from PHPMyAdmin (see their manual for more info) or execute the command via your SSH console (assuming you have your own server)
LOAD DATA INFILE '/mylargefile.csv' INTO TABLE temp_data FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'
MYISAM vs InnoDB
Large or small database it’s always good to take a little time to consider which database engine you are going to use for your project. The two main engines you are going to read about are MYISAM and InnoDB and each has their own benefits and drawbacks. In brief the things to consider (in general) are as follows:
MYISAM
InnoDB
Plan Your Design Carefully
MySQL AnalyzeYour databases design/structure is going to be a large factor in how it performs. Take your time when it comes to planning out the different fields and analyze the data to figure out what the best field types, defaults and field length. You want to accommodate for the right amounts of data and try to avoid varchar columns and overly large data types when the data doesn’t warrant it. As an additional step after you are done with your database, you make want to see what MySQL suggests as field types for all of your different fields. You can do this by executing the following SQL command:
ANALYZE TABLE my_big_table
The result will be a description of each columns information along with a recommendation for what type of datatype it should be along with a proper length. Now you don’t necessarily need to follow the recommendations as they are based solely on existing data, but it may help put you on the right track and get you thinking
To Index or Not to Index
For a dataset as large as this it’s infinitely important to create proper indexes on your data based off of what you need to do with the data on the front-end, BUT if you plan to manipulate the data beforehand refrain from placing too many indexes on the data. Not only will it will make your SQL table larger, but it will also slow down certain operations like column additions, subtractions and additional indexing. With our dataset we needed to take the information we just imported and break it into several different tables to create a relational structure as well as take certain columns and split the information into additional columns. We placed an index on the bare minimum of columns that we knew would help us with the manipulation. All in all, we took 1 large table consisting of 20 million rows of data and split its information into 6 different tables with pieces of the main data in them along with newly created data based off the existing content. We did all of this by writing small PHP scripts to parse and move the data around.
Finding a Balance
A big part of working with large databases from a programming perspective is speed and efficiency. Getting all of the data into your database is great, but if the script you write to access the data is slow, what’s the point? When working with large datasets it’s extremely important that you take the time to understand all of the queries that your script is performing and to create indexes to help those queries where possible. One such way to analyze what your queries are doing is by executing the following SQL command:
EXPLAIN SELECT some_field FROM my_big_table WHERE another_field='MyCustomField';
By adding EXPLAIN to the start of your query MySQL will spit out information describing what indexes it tried to use, did use and how it used them. I labeled this point ‘Finding a balance’ because although indexes can help your script perform faster, they can just as easily make it run slower. You need to make sure you index what is needed and only what is needed. Every index consumes disk space and adds to the overhead of the table. Every time you make an edit to your table, you have to rebuild the index for that particular row and the more indexes you have on those rows, the longer it will take. It all comes down to making smart indexes, efficient SQL queries and most importantly benchmarking as you go to understand what each of your queries is doing and how long it’s taking to do it.
Index On, Index Off
As we worked on the database and front-end script, both the client and us started to notice little things that needed changing and that required us to make changes to the database. Some of these changes involved adding/removing columns and changing the column types. As we had already setup a number of indexes on the data, making any of these changes required the server to do some serious work to keep the indexes in place and handle any modifications. On our small VPS server, some of the changes were taking upwards of 6 hours to complete…certainly not helpful to us being able to do speedy development. The solution? Turn off indexes! Sometimes it’s better to turn the indexes off, make your changes and then turn the indexes back on….especially if you have a lot of different changes to make. With the indexes off, the changes took a matter of seconds to minutes versus hours. When we were happy with our changes we simply turned our indexes back on. This of course took quite some time to re-index everything, but it was at least able to re-index everything all at once, reducing the overall time needed to make these changes one by one. Here’s how to do it:
ALTER TABLE my_big_table DISABLE KEY
ALTER TABLE my_big_table ENABLE KEY
Give MySQL a Tune-Up
Don’t neglect your server when it comes to making your database and script run quickly. Your hardware needs just as much attention and tuning as your database and script does. In particular it’s important to look at your MySQL configuration file to see what changes you can make to better enhance its performance. A great little tool that we’ve come across is the MySQL Tuner http://mysqltuner.com/ . It’s a quick little Perl script that you can download right to your server and run via SSH to see what changes you might want to make to your configuration. Note that you should actively use your front-end script and database for several days before running the tuner so that the tuner has data to analyze. Running it on a fresh server will only provide minimal information and tuning options. We found it great to use the tuner script every few days for the two weeks to see what recommendations it would come up with and at the end we had significantly increased the databases performance.
Don’t be Afraid to Ask
Working with SQL can be challenging to begin with and working with extremely large datasets only makes it that much harder. Don’t be afraid to go to professionals who know what they are doing when it comes to large datasets. Ultimately you will end up with a superior product, quicker development and quicker front-end performance. When it comes to large databases sometimes it’s take a professionals experienced eyes to find all the little caveats that could be slowing your databases performance.
I am new to the Android/Java world and was surprised to find out here (unless I don't understand what I read) that modal dialogs don't work. For some very obscure reasons for me at the moment, I got this "ShowMessage" equivalent with an ok button that works on my tablet in a very modal manner.
From my TDialogs.java module:
class DialogMes
{
AlertDialog alertDialog ;
private final Message NO_HANDLER = null;
public DialogMes(Activity parent,String aTitle, String mes)
{
alertDialog = new AlertDialog.Builder(parent).create();
alertDialog.setTitle(aTitle);
alertDialog.setMessage(mes) ;
alertDialog.setButton("OK",NO_HANDLER) ;
alertDialog.show() ;
}
}
Here's part of the test code:
public class TestDialogsActivity extends Activity implements DlgConfirmEvent
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btShowMessage = (Button) findViewById(R.id.btShowMessage);
btShowMessage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
DialogMes dlgMes = new DialogMes( TestDialogsActivity.this,"Message","life is good") ;
}
});
I also implemented a modal Yes/No dialog following the interface approach suggested above by JohnnyBeGood, and it works pretty good too.
Correction:
My answer is not relevant to the question that I misunderstood. For some reason, I interpreted M. Romain Guy "you don't want to do that" as a no no to modal dialogs. I should have read: "you don't want to do that...this way".
I apologize.
Adding one more possible issue causing this: the formula was wrong because I was using the wrong list separator according to my locale.
Using CultureInfo.CurrentCulture.TextInfo.ListSeparator;
corrected the issue.
Note that the exception was thrown on the following line of code...
Now in FileZilla, create a new Account 1. Host is the FTP Address - e.g. ftp.somewhere.com 2. Protocol is "SFTP-SSH File Transfer Protocol" 3. User ID is your Bluehost User Id 4. Password is your Bluehost Password 5. Click "Connect" to establish a connection with Directory Listing!
This resolve the issue with 3.10 for me. And I'm glad to have the Secure Access for all of my future file transfers. It should prevent security issues in the future.
I am on Ubuntu 18.04 and got the same error, was worried for weeks too. Finally realized that gpg2 is not pointing towards anything. So simply run
git config --global gpg.program gpg
And tada, it works like charm.
Your commits will now have verified tag with them.
Note that you can deploy remotely using HTTP.
http://localhost:8080/manager/deploy
Upload the web application archive (WAR) file that is specified as the request data in this HTTP PUT request, install it into the appBase directory of our corresponding virtual host, and start it using the war file name without the .war extension as the path. The application can later be undeployed (and the corresponding application directory removed) by use of the /undeploy. To deploy the ROOT web application (the application with a context path of "/"), name the war ROOT.war.
and if you're using Ant you can do this using Tomcat Ant tasks (perhaps following a successful build).
To determine which path you then hit on your browser, you need to know the port Tomcat is running on, the context and your servlet path. See here for more details.
Cited from https://unix.stackexchange.com/questions/50177/birth-is-empty-on-ext4/131347#131347 , the following shellscript would work to get creation time:
get_crtime() {
for target in "${@}"; do
inode=$(stat -c %i "${target}")
fs=$(df "${target}" | tail -1 | awk '{print $1}')
crtime=$(sudo debugfs -R 'stat <'"${inode}"'>' "${fs}" 2>/dev/null | grep -oP 'crtime.*--\s*\K.*')
printf "%s\t%s\n" "${target}" "${crtime}"
done
}
Take a look at launch4j
Here my static version:
public static void playAssetSound(Context context, String soundFileName) {
try {
MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor descriptor = context.getAssets().openFd(soundFileName);
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mediaPlayer.prepare();
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
$("input#A").attr("myattr") == null
Guidelines from MSDN: Using decimal, float, and real Data
The default maximum precision of numeric and decimal data types is 38. In Transact-SQL, numeric is functionally equivalent to the decimal data type. Use the decimal data type to store numbers with decimals when the data values must be stored exactly as specified.
The behavior of float and real follows the IEEE 754 specification on approximate numeric data types. Because of the approximate nature of the float and real data types, do not use these data types when exact numeric behavior is required, such as in financial applications, in operations involving rounding, or in equality checks. Instead, use the integer, decimal, money, or smallmoney data types. Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators. It is best to limit float and real columns to > or < comparisons.
Please try this, this will export your data table data's faster to excel.
Note: Range "FW", that I have hard coded is because I had 179 columns.
public void UpdateExcelApplication(SqlDataTable dataTable)
{
var objects = new string[dataTable.Rows.Count, dataTable.Columns.Count];
var rowIndex = 0;
foreach (DataRow row in dataTable.Rows)
{
var colIndex = 0;
foreach (DataColumn column in dataTable.Columns)
{
objects[rowIndex, colIndex++] = Convert.ToString(row[column]);
}
rowIndex++;
}
var range = this.workSheet.Range[$"A3:FW{dataTable.Rows.Count + 2}"];
range.Value = objects;
this.workSheet.Columns.AutoFit();
this.workSheet.Rows.AutoFit();
}
The simplest way to do this is to install Json.NET
from nuget and add the [JsonIgnore]
attribute to the virtual property in the class, for example:
public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> Project_ID { get; set; }
[JsonIgnore]
public virtual Project Project { get; set; }
Although these days, I create a model with only the properties I want passed through so it's lighter, doesn't include unwanted collections, and I don't lose my changes when I rebuild the generated files...
Below is a python program to find all combinations of money. This is a dynamic programming solution with order(n) time. Money is 1,5,10,25
We traverse from row money 1 to row money 25 (4 rows). Row money 1 contains the count if we only consider money 1 in calculating the number of combinations. Row money 5 produces each column by taking the count in row money r for the same final money plus the previous 5 count in its own row (current position minus 5). Row money 10 uses row money 5, which contains counts for both 1,5 and adds in the previous 10 count (current position minus 10). Row money 25 uses row money 10, which contains counts for row money 1,5,10 plus the previous 25 count.
For example, numbers[1][12] = numbers[0][12] + numbers[1][7] (7 = 12-5) which results in 3 = 1 + 2; numbers[3][12] = numbers[2][12] + numbers[3][9] (-13 = 12-25) which results in 4 = 0 + 4, since -13 is less than 0.
def cntMoney(num):
mSz = len(money)
numbers = [[0]*(1+num) for _ in range(mSz)]
for mI in range(mSz): numbers[mI][0] = 1
for mI,m in enumerate(money):
for i in range(1,num+1):
numbers[mI][i] = numbers[mI][i-m] if i >= m else 0
if mI != 0: numbers[mI][i] += numbers[mI-1][i]
print('m,numbers',m,numbers[mI])
return numbers[mSz-1][num]
money = [1,5,10,25]
num = 12
print('money,combinations',num,cntMoney(num))
output:
('m,numbers', 1, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
('m,numbers', 5, [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3])
('m,numbers', 10, [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 4, 4, 4])
('m,numbers', 25, [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 4, 4, 4])
('money,combinations', 12, 4)
Because this is just how Python works - keywords such as class
and def
are not declarations. Instead, they are real live statements which are executed. If they were not executed your module would be .. empty :-)
Anyway, the idiomatic approach is:
# stuff to run always here such as class/def
def main():
pass
if __name__ == "__main__":
# stuff only to run when not called via 'import' here
main()
See What is if __name__ == "__main__"
for?
It does require source control over the module being import
ed, however.
Happy coding.
This is bcrypt:
Generate a random salt. A "cost" factor has been pre-configured. Collect a password.
Derive an encryption key from the password using the salt and cost factor. Use it to encrypt a well-known string. Store the cost, salt, and cipher text. Because these three elements have a known length, it's easy to concatenate them and store them in a single field, yet be able to split them apart later.
When someone tries to authenticate, retrieve the stored cost and salt. Derive a key from the input password, cost and salt. Encrypt the same well-known string. If the generated cipher text matches the stored cipher text, the password is a match.
Bcrypt operates in a very similar manner to more traditional schemes based on algorithms like PBKDF2. The main difference is its use of a derived key to encrypt known plain text; other schemes (reasonably) assume the key derivation function is irreversible, and store the derived key directly.
Stored in the database, a bcrypt
"hash" might look something like this:
$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa
This is actually three fields, delimited by "$":
2a
identifies the bcrypt
algorithm version that was used.10
is the cost factor; 210 iterations of the key derivation function are used (which is not enough, by the way. I'd recommend a cost of 12 or more.)vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa
is the salt and the cipher text, concatenated and encoded in a modified Base-64. The first 22 characters decode to a 16-byte value for the salt. The remaining characters are cipher text to be compared for authentication.This example is taken from the documentation for Coda Hale's ruby implementation.
I use the following .gitignore file generated in gitignore.io:
### Xcode ###
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.xcuserstate
### Objective-C ###
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
Pods/
$fruit= array_map('trim', $fruit);
Swift 3
From all the options displayed here, this is the one that worked for me.
let arr = [6,1,2,3,4,10,11]
var sumedArr = arr.reduce(0, { ($0 + $1)})
print(sumedArr)
I would try defining a more specific width, for starters. It's hard to center something that already spans the entire width:
#container {
width: 400px;
}
The accepted answer was not working for me, I followed this tutorial instead with success.
Basically:
<div id="muteYouTubeVideoPlayer"></div>
<script async src="https://www.youtube.com/iframe_api"></script>
<script>
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('muteYouTubeVideoPlayer', {
videoId: 'YOUR_VIDEO_ID', // YouTube Video ID
width: 560, // Player width (in px)
height: 316, // Player height (in px)
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 1, // Show pause/play buttons in player
showinfo: 0, // Hide the video title
modestbranding: 1, // Hide the Youtube Logo
loop: 1, // Run the video in a loop
fs: 0, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 3, // Hide the Video Annotations
autohide: 0 // Hide video controls when playing
},
events: {
onReady: function(e) {
e.target.mute();
}
}
});
}
// Written by @labnol
</script>
What does copying an object mean? There are a few ways you can copy objects--let's talk about the 2 kinds you're most likely referring to--deep copy and shallow copy.
Since we're in an object-oriented language (or at least are assuming so), let's say you have a piece of memory allocated. Since it's an OO-language, we can easily refer to chunks of memory we allocate because they are usually primitive variables (ints, chars, bytes) or classes we defined that are made of our own types and primitives. So let's say we have a class of Car as follows:
class Car //A very simple class just to demonstrate what these definitions mean.
//It's pseudocode C++/Javaish, I assume strings do not need to be allocated.
{
private String sPrintColor;
private String sModel;
private String sMake;
public changePaint(String newColor)
{
this.sPrintColor = newColor;
}
public Car(String model, String make, String color) //Constructor
{
this.sPrintColor = color;
this.sModel = model;
this.sMake = make;
}
public ~Car() //Destructor
{
//Because we did not create any custom types, we aren't adding more code.
//Anytime your object goes out of scope / program collects garbage / etc. this guy gets called + all other related destructors.
//Since we did not use anything but strings, we have nothing additional to handle.
//The assumption is being made that the 3 strings will be handled by string's destructor and that it is being called automatically--if this were not the case you would need to do it here.
}
public Car(const Car &other) // Copy Constructor
{
this.sPrintColor = other.sPrintColor;
this.sModel = other.sModel;
this.sMake = other.sMake;
}
public Car &operator =(const Car &other) // Assignment Operator
{
if(this != &other)
{
this.sPrintColor = other.sPrintColor;
this.sModel = other.sModel;
this.sMake = other.sMake;
}
return *this;
}
}
A deep copy is if we declare an object and then create a completely separate copy of the object...we end up with 2 objects in 2 completely sets of memory.
Car car1 = new Car("mustang", "ford", "red");
Car car2 = car1; //Call the copy constructor
car2.changePaint("green");
//car2 is now green but car1 is still red.
Now let's do something strange. Let's say car2 is either programmed wrong or purposely meant to share the actual memory that car1 is made of. (It's usually a mistake to do this and in classes is usually the blanket it's discussed under.) Pretend that anytime you ask about car2, you're really resolving a pointer to car1's memory space...that's more or less what a shallow copy is.
//Shallow copy example
//Assume we're in C++ because it's standard behavior is to shallow copy objects if you do not have a constructor written for an operation.
//Now let's assume I do not have any code for the assignment or copy operations like I do above...with those now gone, C++ will use the default.
Car car1 = new Car("ford", "mustang", "red");
Car car2 = car1;
car2.changePaint("green");//car1 is also now green
delete car2;/*I get rid of my car which is also really your car...I told C++ to resolve
the address of where car2 exists and delete the memory...which is also
the memory associated with your car.*/
car1.changePaint("red");/*program will likely crash because this area is
no longer allocated to the program.*/
So regardless of what language you're writing in, be very careful about what you mean when it comes to copying objects because most of the time you want a deep copy.
What are the copy constructor and the copy assignment operator?
I have already used them above. The copy constructor is called when you type code such as Car car2 = car1;
Essentially if you declare a variable and assign it in one line, that's when the copy constructor is called. The assignment operator is what happens when you use an equal sign--car2 = car1;
. Notice car2
isn't declared in the same statement. The two chunks of code you write for these operations are likely very similar. In fact the typical design pattern has another function you call to set everything once you're satisfied the initial copy/assignment is legitimate--if you look at the longhand code I wrote, the functions are nearly identical.
When do I need to declare them myself? If you are not writing code that is to be shared or for production in some manner, you really only need to declare them when you need them. You do need to be aware of what your program language does if you choose to use it 'by accident' and didn't make one--i.e. you get the compiler default. I rarely use copy constructors for instance, but assignment operator overrides are very common. Did you know you can override what addition, subtraction, etc. mean as well?
How can I prevent my objects from being copied? Override all of the ways you're allowed to allocate memory for your object with a private function is a reasonable start. If you really don't want people copying them, you could make it public and alert the programmer by throwing an exception and also not copying the object.
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
I think we could write in the following way to retrieve(below code is just an example, please modify as needed):
Create FUNCTION dbo.ufnGetEmployeeMultiple(@DepartmentID int)
RETURNS VARCHAR(1000) AS
BEGIN
DECLARE @Employeelist varchar(1000)
SELECT @Employeelist = COALESCE(@Employeelist + ', ', '') + E.LoginID
FROM humanresources.Employee E
Left JOIN humanresources.EmployeeDepartmentHistory H ON
E.BusinessEntityID = H.BusinessEntityID
INNER JOIN HumanResources.Department D ON
H.DepartmentID = D.DepartmentID
Where H.DepartmentID = @DepartmentID
Return @Employeelist
END
SELECT D.name as Department, dbo.ufnGetEmployeeMultiple (D.DepartmentID)as Employees
FROM HumanResources.Department D
SELECT Distinct (D.name) as Department, dbo.ufnGetEmployeeMultiple (D.DepartmentID) as
Employees
FROM HumanResources.Department D
Sub TestSave()
Application.Quit
ThisWorkBook.Close SaveChanges = False
End Sub
This seems to work for me, Even though looks like am quitting app before saving, but it saves...
If you have 2 arrays need to be merged based on values even its in different order
let arr1 = [
{ id:"1", value:"this", other: "that" },
{ id:"2", value:"this", other: "that" }
];
let arr2 = [
{ id:"2", key:"val2"},
{ id:"1", key:"val1"}
];
you can do like this
const result = arr1.map(item => {
const obj = arr2.find(o => o.id === item.id);
return { ...item, ...obj };
});
console.log(result);
One object may contain another as a part of its attribute.
So containment need not be physical. e.g., computer system has a warranty.
If you want to the long text wrapped properly in new lines then in your table id call use a css property table-layout:fixed;
otherwise simply css can't break the long text in new lines.
For French Locale (France) ONLY, be careful because /
appears in the date :
echo %DATE%
08/09/2013
For our problem of log file, here is my proposal for French Locale ONLY:
SETLOCAL
set LOGFILE_DATE=%DATE:~6,4%.%DATE:~3,2%.%DATE:~0,2%
set LOGFILE_TIME=%TIME:~0,2%.%TIME:~3,2%
set LOGFILE=log-%LOGFILE_DATE%-%LOGFILE_TIME%.txt
rem log-2014.05.19-22.18.txt
command > %LOGFILE%
//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
console.log("Action Before Selected");
var deptid=e.choice.id;
var depttext=e.choice.text;
console.log("Department ID "+deptid);
console.log("Department Text "+depttext);
});
//when a Department removing
$('#department_id').on('select2-removing', function (e) {
console.log("Action Before Deleted");
var deptid=e.choice.id;
var depttext=e.choice.text;
console.log("Department ID "+deptid);
console.log("Department Text "+depttext);
});
PostgreSQL gives you 2 ways of doing this:
SELECT DISTINCT * FROM (VALUES('a'),('b'),('a'),('v')) AS tbl(col1)
or
SELECT DISTINCT * FROM (select unnest(array['a','b', 'a','v'])) AS tbl(col1)
using array approach you can also do something like this:
SELECT DISTINCT * FROM (select unnest(string_to_array('a;b;c;d;e;f;a;b;d', ';'))) AS tbl(col1)
The UI is a bit different in the newer versions of Windows Server. Here is where you have to enable ASP.Net in order to get it working on IIS
Because you haven't declared it. If you want to use a variable of another class you must use
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestViewController : ViewController = segue.destinationViewController as ViewController
DestViewController.signedIn = false
}
You have to put this code at the end of the NewClass code
There is now a built-in way to do this as of version 6.5.2
Edit -> Line Operations -> Remove Empty Lines
or Remove Empty Lines (Containing Blank characters)
SharpCompress is in my opinion one of the smartest compression libraries out there. It supports LZMA (7-zip), is easy to use and under active development.
As it has LZMA streaming support already, at the time of writing it unfortunately only supports 7-zip archive reading. BUT archive writing is on their todo list (see readme). For future readers: Check to get the current status here: https://github.com/adamhathcock/sharpcompress/blob/master/FORMATS.md
The accepted answer previously contained new Buffer()
, which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).
The Buffer
constructor is deprecated according to the documentation.
Here is an example of a vulnerability that can result from using it in the ws library.
The code snippets should read:
console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));
After this answer was written, it has been updated and now matches this.
try this:
function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
and ensure that in php.ini allow_url_fopen is enable
You can also check pageloaded using following code
IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:
var json = JSON.stringify({whatver: test});
Then just modify the previous answers to:
Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));
If you don't want the newlines in the text file, then don't preserve it.
One way to do this would be to pass the instance of ParentClass
to the ChildClass
on construction
public ChildClass
{
private ParentClass parent;
public ChildClass(ParentClass parent)
{
this.parent = parent;
}
public void LoadData(DateTable dt)
{
// do something
parent.CurrentRow++; // or whatever.
parent.UpdateProgressBar(); // Call the method
}
}
Make sure to pass the reference to this
when constructing ChildClass
inside parent:
if(loadData){
ChildClass childClass = new ChildClass(this); // here
childClass.LoadData(this.Datatable);
}
Caveat: This is probably not the best way to organise your classes, but it directly answers your question.
EDIT: In the comments you mention that more than 1 parent class wants to use ChildClass
. This is possible with the introduction of an interface, eg:
public interface IParentClass
{
void UpdateProgressBar();
int CurrentRow{get; set;}
}
Now, make sure to implement that interface on both (all?) Parent Classes and change child class to this:
public ChildClass
{
private IParentClass parent;
public ChildClass(IParentClass parent)
{
this.parent = parent;
}
public void LoadData(DateTable dt)
{
// do something
parent.CurrentRow++; // or whatever.
parent.UpdateProgressBar(); // Call the method
}
}
Now anything that implements IParentClass
can construct an instance of ChildClass
and pass this
to its constructor.
Use \overleftarrow
to create a long arrow to the left.
\overleftarrow{blahblahblah}
Following the argument about Math.ceil(value/10d)
and (value+9)/10
I ended up coding a proper non-dead code, non-interpret mode benchmark.
I've been telling that writing micro benchmark is not an easy task. The code below illustrates this:
00:21:40.109 starting up....
00:21:40.140 doubleCeil: 19444599
00:21:40.140 integerCeil: 19444599
00:21:40.140 warming up...
00:21:44.375 warmup doubleCeil: 194445990000
00:21:44.625 warmup integerCeil: 194445990000
00:22:27.437 exec doubleCeil: 1944459900000, elapsed: 42.806s
00:22:29.796 exec integerCeil: 1944459900000, elapsed: 2.363s
The benchmark is in Java since I know well how Hotspot optimizes and ensures it's a fair result. With such results, no statistics, noise or anything can taint it.
Integer ceil is insanely much faster.
The code
package t1;
import java.math.BigDecimal;
import java.util.Random;
public class Div {
static int[] vals;
static long doubleCeil(){
int[] v= vals;
long sum = 0;
for (int i=0;i<v.length;i++){
int value = v[i];
sum+=Math.ceil(value/10d);
}
return sum;
}
static long integerCeil(){
int[] v= vals;
long sum = 0;
for (int i=0;i<v.length;i++){
int value = v[i];
sum+=(value+9)/10;
}
return sum;
}
public static void main(String[] args) {
vals = new int[7000];
Random r= new Random(77);
for (int i = 0; i < vals.length; i++) {
vals[i] = r.nextInt(55555);
}
log("starting up....");
log("doubleCeil: %d", doubleCeil());
log("integerCeil: %d", integerCeil());
log("warming up...");
final int warmupCount = (int) 1e4;
log("warmup doubleCeil: %d", execDoubleCeil(warmupCount));
log("warmup integerCeil: %d", execIntegerCeil(warmupCount));
final int execCount = (int) 1e5;
{
long time = System.nanoTime();
long s = execDoubleCeil(execCount);
long elapsed = System.nanoTime() - time;
log("exec doubleCeil: %d, elapsed: %.3fs", s, BigDecimal.valueOf(elapsed, 9));
}
{
long time = System.nanoTime();
long s = execIntegerCeil(execCount);
long elapsed = System.nanoTime() - time;
log("exec integerCeil: %d, elapsed: %.3fs", s, BigDecimal.valueOf(elapsed, 9));
}
}
static long execDoubleCeil(int count){
long sum = 0;
for(int i=0;i<count;i++){
sum+=doubleCeil();
}
return sum;
}
static long execIntegerCeil(int count){
long sum = 0;
for(int i=0;i<count;i++){
sum+=integerCeil();
}
return sum;
}
static void log(String msg, Object... params){
String s = params.length>0?String.format(msg, params):msg;
System.out.printf("%tH:%<tM:%<tS.%<tL %s%n", new Long(System.currentTimeMillis()), s);
}
}
Using ' and " at the same time works great for me (Windows 10, python 3)
import os
os.system('"some cmd command here"')
for example to open my web browser I can use this:
os.system('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"')
(Edit) for an easier way to open your browser I can use this:
import webbrowser
webbrowser.open('website or leave it alone if you only want to open the
browser')
No need for all that. Check out pathinfo(), it gives you all the components of your path.
Example from the manual:
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // filename is only since PHP 5.2.0
Output of the code:
/www/htdocs
index.html
html
index
And alternatively you can get only certain parts like:
echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html
You don't need to call json.getJSONArray()
at all, because the JSON you're working with already is an array. So, don't construct an instance of JSONObject
; use a JSONArray
. This should suffice:
// ...
JSONArray json = new JSONArray(result);
// ...
for(int i=0;i<json.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = json.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArray
at the root, not a JSONObject
.
You can use placeholders and feed_dict.
Suppose we have numpy arrays like these:
trX = np.linspace(-1, 1, 101)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33
You can declare two placeholders:
X = tf.placeholder("float")
Y = tf.placeholder("float")
Then, use these placeholders (X, and Y) in your model, cost, etc.: model = tf.mul(X, w) ... Y ... ...
Finally, when you run the model/cost, feed the numpy arrays using feed_dict:
with tf.Session() as sess:
....
sess.run(model, feed_dict={X: trY, Y: trY})
You can recursively iterate through subviews, store an array of all UITextFields, and then loop through them and resign them all.
Not really a great solution, especially if you have a lot of subviews, but for simple apps it should do the trick.
I solved this in a much more complicated, but much more performant way, but using a singleton/manager for the animation engine of my app, and any time a text field became the responder, I would assign assign it to a static which would get swept up (resigned) based on certain other events... its almost impossible for me to explain in a paragraph.
Be creative, it only took me 10 minutes to think through this for my app after I found this question.
*nix provides a nice little command which makes our lives a lot easier.
GET:
with JSON:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource
with XML:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource
POST:
For posting data:
curl --data "param1=value1¶m2=value2" http://hostname/resource
For file upload:
curl --form "[email protected]" http://hostname/resource
RESTful HTTP Post:
curl -X POST -d @filename http://hostname/resource
For logging into a site (auth):
curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/
Pretty-printing the curl results:
For JSON:
If you use npm
and nodejs
, you can install json
package by running this command:
npm install -g json
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json
If you use pip
and python
, you can install pjson
package by running this command:
pip install pjson
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson
If you use Python 2.6+, json tool is bundled within.
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool
If you use gem
and ruby
, you can install colorful_json
package by running this command:
gem install colorful_json
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson
If you use apt-get
(aptitude package manager of your Linux distro), you can install yajl-tools
package by running this command:
sudo apt-get install yajl-tools
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json_reformat
For XML:
If you use *nix with Debian/Gnome envrionment, install libxml2-utils
:
sudo apt-get install libxml2-utils
Usage:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -
or install tidy
:
sudo apt-get install tidy
Usage:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -
Saving the curl response to a file
curl http://hostname/resource >> /path/to/your/file
or
curl http://hostname/resource -o /path/to/your/file
For detailed description of the curl command, hit:
man curl
For details about options/switches of the curl command, hit:
curl -h
One possible answer to OP-s question ("I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?") is to use built-in function divmod()
num = int(input('Enter a number: ')
nums_sum = 0
while num:
num, reminder = divmod(num, 10)
nums_sum += reminder
If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1
or -m 2
option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.
git revert <commit> -m 1
git revert <commit> -m 2
The reason is because when you explicitly do "0" == false
, both sides are being converted to numbers, and then the comparison is performed.
When you do: if ("0") console.log("ha")
, the string value is being tested. Any non-empty string is true
, while an empty string is false
.
Equal (==)
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
(From Comparison Operators in Mozilla Developer Network)
Here is what I have:
def is_prime(num):
if num < 2: return False
elif num < 4: return True
elif not num % 2: return False
elif num < 9: return True
elif not num % 3: return False
else:
for n in range(5, int(math.sqrt(num) + 1), 6):
if not num % n:
return False
elif not num % (n + 2):
return False
return True
It's pretty fast for large numbers, as it only checks against already prime numbers for divisors of a number.
Now if you want to generate a list of primes, you can do:
# primes up to 'max'
def primes_max(max):
yield 2
for n in range(3, max, 2):
if is_prime(n):
yield n
# the first 'count' primes
def primes_count(count):
counter = 0
num = 3
yield 2
while counter < count:
if is_prime(num):
yield num
counter += 1
num += 2
using generators here might be desired for efficiency.
And just for reference, instead of saying:
one = 1
while one == 1:
# do stuff
you can simply say:
while 1:
#do stuff
Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.
The opposite is a much better strategy. If you have minSdkVersion
to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi
or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi
at all.
This is probably why the Android NDK doesn't even support armeabi
anymore as per revision r17b. [source]
I think it should be the case. To erase the character, you should use replace(".", "")
instead.
Try this...
1.create drawable xml(custom_layout.xml):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" />
<stroke
android:width="2dp"
android:color="#FF785C" />
<corners android:radius="10dp" />
</shape>
2.add your view background
android:background="@drawable/custom_layout"
From my testing, there are three criteria for sorting characters as described below. Aside from this, shorter strings are sorted above longer strings that start with the same characters.
Note: This testing only looked at the first character sorting and did not look into edge cases described by this answer, which found that, for all characters after the first character, numbers take precedence over symbols (i.e. the order is 1. Symbols 2. Numbers 3. Letters for first character, 1. Numbers 2. Symbols 3. Letters after). This answer also indicated that the Unicode/ASCII layer of sorting might not be entirely consistent. I'll update this answer if I get time to look into these edge cases.
Note: It's important to note that sorting order might be subject to change as described by this answer. It is not clear to me though the extent to which this actually ever changes. I've done this testing and found it to be valid on both Windows 7 and Windows 10.
Symbols
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))
Numbers
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))
Letters
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))
Sorting Rule Sequence vs Observed Order
It's worth noting that there are really two ways of looking at this. Ultimately, what you have are sorting rules that are applied in a certain order, in turn, this produces an observed order. The ordering of older rules becomes nested under the ordering of newer rules. This means that the first rule applied is the last rule observed, while the last rule applied is the first or topmost rule observed.
Sorting Rule Sequence
1.) Sort on Unicode Value (U+xxxx)
2.) Sort on culture/language
3.) Sort on Type (Symbol, Number, Letter)
Observed Order
The highest level of grouping is by type in the following order...
1.) Symbols
2.) Numbers
3.) Letters
Therefore, any symbol from any language comes before any number from any language, while any letter from any language appears after all symbols and numbers.
The second level of grouping is by culture/language. The following order seems to apply for this:
Latin
Greek
Cyrillic
Hebrew
Arabic
The lowest rule observed is Unicode order, so items within a type-language group are ordered by Unicode value (U+xxxx).
Adapted from here: https://superuser.com/a/971721/496260
Here are 3 examples:
$(document).on('click', 'ul li a', function (e) {_x000D_
e.preventDefault();_x000D_
_x000D_
var example1 = $(this).parents('ul:first').attr('id');_x000D_
$('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
$('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
_x000D_
var example3 = $(this).closest('ul').attr('id');_x000D_
$('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
<li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
<h1>Results:</h1>_x000D_
</div>
_x000D_
Let me know whether it was helpful.
Otherwise Try this :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Temp {
public static void main(String[] args) {
File file = new File("c:/EventItemBroker.java");
byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
for (int i = 0; i < b.length; i++) {
System.out.print((char)b[i]);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
}
}
public class WriteByteArrayToFile {
public static void main(String[] args) {
String strFilePath = "Your path";
try {
FileOutputStream fos = new FileOutputStream(strFilePath);
String strContent = "Write File using Java ";
fos.write(strContent.getBytes());
fos.close();
}
catch(FileNotFoundException ex) {
System.out.println("FileNotFoundException : " + ex);
}
catch(IOException ioe) {
System.out.println("IOException : " + ioe);
}
}
}
Live demo with ESC functionality
Works on both Desktop and Mobile
var notH = 1,
$pop = $('.form_wrapper').hover(function(){ notH^=1; });
$(document).on('mousedown keydown', function( e ){
if(notH||e.which==27) $pop.hide();
});
If for some case you need to be sure that your element is really visible when you do clicks on the document: if($pop.is(':visible') && (notH||e.which==27)) $pop.hide();
For JavaScript arrays, you use Both push() and concat() function.
var array = [1, 2, 3];
array.push(4, 5); //use push for appending a single array.
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); //It is better use concat for appending more then one array.
This should now work with Internet Explorer, Firefox v12+ and Chrome 28+
<img src="'../images/foo.gif'"
alt="line 1
line 2" title="line 1
line 2">
Try a JavaScript tooltip library for a better result, something like OverLib.
There are a couple of things that need to be adjusted in your layout:
You are nesting col
elements within form-group
elements. This should be the other way around (the form-group
should be within the col-sm-xx
element).
You should always use a row
div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12
is still on the same row with the above 3 .col-sm-4
resulting in a total of columns greater than 12, and causing the overlap problem.
Here is a fixed demo.
And an excerpt of what the problematic section HTML should become:
<fieldset>
<legend>Personal Information</legend>
<div class='row'>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_title">Title</label>
<input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_firstname">First name</label>
<input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_lastname">Last name</label>
<input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
</div>
</div>
</div>
<div class='row'>
<div class='col-sm-12'>
<div class='form-group'>
<label for="user_email">Email</label>
<input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
</div>
</div>
</div>
</fieldset>
df=pd.read_csv("filename.csv" , parse_dates=["<column name>"])
type(df.<column name>)
example: if you want to convert day which is initially a string to a Timestamp in Pandas
df=pd.read_csv("weather_data2.csv" , parse_dates=["day"])
type(df.day)
The output will be pandas.tslib.Timestamp
First convert to p12:
openssl pkcs12 -export -in [filename-certificate] -inkey [filename-key] -name [host] -out [filename-new-PKCS-12.p12]
Create new JKS from p12:
keytool -importkeystore -deststorepass [password] -destkeystore [filename-new-keystore.jks] -srckeystore [filename-new-PKCS-12.p12] -srcstoretype PKCS12
Based on solution You've already found How to apply CSS to iframe?:
var cssLink = document.createElement("link")
cssLink.href = "file://path/to/style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['iframe'].document.body.appendChild(cssLink);
or more jqueryish (from Append a stylesheet to an iframe with jQuery):
var $head = $("iframe").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));
as for security issues: Disabling same-origin policy in Safari
From the fine manual.
You must own the table to use ALTER TABLE.
Or be a database superuser.
ERROR: must be owner of relation contact
PostgreSQL error messages are usually spot on. This one is spot on.
You have to create Different values folder for different screens . Like
values-sw720dp 10.1” tablet 1280x800 mdpi
values-sw600dp 7.0” tablet 1024x600 mdpi
values-sw480dp 5.4” 480x854 mdpi
values-sw480dp 5.1” 480x800 mdpi
values-xxhdpi 5.5" 1080x1920 xxhdpi
values-xxxhdpi 5.5" 1440x2560 xxxhdpi
values-xhdpi 4.7” 1280x720 xhdpi
values-xhdpi 4.65” 720x1280 xhdpi
values-hdpi 4.0” 480x800 hdpi
values-hdpi 3.7” 480x854 hdpi
values-mdpi 3.2” 320x480 mdpi
values-ldpi 3.4” 240x432 ldpi
values-ldpi 3.3” 240x400 ldpi
values-ldpi 2.7” 240x320 ldpi
For more information you may visit here
Different values folders in android
http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html
Edited By @humblerookie
You can make use of Android Studio plugin called Dimenify to auto generate dimension values for other pixel buckets based on custom scale factors. Its still in beta, be sure to notify any issues/suggestions you come across to the developer.
Set equal name
attributes to create a group;
<form>_x000D_
<fieldset id="group1">_x000D_
<input type="radio" value="value1" name="group1">_x000D_
<input type="radio" value="value2" name="group1">_x000D_
</fieldset>_x000D_
_x000D_
<fieldset id="group2">_x000D_
<input type="radio" value="value1" name="group2">_x000D_
<input type="radio" value="value2" name="group2">_x000D_
<input type="radio" value="value3" name="group2">_x000D_
</fieldset>_x000D_
</form>
_x000D_
A template class is like a macro, only a whole lot less evil.
Think of a template as a macro. The parameters to the template get substituted into a class (or function) definition, when you define a class (or function) using a template.
The difference is that the parameters have "types" and values passed are checked during compilation, like parameters to functions. The types valid are your regular C++ types, like int and char. When you instantiate a template class, you pass a value of the type you specified, and in a new copy of the template class definition this value gets substituted in wherever the parameter name was in the original definition. Just like a macro.
You can also use the "class
" or "typename
" types for parameters (they're really the same). With a parameter of one of these types, you may pass a type name instead of a value. Just like before, everywhere the parameter name was in the template class definition, as soon as you create a new instance, becomes whatever type you pass. This is the most common use for a template class; Everybody that knows anything about C++ templates knows how to do this.
Consider this template class example code:
#include <cstdio>
template <int I>
class foo
{
void print()
{
printf("%i", I);
}
};
int main()
{
foo<26> f;
f.print();
return 0;
}
It's functionally the same as this macro-using code:
#include <cstdio>
#define MAKE_A_FOO(I) class foo_##I \
{ \
void print() \
{ \
printf("%i", I); \
} \
};
MAKE_A_FOO(26)
int main()
{
foo_26 f;
f.print();
return 0;
}
Of course, the template version is a billion times safer and more flexible.
I also wanted to combine a DatePicker and a TimePicker. So I create an API to handle both in one interface! :)
https://github.com/Kunzisoft/Android-SwitchDateTimePicker
You can also use SublimePicker
Simply add spaces for { 2 3 4 5 6 } like these:
cout<<"{";
for(){
cout<<" "<<n; //n is the element to print !
}
cout<<" }";
Use FirstOrDefault or a foreach loop as already mentioned. Manually fetching an enumerator and calling Current should be avoided. foreach will dispose your enumerator for you if it implements IDisposable. When calling MoveNext and Current you have to dispose it manually (if aplicable).
Well if you're happy printing it in decimal, you could just make it positive by masking:
int positive = bytes[i] & 0xff;
If you're printing out a hash though, it would be more conventional to use hex. There are plenty of other questions on Stack Overflow addressing converting binary data to a hex string in Java.
You need to process the image beforehand, to make a centered and stretched image. Try this:
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"image.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
Replace this
<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">
with
<button value=" Send" class="btn btn-success" type="submit" id="submit">
You need to put the full path in the php ini when loading the mysql dll, i.e :-
extension=c:/php54/ext/php_mbstring.dll
extension=c:/php54/ext/php_mysql.dll
Then you don't need to move them to the windows folder.
If you want to duplicate the table with all its constraints & keys follows this below steps:
Then for copying the data run this below script:
SET IDENTITY_INSERT DuplicateTable ON
INSERT Into DuplicateTable ([Column1], [Column2], [Column3], [Column4],... )
SELECT [Column1], [Column2], [Column3], [Column4],... FROM MainTable
SET IDENTITY_INSERT DuplicateTable OFF
try
{
//Handle the alert pop-up using seithTO alert statement
Alert alert = driver.switchTo().alert();
//Print alert is present
System.out.println("Alert is present");
//get the message which is present on pop-up
String message = alert.getText();
//print the pop-up message
System.out.println(message);
alert.sendKeys("");
//Click on OK button on pop-up
alert.accept();
}
catch (NoAlertPresentException e)
{
//if alert is not present print message
System.out.println("alert is not present");
}
You could try using https://www.printnode.com which is essentially exactly the service that you are looking for. You download and install a desktop client onto the users computer - https://www.printnode.com/download. You can then discover and print to any printers on that user's computer using their JSON API https://www.printnode.com/docs/api/curl/. They have lots of libs here: https://github.com/PrintNode/
ls -lR
is what you were looking for, or atleast I was. cheers
Old Way (pre-1.7):
$("...").attr("onclick", "").unbind("click");
New Way (1.7+):
$("...").prop("onclick", null).off("click");
(Replace ... with the selector you need.)
// use the "[attr=value]" syntax to avoid syntax errors with special characters (like "$")_x000D_
$('[id="a$id"]').prop('onclick',null).off('click');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<a id="a$id" onclick="alert('get rid of this')" href="javascript:void(0)" class="black">Qualify</a>
_x000D_