If you have multiples docker containers launched, use this
$ docker rm $(docker ps -aq)
It will remove all the current dockers listed in the "ps -aq" command.
Source : aaam on https://github.com/docker/docker/issues/12487
For me using Select2.full.js Version 4.0.3 none of the above solutions was working the way it should be. So I wrote a combination of the solutions above. First of all I modified Select2.full.js to transfer the internal focus and blur events to jquery events as "Thomas Molnar" did in his answer.
EventRelay.prototype.bind = function (decorated, container, $container) {
var self = this;
var relayEvents = [
'open', 'opening',
'close', 'closing',
'select', 'selecting',
'unselect', 'unselecting',
'focus', 'blur'
];
And then I added the following code to handle focus and blur and focussing the next element
$("#myId").select2( ... ).one("select2:focus", select2Focus).on("select2:blur", function ()
{
var select2 = $(this).data('select2');
if (select2.isOpen() == false)
{
$(this).one("select2:focus", select2Focus);
}
}).on("select2:close", function ()
{
setTimeout(function ()
{
// Find the next element and set focus on it.
$(":focus").closest("tr").next("tr").find("select:visible,input:visible").focus();
}, 0);
});
function select2Focus()
{
var select2 = $(this).data('select2');
setTimeout(function() {
if (!select2.isOpen()) {
select2.open();
}
}, 0);
}
More IntelliJ 13+ Shortcuts for Terminal
Mac OS X:
alt ?F12
cmd ?shift ?A then type Terminal
then hit Enter
shift ?shift ?shift ?shift ? then type Terminal
then hit Enter
Windows:
altF12 press Enter
ctrlshift ?A start typing Terminal
then hit Enter
shift ?shift ? then type Terminal
then hit Enter
The question is with JQuery, it's just FYI.
let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
yourBtnID.style.display = 'none';
if (textareaID.value.length) {
yourBtnID.style.display = 'inline-block';
}
});
<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>
CTRL+SHIFT+D
And there are many shortcuts you can see them by going to
Settings » Shortcuts, as displayed here:
Alternatively, use CTRL + ? to go to the settings, from there one can reach the "Shortcuts" sub-item on the left or use the Official reference.
foreach ($basearr as &$row)
{
$row['value'] = $row['url'];
unset( $row['url'] );
}
unset($row);
A very good plugin management system to use. The included vimrc file is good enough for python programming and can be easily configured to your needs. See http://spf13.com/project/spf13-vim/
There is a nice generic way using the .data('events') collection:
function getEventsList($obj) {
var ev = new Array(),
events = $obj.data('events'),
i;
for(i in events) { ev.push(i); }
return ev.join(' ');
}
$obj.on(getEventsList($obj), function(e) {
console.log(e);
});
This logs every event that has been already bound to the element by jQuery the moment this specific event gets fired. This code was pretty damn helpful for me many times.
Btw: If you want to see every possible event being fired on an object use firebug: just right click on the DOM element in html tab and check "Log Events". Every event then gets logged to the console (this is sometimes a bit annoying because it logs every mouse movement...).
As an addition to fuzzyman's reply:
pip won't install binary packages and isn't well tested on Windows.
As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.
Here is a trick on Windows:
you can use easy_install <package>
to install binary packages to avoid building a binary
you can use pip uninstall <package>
even if you used easy_install.
This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.
See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install
I will ask on the mailing list what is planned for that.
Here is the latest update:
The new supported way to install binaries is going to be wheel
!
It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1
https://pypi.python.org/pypi/wheel
http://wheel.readthedocs.org/en/latest/
I will test wheel
by creating an OS X installer for PySide
using wheel
instead of eggs. Will get back and report about this.
cheers - Chris
The transition to wheel
is almost over. Most packages are supporting wheel
.
I promised to build wheels for PySide
, and I did that last summer. Works great!
HINT:
A few developers failed so far to support the wheel format, simply because they forget to
replace distutils
by setuptools
.
Often, it is easy to convert such packages by replacing this single word in setup.py
.
LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.
Assuming this example HTML:
<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />
You could have this javascript:
$("#email").bind("change", function(e){
$.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
function(data){
$.each(data, function(i,item){
if (item.field == "first_name") {
$("#first_name").val(item.value);
} else if (item.field == "last_name") {
$("#last_name").val(item.value);
}
});
});
});
Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:
<?php
//look up the record based on email and get the firstname and lastname
...
//build the JSON array for return
$json = array(array('field' => 'first_name',
'value' => $firstName),
array('field' => 'last_name',
'value' => $last_name));
echo json_encode($json );
?>
You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.
The following solution works for me. I added OnKeyDown
and OnKeyUp
event override to keep the TextBox text always selected.
public class NumericTextBox : TextBox
{
private bool _focused;
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
if (MouseButtons == MouseButtons.None)
{
this.SelectAll();
_focused = true;
}
}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
if (MouseButtons == MouseButtons.None)
{
SelectAll();
_focused = true;
}
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
_focused = false;
}
protected override void OnMouseUp(MouseEventArgs mevent)
{
base.OnMouseUp(mevent);
if (!_focused)
{
if (SelectionLength == 0)
SelectAll();
_focused = true;
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (SelectionLength == 0)
SelectAll();
_focused = true;
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (SelectionLength == 0)
SelectAll();
_focused = true;
}
}
It's even easier if you consider that the Generic List in C# is indexed from 0 like an array. This means you can just use something like:
int index = 0; int i = accounts[index];
In case you use jQuery you need to wait for $(window).load
, because the embedded SVG document might not be yet loaded at $(document).ready
$(window).load(function () {
//alert("Document loaded, including graphics and embedded documents (like SVG)");
var a = document.getElementById("alphasvg");
//get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
//get the inner element by id
var delta = svgDoc.getElementById("delta");
delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});
How to reproduce the bug:
Settings -> Developer Options -> Don't keep Activities
.AsyncTask
is executing and the ProgressDialog
is showing.The Android OS will destroy an activity as soon as it is hidden. When onPostExecute
is called the Activity
will be in "finishing" state and the ProgressDialog
will be not attached to Activity
.
How to fix it:
onPostExecute
method. ProgressDialog
in onDestroy
method. Otherwise, android.view.WindowLeaked
exception will be thrown. This exception usually comes from dialogs that are still active when the activity is finishing.Try this fixed code:
public class YourActivity extends Activity {
private void showProgressDialog() {
if (pDialog == null) {
pDialog = new ProgressDialog(StartActivity.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
}
pDialog.show();
}
private void dismissProgressDialog() {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
}
@Override
protected void onDestroy() {
dismissProgressDialog();
super.onDestroy();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// Before starting background thread Show Progress Dialog
@Override
protected void onPreExecute() {
showProgressDialog();
}
//getting All products from url
protected String doInBackground(String... args) {
doMoreStuff("internet");
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
return;
}
dismissProgressDialog();
something(note);
}
}
}
Yes -- the X509Store.Certificates
property returns a snapshot of the X.509 certificate store.
You can do this:
public int Property { get { ... } private set { ... } }
the ultimate answer: change the owner of that directory to whoever you are
sudo chown -R `whoami` /usr/local/include
which is also recommended by brew if you run brew doctor
Just use .
for concatenating.
And you missed out the $personCount
increment!
while ($personCount < 10) {
$result .= $personCount . ' people';
$personCount++;
}
echo $result;
While it is possible to combine the results, I would advise against doing so.
You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.
You can run something like
git ls-files | xargs wc -l
which will give you the total count ?
Or use this tool ? http://line-count.herokuapp.com/
The angular.forEach()
will iterate through your json
object.
First iteration,
key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}
Second iteration,
key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }
To get the value of your name
, you can use value.name
or value["name"]
. Same with your password
, you use value.password
or value["password"]
.
The code below will give you what you want:
angular.forEach(json, function (value, key)
{
//console.log(key);
//console.log(value);
if (value.password == "thomasTheKing") {
console.log("username is thomas");
}
});
a=[1,2,3]
b=[str(x) for x in a]
print b
above method is the easiest and most general way to convert list into string. another short method is-
a=[1,2,3]
b=map(str,a)
print b
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
I tried all the above and found them wanting. This is the simplest most flexible solution I could figure out (thanks to all of the above for inspiration).
HTML
<div id="container">
<ul>
<li>HOME</li>
<li>ABOUT US</li>
<li>SERVICES</li>
<li>PREVIOUS PROJECTS</li>
<li>TESTIMONIALS</li>
<li>NEWS</li>
<li>RESEARCH & DEV</li>
<li>CONTACT</li>
</ul>
</div>
CSS
div#container{
width:900px;
background-color:#eee;
padding:20px;
}
ul {
display:table;
width: 100%;
margin:0 0;
-webkit-padding-start:0px; /* reset chrome default */
}
ul li {
display:table-cell;
height:30px;
line-height:30px;
font-size:12px;
padding:20px 10px;
text-align: center;
background-color:#999;
border-right:2px solid #fff;
}
ul li:first-child {
border-radius:10px 0 0 10px;
}
ul li:last-child {
border-radius:0 10px 10px 0;
border-right:0 none;
}
You can drop the first/last child-rounded ends, obviously, but I think they're real purdy (and so does your client ;)
The container width limits the horizontal list, but you can ditch this and just apply an absolute value to the UL if you like.
Fiddle with it, if you like..
You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".
You can only use real devices.
Emulator Limitations
The functional limitations of the emulator include:
Refer to the documentation
I had this one a while back, and the answer isn't necessarily what you'd expect. This error message often crops up when your connection string is wrong.
At a guess, you'll need something like this:
<connectionStrings>
<add name="hublisherEntities" connectionString="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
What's happening is that it's looking for a data source in the wrong place; Entity Framework specifies it slightly differently. If you post your connection string and EF config then we can check.
The git blame
command annotates lines with information from the revision which last modified the line, and... with Git 2.22 (Q2 2019), will do so faster, because of a performance fix around "git blame
", especially in a linear history (which is the norm we should optimize for).
See commit f892014 (02 Apr 2019) by David Kastrup (fedelibre
).
(Merged by Junio C Hamano -- gitster
-- in commit 4d8c4da, 25 Apr 2019)
blame.c
: don't drop origin blobs as eagerlyWhen a parent blob already has chunks queued up for blaming, dropping the blob at the end of one blame step will cause it to get reloaded right away, doubling the amount of I/O and unpacking when processing a linear history.
Keeping such parent blobs in memory seems like a reasonable optimization that should incur additional memory pressure mostly when processing the merges from old branches.
Your array.xml is not right. change it to like this
Here is array.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="testArray">
<item>first</item>
<item>second</item>
<item>third</item>
<item>fourth</item>
<item>fifth</item>
</string-array>
</resources>
A good plugin that I have used before is DataTables.
<div>It's working fine.....</div>
div
{
height: calc(100vh - 8vw);
background: #000;
overflow:visible;
color: red;
}
Check here this css code right now support All browser without Opera
Live
@bobflux's answer is great. I would like to extend it by adding a complete query that uses proposed approach.
select tt.id, tt.x_field
from target_table as tt
-- Here we join our target_table with order_table to specify custom ordering.
left join
(values ('f', 1), ('p', 2), ('i', 3), ('a', 4)) as order_table (x_field, order_num)
on order_table.x_field = tt.x_field
order by
order_table.order_num, -- Here we order values by our custom order.
tt.x_field; -- Other values can be ordered alphabetically, for example.
Here is complete demo.
Normally, with scalar values:
$elements = array('foo', ...);
array_splice($array, $position, $length, $elements);
To insert a single array element into your array don't forget to wrap the array in an array (as it was a scalar value!):
$element = array('key1'=>'value1');
$elements = array($element);
array_splice($array, $position, $length, $elements);
otherwise all the keys of the array will be added piece by piece.
Install the ASP.NET AJAX Control Toolkit
Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the ASP.NET AJAX Control Toolkit Releases page of the CodePlex web site.
Copy the contents of this zip file directly into the bin directory of your web site.
Update web.config
Put this in your web.config under the <controls> section:
<?xml version="1.0"?>
<configuration>
...
<system.web>
...
<pages>
...
<controls>
...
<add tagPrefix="ajaxtoolkit"
namespace="AjaxControlToolkit"
assembly="AjaxControlToolKit"/>
</controls>
</pages>
...
</system.web>
...
</configuration>
Setup Visual Studio
Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"
Inside that tab, right-click on the Toolbox and select "Choose Items..."
When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.
You can now use the controls in your web sites!
Clearly you need a flexible solution that can support types masquerading as boolean. The following allows for that:
template<typename T> bool Flip(const T& t);
You can then specialize this for different types that might pretend to be boolean. For example:
template<> bool Flip<bool>(const bool& b) { return !b; }
template<> bool Flip<int>(const int& i) { return !(i == 0); }
An example of using this construct:
if(Flip(false)) { printf("flipped false\n"); }
if(!Flip(true)) { printf("flipped true\n"); }
if(Flip(0)) { printf("flipped 0\n"); }
if(!Flip(1)) { printf("flipped 1\n"); }
No, I'm not serious.
I got a solution!
When resetting root password at step 2), also change the auth plugin to mysql_native_password
:
use mysql;
update user set authentication_string=PASSWORD("") where User='root';
update user set plugin="mysql_native_password" where User='root'; # THIS LINE
flush privileges;
quit;
This allowed me to log in successfully!
sudo /etc/init.d/mysql stop # stop mysql service
sudo mysqld_safe --skip-grant-tables & # start mysql without password
# enter -> go
mysql -uroot # connect to mysql
use mysql; # use mysql table
update user set authentication_string=PASSWORD("") where User='root'; # update password to nothing
update user set plugin="mysql_native_password" where User='root'; # set password resolving to default mechanism for root user
flush privileges;
quit;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start # reset mysql
# try login to database, just press enter at password prompt because your password is now blank
mysql -u root -p
When you see a socket error, a community came with 2 possible solutions:
sudo mkdir -p /var/run/mysqld; sudo chown mysql /var/run/mysqld
sudo mysqld_safe --skip-grant-tables &
(thanks to @Cerin)
Or
mkdir -p /var/run/mysqld && chown mysql:mysql /var/run/mysqld
(thanks to @Peter Dvukhrechensky)
mysql -uroot # "-hlocalhost" is default
Can lead to "missing file" or slt error.
mysql -uroot -h127.0.0.1
Works better.
I've found many ways to create mysqld.sock
file, change access rights or symlink it. It was not the issue after all.
my.cnf
fileThe issue also was not there. If you are not sure, this might help you.
How to implement 'in' and 'not in' for a pandas DataFrame?
Pandas offers two methods: Series.isin
and DataFrame.isin
for Series and DataFrames, respectively.
The most common scenario is applying an isin
condition on a specific column to filter rows in a DataFrame.
df = pd.DataFrame({'countries': ['US', 'UK', 'Germany', np.nan, 'China']})
df
countries
0 US
1 UK
2 Germany
3 China
c1 = ['UK', 'China'] # list
c2 = {'Germany'} # set
c3 = pd.Series(['China', 'US']) # Series
c4 = np.array(['US', 'UK']) # array
Series.isin
accepts various types as inputs. The following are all valid ways of getting what you want:
df['countries'].isin(c1)
0 False
1 True
2 False
3 False
4 True
Name: countries, dtype: bool
# `in` operation
df[df['countries'].isin(c1)]
countries
1 UK
4 China
# `not in` operation
df[~df['countries'].isin(c1)]
countries
0 US
2 Germany
3 NaN
# Filter with `set` (tuples work too)
df[df['countries'].isin(c2)]
countries
2 Germany
# Filter with another Series
df[df['countries'].isin(c3)]
countries
0 US
4 China
# Filter with array
df[df['countries'].isin(c4)]
countries
0 US
1 UK
Sometimes, you will want to apply an 'in' membership check with some search terms over multiple columns,
df2 = pd.DataFrame({
'A': ['x', 'y', 'z', 'q'], 'B': ['w', 'a', np.nan, 'x'], 'C': np.arange(4)})
df2
A B C
0 x w 0
1 y a 1
2 z NaN 2
3 q x 3
c1 = ['x', 'w', 'p']
To apply the isin
condition to both columns "A" and "B", use DataFrame.isin
:
df2[['A', 'B']].isin(c1)
A B
0 True True
1 False False
2 False False
3 False True
From this, to retain rows where at least one column is True
, we can use any
along the first axis:
df2[['A', 'B']].isin(c1).any(axis=1)
0 True
1 False
2 False
3 True
dtype: bool
df2[df2[['A', 'B']].isin(c1).any(axis=1)]
A B C
0 x w 0
3 q x 3
Note that if you want to search every column, you'd just omit the column selection step and do
df2.isin(c1).any(axis=1)
Similarly, to retain rows where ALL columns are True
, use all
in the same manner as before.
df2[df2[['A', 'B']].isin(c1).all(axis=1)]
A B C
0 x w 0
numpy.isin
, query
, list comprehensions (string data)In addition to the methods described above, you can also use the numpy equivalent: numpy.isin
.
# `in` operation
df[np.isin(df['countries'], c1)]
countries
1 UK
4 China
# `not in` operation
df[np.isin(df['countries'], c1, invert=True)]
countries
0 US
2 Germany
3 NaN
Why is it worth considering? NumPy functions are usually a bit faster than their pandas equivalents because of lower overhead. Since this is an elementwise operation that does not depend on index alignment, there are very few situations where this method is not an appropriate replacement for pandas' isin
.
Pandas routines are usually iterative when working with strings, because string operations are hard to vectorise. There is a lot of evidence to suggest that list comprehensions will be faster here..
We resort to an in
check now.
c1_set = set(c1) # Using `in` with `sets` is a constant time operation...
# This doesn't matter for pandas because the implementation differs.
# `in` operation
df[[x in c1_set for x in df['countries']]]
countries
1 UK
4 China
# `not in` operation
df[[x not in c1_set for x in df['countries']]]
countries
0 US
2 Germany
3 NaN
It is a lot more unwieldy to specify, however, so don't use it unless you know what you're doing.
Lastly, there's also DataFrame.query
which has been covered in this answer. numexpr FTW!
The most common idiom for creating an array without using the inefficient +=
is something like this, from the output of a loop:
$array = foreach($i in 1..10) {
$i
}
$array
If your widget is a Button:
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal">
<Button android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="somebutton"/>
<TextView android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
I'm assuming you want your widget to take up one half, and another widget to take up the other half. The trick is using a LinearLayout, setting layout_width="fill_parent"
on both widgets, and setting layout_weight
to the same value on both widgets as well. If there are two widgets, both with the same weight, the LinearLayout will split the width between the two widgets.
This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config
file and having something like this
Host git_host
HostName git.host.de
User root
Port 4019
then you can have
url = git_host:/var/cache/git/project.git
and you can also ssh git_host
and scp git_host ...
and everything will work out.
In R, you can assign your own operators using %[characters]%
. A trivial example:
'%p%' <- function(x, y){x^2 + y}
2 %p% 3 # result: 7
While I agree with BlueTrin that %%
is pretty standard, I have a suspicion %/%
may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/%
means do a special sort of division (integer division)
I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like
$redis->set('persons', $persons)
Later I decided to change to "hSet" method, and I tried it this way
foreach($persons as $person){
$redis->hSet('persons', $person->id, $person);
}
Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with
del persons
It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.
To display the item number on the repeater you can use the Container.ItemIndex
property.
<asp:repeater id="rptRepeater" runat="server">
<itemtemplate>
Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
</itemtemplate>
<separatortemplate>
<br />
</separatortemplate>
</asp:repeater>
From what I understand, you struggle with what to put into your template.
I'll show an example:
<ul>
{% for guest in guests %}
<li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
{% endfor %}
</ul>
Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.
A terser way, either with rev
:
x[!(!duplicated(x) & rev(!duplicated(rev(x))))]
... rather than fromLast
:
x[!(!duplicated(x) & !duplicated(x, fromLast = TRUE))]
... and as a helper function to provide either logical vector or elements from original vector :
duplicates <- function(x, as.bool = FALSE) {
is.dup <- !(!duplicated(x) & rev(!duplicated(rev(x))))
if (as.bool) { is.dup } else { x[is.dup] }
}
Treating vectors as data frames to pass to table
is handy but can get difficult to read, and the data.table
solution is fine but I'd prefer base R solutions for dealing with simple vectors like IDs.
String TitleCaseString(String s)
{
if (s == null || s.Length == 0) return s;
string[] splits = s.Split(' ');
for (int i = 0; i < splits.Length; i++)
{
switch (splits[i].Length)
{
case 1:
break;
default:
splits[i] = Char.ToUpper(splits[i][0]) + splits[i].Substring(1);
break;
}
}
return String.Join(" ", splits);
}
$('select#id').find('option').each(function() {
alert($(this).val());
});
You can use the client-side onclick event to do that:
yourButton.Attributes.Add("onclick", "this.disabled=true;");
if number >= 10000 and number <= 30000:
print ("you have to pay 5% taxes")
If you have already tried using the git add .
command to add all your untracked files, make sure you're not under a subfolder of your root project.
git add .
will stage all your files under the current subfolder.
If you need it to have as a condition in an other event, I solved it this way:
$('.classname').hover(
function(){$(this).data('hover',true);},
function(){$(this).data('hover',false);}
);
Then in another event, you can easily use it:
if ($(this).data('hover')){
//...
}
(I see some using is(':hover')
to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)
Didn't see this suggested: me.onChange && me.onChange(str);
Basically if me.onChange is undefined (which it will be if it hasn't been initiated) then it won't execute the latter part. If me.onChange is a function, it will execute me.onChange(str).
You can even go further and do:
me && me.onChange && me.onChange(str);
in case me is async as well.
In certain cases, the use of :
for(var pair of formData.entries(){...
is impossible.
I've used this code in replacement :
var outputLog = {}, iterator = myFormData.entries(), end = false;
while(end == false) {
var item = iterator.next();
if(item.value!=undefined) {
outputLog[item.value[0]] = item.value[1];
} else if(item.done==true) {
end = true;
}
}
console.log(outputLog);
It's not a very smart code, but it works...
Hope it's help.
Use counting sort and then find the second largest element, starting from index 0 towards the end. There should be at least 1 comparison, at most n-1
(when there's only one element!).
To check if field is NULL use IS NULL
, IS NOT NULL
operators.
MySql reference http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html
In this LIVE DEMO i've achieved this by using the :before css selector which seems to work quite nicely.
.myDiv {_x000D_
position: relative; /*Parent MUST be relative*/_x000D_
z-index: 9;_x000D_
background: green;_x000D_
_x000D_
/*Set width/height of the div in 'parent'*/ _x000D_
width:100px;_x000D_
height:100px;_x000D_
}_x000D_
_x000D_
_x000D_
.myDiv:before {_x000D_
content: "";_x000D_
position: absolute;/*set 'child' to be absolute*/_x000D_
z-index: -1; /*Make this lower so text appears in front*/_x000D_
_x000D_
_x000D_
/*You can choose to align it left, right, top or bottom here*/_x000D_
top: 0; _x000D_
right:0;_x000D_
bottom: 60%;_x000D_
left: 0;_x000D_
_x000D_
_x000D_
background: red;_x000D_
}
_x000D_
<div class="myDiv">this is my div with multiple colours. It work's with text too!</div>
_x000D_
I thought i would add this as I feel it could work quite well for a percentage bar/visual level of something.
It also means you're not creating multiple divs if you don't have to, and keeps this page up-to-date
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
To get bytes back just:
new BigInteger(bytes).toByteArray()
If you don't mind getting your hands dirty, it isn't that difficult to write an RTF to HTML converter.
Writing a general purpose RTF->HTML converter would be somewhat complicated because you would need to deal with hundreds of RTF verbs. However, in your case you are only dealing with those verbs used specifically by Crystal Reports. I'll bet the standard RTF coding generated by Crystal doesn't vary much from report to report.
I wrote an RTF to HTML converter in C++, but it only deals with basic formatting like fonts, paragraph alignments, etc. My translator basically strips out any specialized formatting that it isn't prepared to deal with. It took about 400 lines of C++. It basically scans the text for RTF tags and replaces them with equivalent HTML tags. RTF tags that aren't in my list are simply stripped out. A regex function is really helpful when writing such a converter.
You can achieve this by using the Delegate.Remove or Delegate.RemoveAll methods.
Here is how i got it solved : I ran the emulator with following command :
sudo /home/code/Android/Sdk/tools/emulator -avd Nexus_S_API_21 -netspeed full -netdelay none -debug-init -logcat '*:v'
and received the following in the output :
NAND: could not write file /tmp/android-code/TMP7.tmp, No space left on device. (similar error, could not reproduce it)
So, i just freed up some disk space from my /home directory in ubuntu (for windows free the C: drive space) and it then booted smoothly.
I was facing same issue, for me adding certificate to trust store solved this issue.
You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.
If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)
I wanted to throw a 'normal' 404 for any logged in user that isn't an admin, so I ended up writing something like this in Rails 5:
class AdminController < ApplicationController
before_action :blackhole_admin
private
def blackhole_admin
return if current_user.admin?
raise ActionController::RoutingError, 'Not Found'
rescue ActionController::RoutingError
render file: "#{Rails.root}/public/404", layout: false, status: :not_found
end
end
I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.
but I should add more infomation when you use pycharm and enable auto import
.
when you format the code, the code from mpl_toolkits.mplot3d import Axes3D
will auto remove by pycharm.
so, my solution is
from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
and it works well!
I had the same problem and I found out that if you add the URL param ?v=3
you won't get the warning message anymore:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
As pointed out in the comments by @Zia Ul Rehman Mughal
Turns out specifying this means you are referring to old frozen version 3.0 not the latest version. Frozen old versions are not updated with bug fixes or anything. But this is good to mention though. https://developers.google.com/maps/documentation/javascript/versions#the-frozen-version
This solution doesn't work anymore.
Use anchor links and the scroll-behavior
property (MDN reference) for the scrolling container:
scroll-behavior: smooth;
Browser support: Firefox 36+, Chrome 61+ (therefore also Edge 79+) and Opera 48+.
Intenet Explorer, non-Chromium Edge and (so far) Safari do not support scroll-behavior
and simply "jump" to the link target.
Example usage:
<head>
<style type="text/css">
html {
scroll-behavior: smooth;
}
</style>
</head>
<body id="body">
<a href="#foo">Go to foo!</a>
<!-- Some content -->
<div id="foo">That's foo.</div>
<a href="#body">Back to top</a>
</body>
Here's a Fiddle.
And here's also a Fiddle with both horizontal and vertical scrolling.
They both increment the number. ++i
is equivalent to i = i + 1
.
i++
and ++i
are very similar but not exactly the same. Both increment the number, but ++i
increments the number before the current expression is evaluated, whereas i++
increments the number after the expression is evaluated.
int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a =
Check this link.
The default sort for arrays in Javascript is an alphabetical search. If you want a numerical sort, try something like this:
var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });
Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv
commands will tire quickly. To make things a bit easier this is what I do:
git add . -A
to remove all files.git add .
. Git should see that the files are renamed.Now you can make a commit saying you have changed the file name capitalization.
try this:
.button input, .button a {
//css here
}
That will apply the style to all a tags nested inside of <p class="button"></p>
Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid
in its place, not just 1, of course. And, I just made up the cid
value.
I also don't under stand what the "-" means after the 200 140 section of the log
That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)
I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections
library exists to fulfill these purposes.
from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
letter_counter[letter] += 1
>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})
In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.
As for the dict.get(a_key, default_value)
, there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.
I came across this problem, most people use jQuery... Here was my solution. "Do not mind, I am just a beginner in this..."
.cards-collection {
.card-item {
width: 100%;
margin: 20px 20px;
padding:0 ;
.card {
border-radius: 10px;
button {
border: inherit;
}
}
}
}
.container-fluid
.row.cards-collection.justify-content-center
.card-item.col-lg-3.col-md-4.col-sm-6.col-11
.card.h-100
If any card item height is e.g. 400px (based on it's contents), because the default for flex-align is stretch, then .card-item (child of row or card-collection class) will be stretched. making the height of the card to be 100% of the parent will occupy this full height.
I hope I was correct. Am I?
So I'm not entirely sure why this works, but it saves an image with my plot:
dtf = pd.DataFrame.from_records(d,columns=h)
dtf2.plot()
fig = plt.gcf()
fig.savefig('output.png')
I'm guessing that the last snippet from my original post saved blank because the figure was never getting the axes generated by pandas. With the above code, the figure object is returned from some magic global state by the gcf() call (get current figure), which automagically bakes in axes plotted in the line above.
Just simply add (keyup.enter)="yourFunction()"
First, set height greater than width. In theory, this is all you should need. The HTML5 Spec suggests as much:
... the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties.
Opera had it implemented this way, but Opera is now using WebKit Blink. As of today, no browser implements a vertical slider based solely on height being greater than width.
Regardless, setting height greater than width is needed to get the layout right between browsers. Applying left and right padding will also help with layout and positioning.
For Chrome, use -webkit-appearance: slider-vertical
.
For IE, use writing-mode: bt-lr
.
For Firefox, add an orient="vertical"
attribute to the html. Pity that they did it this way. Visual styles should be controlled via CSS, not HTML.
input[type=range][orient=vertical]
{
writing-mode: bt-lr; /* IE */
-webkit-appearance: slider-vertical; /* WebKit */
width: 8px;
height: 175px;
padding: 0 5px;
}
_x000D_
<input type="range" orient="vertical" />
_x000D_
This solution is based on current browser implementations of as yet undefined or unfinalized CSS properties. If you intend to use it in your code, be prepared to make code adjustments as newer browser versions are released and w3c recommendations are completed.
MDN contains an explicit warning against using -webkit-appearance
on the web:
Do not use this property on Web sites: not only is it non-standard, but its behavior change from one browser to another. Even the keyword
none
has not the same behavior on each form element on different browsers, and some doesn't support it at all.
The caption for the vertical slider demo in the IE documentation erroneously indicates that setting height greater than width will display a range slider vertically, but this does not work. In the code section, it plainly does not set height or width, and instead uses writing-mode
. The writing-mode
property, as implemented by IE, is very robust. Sadly, the values defined in the current working draft of the spec as of this writing, are much more limited. Should future versions of IE drop support of bt-lr
in favor of the currently proposed vertical-lr
(which would be the equivalent of tb-lr
), the slider would display upside down. Most likely, future versions would extend the writing-mode
to accept new values rather than drop support for existing values. But, it's good to know what you are dealing with.
The best approach depends on the expected key distribution and number of collisions. If relatively few collisions are expected, it really doesn't matter which method is used. If lots of collisions are expected, then which to use depends on the cost of rehashing or probing vs. manipulating the extensible bucket data structure.
But here is source code example of An Hashmap Implementation in C
I face this issue multiple times. It turns out, that it has nothing to do with permissions, cache, etc. The error message is misleading. For node v 6.x you will see more detailed error stack but not after 7.x For me and my colleges, the issue is timeout function. Basically the package install has not finished yet (i.e. holding the directory) when npm tries to delete it. in node 6.x you can see that in finalize.js now it's gone! Just use yarn.
As of 6-6-15 the Web Root location is at /tmp/deployment/application/ROOT using Tomcat.
Also have a look into the built-in DataFrame.filter
function.
Minimalistic but greedy approach (sufficient for the given df):
df.filter(regex="[^BD]")
Conservative/lazy approach (exact matches only):
df.filter(regex="^(?!(B|D)$).*$")
Conservative and generic:
exclude_cols = ['B','C']
df.filter(regex="^(?!({0})$).*$".format('|'.join(exclude_cols)))
I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...
There is a line of code to uncommment in order to have it return JSON.
Put this in your server directive:
location /issue {
rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
}
Or duplicate it:
location /issue1 {
rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
...
You can use the Django-Truncate library to delete all data of a table without destroying the table structure.
Example:
pip install django-truncate
settings.py
file:INSTALLED_APPS = [
...
'django_truncate',
]
python manage.py truncate --apps app_name --models table_name
import java.io.*;
import java.util.*;
import java.util.HashMap;
public class Solution
{
public static void main(String[] args)
{
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1,"SUNDAY");
hm.put(2,"MONDAY");
hm.put(3,"TUESDAY");
hm.put(4,"WEDNESDAY");
hm.put(5,"THURSDAY");
hm.put(6,"FRIDAY");
hm.put(7,"SATURDAY");
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
String format = year + "/" + month + "/" + day;
Date date = null;
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
date = formatter.parse(format);
}
catch(Exception e){
}
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(hm.get(dayOfWeek));
}
}
MySQL 8 changed the default charset to utf8mb4. But some clients don't know this charset. Hence when the server reports its default charset to the client, and the client doesn't know what the server means, it throws this error.
See also https://bugs.mysql.com/bug.php?id=71606
That bug is against the MySQL Connector/C++ so it's affecting more than just PHP.
Okay—I got it to work by changing the character set to utf8, to be compatible with non-upgraded clients. I added this to /etc/my.cnf and restarted mysqld:
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8
I found these settings in an answer from 2010: Change MySQL default character set to UTF-8 in my.cnf?
EDIT: This is bad advice. Use "o", as above. "s" does the wrong thing.
I always use this:
dateTime.ToUniversalTime().ToString("s");
This is correct if your schema looks like this:
<xs:element name="startdate" type="xs:dateTime"/>
Which would result in:
<startdate>2002-05-30T09:00:00</startdate>
You can get more information here: http://www.w3schools.com/xml/schema_dtypes_date.asp
At the moment of writing, JavaScript is receiving a new data type: BigInt
. It is a TC39 proposal at stage 4 to be included in EcmaScript 2020. BigInt
is available in Chrome 67+, FireFox 68+, Opera 54 and Node 10.4.0. It is underway in Safari, et al... It introduces numerical literals having an "n" suffix and allows for arbitrary precision:
var a = 123456789012345678901012345678901n;
Precision will still be lost, of course, when such a number is (maybe unintentionally) coerced to a number data type.
And, obviously, there will always be precision limitations due to finite memory, and a cost in terms of time in order to allocate the necessary memory and to perform arithmetic on such large numbers.
For instance, the generation of a number with a hundred thousand decimal digits, will take a noticeable delay before completion:
console.log(BigInt("1".padEnd(100000,"0")) + 1n)
...but it works.
I couldn't find a single answer or a section in the official Django docs that had all the information I needed to override/extend the default admin templates, so I'm writing this answer as a complete guide, hoping that it would be helpful for others in the future.
Assuming the standard Django project structure:
mysite-container/ # project container directory
manage.py
mysite/ # project package
__init__.py
admin.py
apps.py
settings.py
urls.py
wsgi.py
app1/
app2/
...
static/
templates/
Here's what you need to do:
In mysite/admin.py
, create a sub-class of AdminSite
:
from django.contrib.admin import AdminSite
class CustomAdminSite(AdminSite):
# set values for `site_header`, `site_title`, `index_title` etc.
site_header = 'Custom Admin Site'
...
# extend / override admin views, such as `index()`
def index(self, request, extra_context=None):
extra_context = extra_context or {}
# do whatever you want to do and save the values in `extra_context`
extra_context['world'] = 'Earth'
return super(CustomAdminSite, self).index(request, extra_context)
custom_admin_site = CustomAdminSite()
Make sure to import custom_admin_site
in the admin.py
of your apps and register your models on it to display them on your customized admin site (if you want to).
In mysite/apps.py
, create a sub-class of AdminConfig
and set default_site
to admin.CustomAdminSite
from the previous step:
from django.contrib.admin.apps import AdminConfig
class CustomAdminConfig(AdminConfig):
default_site = 'admin.CustomAdminSite'
In mysite/settings.py
, replace django.admin.site
in INSTALLED_APPS
with apps.CustomAdminConfig
(your custom admin app config from the previous step).
In mysite/urls.py
, replace admin.site.urls
from the admin URL to custom_admin_site.urls
from .admin import custom_admin_site
urlpatterns = [
...
path('admin/', custom_admin_site.urls),
# for Django 1.x versions: url(r'^admin/', include(custom_admin_site.urls)),
...
]
Create the template you want to modify in your templates
directory, maintaining the default Django admin templates directory structure as specified in the docs. For example, if you were modifying admin/index.html
, create the file templates/admin/index.html
.
All of the existing templates can be modified this way, and their names and structures can be found in Django's source code.
Now you can either override the template by writing it from scratch or extend it and then override/extend specific blocks.
For example, if you wanted to keep everything as-is but wanted to override the content
block (which on the index page lists the apps and their models that you registered), add the following to templates/admin/index.html
:
{% extends 'admin/index.html' %}
{% block content %}
<h1>
Hello, {{ world }}!
</h1>
{% endblock %}
To preserve the original contents of a block, add {{ block.super }}
wherever you want the original contents to be displayed:
{% extends 'admin/index.html' %}
{% block content %}
<h1>
Hello, {{ world }}!
</h1>
{{ block.super }}
{% endblock %}
You can also add custom styles and scripts by modifying the extrastyle
and extrahead
blocks.
Transmission Delay : Amount of time required to pump all bits/packets into the electric wire/optic fibre.
Propagation delay : It's the amount of time needed for a packet to reach the destination.
If propagation delay is very high than transmission delay the chance of losing the packet is high.
Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.
The most important thing is, the action created must return partial view, see below.
public ActionResult _YourPartialViewSection()
{
return PartialView();
}
In addition to the solution you accepted, you could also implement the special __lt__()
("less than") method on the class. The sort()
method (and the sorted()
function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.
class Foo(object):
def __init__(self, score):
self.score = score
def __lt__(self, other):
return self.score < other.score
l = [Foo(3), Foo(1), Foo(2)]
l.sort()
You only need to write
seamless
in your code. There is not need for:
seamless ="seamless"
I just found this out myself.
EDIT - this does not remove scrollbars. Strangely
scrolling="no" still seems to work in html5. I have tried using the overflow function with an inline style as recommended by html5 but this doesn't work for me.
Found a solution with pop
and map
d = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'b', 'c']
list(map(d.pop, keys))
print(d)
The output of this:
{'d': 'valueD'}
I have answered this question so late just because I think it will help in the future if anyone searches the same. And this might help.
Update
The above code will throw an error if a key does not exist in the dict.
DICTIONARY = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'l', 'c']
def remove_keys(key):
try:
DICTIONARY.pop(key, None)
except:
pass # or do any action
list(map(remove_key, keys))
print(DICTIONARY)
output:
DICTIONARY = {'b': 'valueB', 'd': 'valueD'}
Alternatively you can use Jetty which is (now) part of the Eclipe Platform (the Help system is running Jetty). Besides Jetty is used by Android, Windows Mobile..
To get started check the Eclipse Wiki or if you prefer a Video And check out this related Post!
As an update to Joe's answer, in that you can script the creation of the repository using the API, only the API call I needed was different. This may be because we are using bitbucket server, and not bitbucket cloud.
To create a new repo within a project on our server, I used:
curl -X POST -v -u USER:PASSWORD -H "Content-Type: application/json" \
http://SERVER/rest/api/1.0/projects/PROJECTNAME/repos/ \
-d '{"scmid":"git", "name":"REPONAME"}'
where USER
, PASSWORD
, SERVER
, PROJECTNAME
and REPONAME
were of course the desired/required values.
The call is documented in the API reference.
/rest/api/1.0/projects/{projectKey}/repos
Create a new repository. Requires an existing project in which this repository will be created. The only parameters which will be used are name and scmId.
The authenticated user must have PROJECT_ADMIN permission for the context project to call this resource.
Pass your arguments in constructor itself.
Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
Try as below:
var dt = new Date();
dt.setMinutes( dt.getMinutes() - 20 );
console.log('#####',dt);
FAT32
along with FAT16
and FAT12
are File System Types, but vfat
along with umsdos
and msdos
are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos
driver don't have long filenames (they are 8.3 format). vfat
is the most common driver for mounting FAT32 file systems nowadays.
Source: this wikipedia article
Output of commands like df
and lsblk
indeed show vfat
as the File System Type. But sudo file -sL /dev/<partition>
shows FAT (32 bit)
if a File System is FAT32.
You can confirm vfat
is a module and not a File System Type by running modinfo vfat
.
A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:
from tkinter import Frame, Tk
class MyApp():
def __init__(self):
self.root = Tk()
self.my_frame_red = Frame(self.root, bg='red')
self.my_frame_red.grid(row=0, column=0, sticky='nsew')
self.my_frame_blue = Frame(self.root, bg='blue')
self.my_frame_blue.grid(row=0, column=1, sticky='nsew')
self.root.grid_rowconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(1, weight=1)
self.root.mainloop()
if __name__ == '__main__':
app = MyApp()
But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.
Use cmp
command. This will either exit cleanly if they are binary equal, or it will print out where the first difference occurs and exit.
More flexible than select max()
is:
select distinct first_row(column_x) over (order by column_y,column_z,...) from Table_A
Use Tuple in Converter, and in OnExecute, cast the parameter object back to Tuple.
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
Tuple<string, string> tuple = new Tuple<string, string>(
(string)values[0], (string)values[1]);
return (object)tuple;
}
}
// ...
public void OnExecute(object parameter)
{
var param = (Tuple<string, string>) parameter;
}
In my experience, a "typical" use of eval is for running commands that generate shell commands to set environment variables.
Perhaps you have a system that uses a collection of environment variables, and you have a script or program that determines which ones should be set and their values. Whenever you run a script or program, it runs in a forked process, so anything it does directly to environment variables is lost when it exits. But that script or program can send the export commands to stdout.
Without eval, you would need to redirect stdout to a temp file, source the temp file, and then delete it. With eval, you can just:
eval "$(script-or-program)"
Note the quotes are important. Take this (contrived) example:
# activate.sh
echo 'I got activated!'
# test.py
print("export foo=bar/baz/womp")
print(". activate.sh")
$ eval $(python test.py)
bash: export: `.': not a valid identifier
bash: export: `activate.sh': not a valid identifier
$ eval "$(python test.py)"
I got activated!
With PostgreSQL 9.5, this is now native functionality (like MySQL has had for several years):
INSERT ... ON CONFLICT DO NOTHING/UPDATE ("UPSERT")
9.5 brings support for "UPSERT" operations. INSERT is extended to accept an ON CONFLICT DO UPDATE/IGNORE clause. This clause specifies an alternative action to take in the event of a would-be duplicate violation.
...
Further example of new syntax:
INSERT INTO user_logins (username, logins)
VALUES ('Naomi',1),('James',1)
ON CONFLICT (username)
DO UPDATE SET logins = user_logins.logins + EXCLUDED.logins;
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
As this is specifically tagged for jQuery -
$("#myElement")[0].getBoundingClientRect();
or
$("#myElement").get(0).getBoundingClientRect();
(These are functionally identical, in some older browsers .get()
was slightly faster)
Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...
Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect()
calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...
The solution I use for large sql restore is a mysqldumpsplitter script. I split my sql.gz into individual tables. then load up something like mysql workbench and process it as a restore to the desired schema.
Here is the script https://github.com/kedarvj/mysqldumpsplitter
And this works for larger sql restores, my average on one site I work with is a 2.5gb sql.gz file, 20GB uncompressed, and ~100Gb once restored fully
Here's a flow chart that illustrates a for loop:
The equivalent C code would be
for(i = 2; i <= 6; i = i + 2) {
printf("%d\t", i + 1);
}
I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.
Nope! You have to do it at runtime.
If you want to make your app backwards compatible, then simply check the device API level. If it is higher than 11, then you can fiddle with the ActionBar and set the subtitle.
if(Integer.valueOf(android.os.Build.VERSION.SDK) >= 11){
//set actionbar title
}
if you have started the server with
python -m SimpleHTTPServer 8888
then you can press ctrl + c to down the server.
But if you have started the server with
python -m SimpleHTTPServer 8888 &
or
python -m SimpleHTTPServer 8888 & disown
you have to see the list first to kill the process,
run command
ps
or
ps aux | less
it will show you some running process like this ..
PID TTY TIME CMD
7247 pts/3 00:00:00 python
7360 pts/3 00:00:00 ps
23606 pts/3 00:00:00 bash
you can get the PID from here. and kill that process by running this command..
kill -9 7247
here 7247 is the python id.
Also for some reason if the port still open you can shut down the port with this command
fuser -k 8888/tcp
here 8888 is the tcp port opened by python.
Hope its clear now.
REST webservice: (http://localhost:8080/your-app/rest/data/post)
package com.yourorg.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/data")
public class JSONService {
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "Data post: "+data;
return Response.status(201).entity(result).build();
}
Client send a post:
package com.yourorg.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");
String input = "{\"message\":\"Hello\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In your code you are assigning a native method to a property of custom object.
When you call support.animationFrame(function () {})
, it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window
.
So the correct usage here is support.animationFrame.call(window, function() {});
.
The same happens with alert too:
var myObj = {
myAlert : alert //copying native alert to an object
};
myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window
Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame: _raf ? _raf.bind(window) : null
};
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
I presume SELECT user FROM dual;
should give you the current user
and SELECT sys_context('userenv','instance_name') FROM dual;
the name of the instance
I believe you can get SID as SELECT sys_context('USERENV', 'SID') FROM DUAL;
Solution
Use this code
jQuery.nl2br = function(varTest){
return varTest.replace(/(\r\n|\n\r|\r|\n)/g, "<br>");
};
This should do the trick
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
then you enumerate over the controls like so
foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
// do something with tb here
}
To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -
Hibernate Object States
Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.
Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.
Detached - A detached instance is an object that has been persistent, but its Session has been closed.
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview
Transaction Write-Behind
The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.
- To perform batch inserts and updates.
- To propagate only the last change. If an object is updated more than once, it still fires only one update statement.
http://learningviacode.blogspot.com/2012/02/write-behind-technique-in-hibernate.html
First Level Cache
Hibernate has something called 'First Level Cache'. Whenever you pass an object to save()
, update()
or saveOrUpdate()
, and whenever you retrieve an object using load()
, get()
, list()
, iterate()
or scroll()
, that object is added to the internal cache of the Session. This is where it tracks changes to various objects.
Hibernate Intercepters and Object Lifecycle Listeners -
The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html#d0e3069
This section Updated
Cascading
Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete'
from parent to child association will result in deletion of all children when a parent is deleted.
So, why are these important.
To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached
and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.
That's why hibernate (sometimes) issues a 'SELECT'
statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.
Why does hibernate issue the 'SELECT' statement only sometimes?
Hibernate issues a 'SELECT'
statement to determine what state the object is in. If the select statement returns an object, the object is in detached
state and if it does not return an object, the object is in transient
state.
Coming to your scenario -
Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached
and then re-attches it to the session and processes delete lifecycle.
Update - Since you are explicitly calling 'Update'
instead of 'SaveOrUpdate'
, hibernate blindly assumes that the object is in detached
state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.
SaveOrUpdate - If you call 'SaveOrUpdate'
, hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached
state. If the object is in transient
state, it processes the 'insert'
lifecycle and if the object is in detached
state, it processes the 'Update'
lifecycle.
I don't like plural table names because some nouns in English are not countable (water, soup, cash) or the meaning changes when you make it countable (chicken vs a chicken; meat vs bird). I also dislike using abbreviations for table name or column name because doing so adds extra slope to the already steep learning curve.
Ironically, I might make User
an exception and call it Users
because of USER (Transac-SQL), because I too don't like using brackets around tables if I don't have to.
I also like to name all the ID columns as Id
, not ChickenId
or ChickensId
(what do plural guys do about this?).
All this is because I don't have proper respect for the database systems, I am just reapplying one-trick-pony knowledge from OO naming conventions like Java's out of habit and laziness. I wish there were better IDE support for complicated SQL.
Hi we can extract the pdf files using Apache Tika
The Example is :
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
public class WebPagePdfExtractor {
public Map<String, Object> processRecord(String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
Map<String, Object> map = new HashMap<String, Object>();
try {
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream input = null;
if (entity != null) {
try {
input = entity.getContent();
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
AutoDetectParser parser = new AutoDetectParser();
ParseContext parseContext = new ParseContext();
parser.parse(input, handler, metadata, parseContext);
map.put("text", handler.toString().replaceAll("\n|\r|\t", " "));
map.put("title", metadata.get(TikaCoreProperties.TITLE));
map.put("pageCount", metadata.get("xmpTPg:NPages"));
map.put("status_code", response.getStatusLine().getStatusCode() + "");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return map;
}
public static void main(String arg[]) {
WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();
Map<String, Object> extractedMap = webPagePdfExtractor.processRecord("http://math.about.com/library/q20.pdf");
System.out.println(extractedMap.get("text"));
}
}
string stringToDecrypt = CypherText.Replace(" ", "+");
int len = stringToDecrypt.Length;
byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt);
you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.
You should always consider a non-vba solution first.
Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):
http://www.youtube.com/watch?v=RCLUM0UMLXo
http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx
If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.
If it has to be the latter, then there is need for more details on your specification, regarding performance questions.
You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.
This would look something like that:
Public Sub CopyFilter()
Dim wks As Worksheet
Dim avarTemp() As Variant
'go through each worksheet
For Each wks In ThisWorkbook.Worksheets
avarTemp = wks.UsedRange
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
'check in the first column in each row
If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
'copy cell
targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
End If
Next i
Next wks
End Sub
Ok, now i have something nice which could come in handy for myself:
Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
Dim avarTemp() As Variant
Dim avarResult() As Variant
Dim i As Long
avarTemp = rng
ReDim avarResult(0)
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
If avarTemp(i, 1) = "active" Then
avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
'expand our result array
ReDim Preserve avarResult(UBound(avarResult) + 1)
End If
Next i
FILTER = avarResult
End Function
You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)
I've come across a cross-platform implementation of kbhit
at http://home.wlu.edu/~levys/software/kbhit.py (made edits to remove irrelevant code):
import os
if os.name == 'nt':
import msvcrt
else:
import sys, select
def kbhit():
''' Returns True if a keypress is waiting to be read in stdin, False otherwise.
'''
if os.name == 'nt':
return msvcrt.kbhit()
else:
dr,dw,de = select.select([sys.stdin], [], [], 0)
return dr != []
Make sure to read()
the waiting character(s) -- the function will keep returning True
until you do!
If that message is bother you, You need run Visual Studio with administrative rights to apply this direction on Visual Studio.
Tools-> Options-> Debugging-> Symbols and select check in a box "Microsoft Symbol Servers", mark load all modules then click Load all Symbols.
Everything else Visual Studio will do it for you, and you will have this message under Debug in Output window "Native' has exited with code 0 (0x0)"
Dart http's implementation process the bytes thanks to that "charset=utf-8", so i'm sure several implementations out there supports this, to avoid the "latin-1" fallback charset when reading the bytes from the response. In my case, I totally lose format on the response body string, so I have to do the bytes encoding manually to utf8, or add that header "inner" parameter on my server's API response.
MSDN has an easy way to perform sorting on columns with up/down glyphs. The example isn't complete, though - they don't explain how to use the data templates for the glyphs. Below is what I got to work with my ListView. This works on .Net 4.
In your ListView, you have to specify an event handler to fire for a click on the GridViewColumnHeader. My ListView looks like this:
<ListView Name="results" GridViewColumnHeader.Click="results_Click">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=ContactName}">
<GridViewColumn.Header>
<GridViewColumnHeader Content="Contact Name" Padding="5,0,0,0" HorizontalContentAlignment="Left" MinWidth="150" Name="ContactName" />
</GridViewColumn.Header>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=PrimaryPhone}">
<GridViewColumn.Header>
<GridViewColumnHeader Content="Contact Number" Padding="5,0,0,0" HorizontalContentAlignment="Left" MinWidth="150" Name="PrimaryPhone"/>
</GridViewColumn.Header>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
In your code behind, set up the code to handle the sorting:
// Global objects
BindingListCollectionView blcv;
GridViewColumnHeader _lastHeaderClicked = null;
ListSortDirection _lastDirection = ListSortDirection.Ascending;
// Header click event
void results_Click(object sender, RoutedEventArgs e)
{
GridViewColumnHeader headerClicked =
e.OriginalSource as GridViewColumnHeader;
ListSortDirection direction;
if (headerClicked != null)
{
if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
{
if (headerClicked != _lastHeaderClicked)
{
direction = ListSortDirection.Ascending;
}
else
{
if (_lastDirection == ListSortDirection.Ascending)
{
direction = ListSortDirection.Descending;
}
else
{
direction = ListSortDirection.Ascending;
}
}
string header = headerClicked.Column.Header as string;
Sort(header, direction);
if (direction == ListSortDirection.Ascending)
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowUp"] as DataTemplate;
}
else
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowDown"] as DataTemplate;
}
// Remove arrow from previously sorted header
if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
{
_lastHeaderClicked.Column.HeaderTemplate = null;
}
_lastHeaderClicked = headerClicked;
_lastDirection = direction;
}
}
// Sort code
private void Sort(string sortBy, ListSortDirection direction)
{
blcv.SortDescriptions.Clear();
SortDescription sd = new SortDescription(sortBy, direction);
blcv.SortDescriptions.Add(sd);
blcv.Refresh();
}
And then in your XAML, you need to add two DataTemplates that you specified in the sorting method:
<DataTemplate x:Key="HeaderTemplateArrowUp">
<DockPanel LastChildFill="True" Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}">
<Path x:Name="arrowUp" StrokeThickness="1" Fill="Gray" Data="M 5,10 L 15,10 L 10,5 L 5,10" DockPanel.Dock="Right" Width="20" HorizontalAlignment="Right" Margin="5,0,5,0" SnapsToDevicePixels="True"/>
<TextBlock Text="{Binding }" />
</DockPanel>
</DataTemplate>
<DataTemplate x:Key="HeaderTemplateArrowDown">
<DockPanel LastChildFill="True" Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}">
<Path x:Name="arrowDown" StrokeThickness="1" Fill="Gray" Data="M 5,5 L 10,10 L 15,5 L 5,5" DockPanel.Dock="Right" Width="20" HorizontalAlignment="Right" Margin="5,0,5,0" SnapsToDevicePixels="True"/>
<TextBlock Text="{Binding }" />
</DockPanel>
</DataTemplate>
Using the DockPanel
with LastChildFill
set to true will keep the glyph on the right of the header and let the label fill the rest of the space. I bound the DockPanel
width to the ActualWidth
of the GridViewColumnHeader
because my columns have no width, which lets them autofit to the content. I did set MinWidth
s on the columns, though, so that the glyph doesn't cover up the column title. The TextBlock Text
is set to an empty binding which displays the column name specified in the header.
This should be working. Please have a look at this fiddle.
$(function() {
$( "#slider" ).slider();
});//Links to jsfiddle must be accompanied by code
Make sure you're loading the libraries in this order: jQuery, jQuery UI CSS, jQuery UI, AngularJS.
#ifndef MY_HEADER_H
# define MY_HEADER_H
//put your function headers here
#endif
MY_HEADER_H
serves as a double-inclusion guard.
For the function declaration, you only need to define the signature, that is, without parameter names, like this:
int foo(char*);
If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.
This declares the function foo
which accepts a char*
and returns an int
.
In your source file, you would have:
#include "my_header.h"
int foo(char* name) {
//do stuff
return 0;
}
Using the request module solved the issue.
// Include the request library for Node.js
var request = require('request');
// Basic Authentication credentials
var username = "vinod";
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
console.log(body); } );
as answered above: Object.keys(obj).length
But: as we have now a real Map class in ES6, I would suggest to use it instead of using the properties of an object.
const map = new Map();
map.set("key", "value");
map.size; // THE fastest way
function amiLoadedInIFrame() {
try {
// Introduce a new propery in window.top
window.top.dummyAttribute = true;
// If window.dummyAttribute is there.. then window and window.top are same intances
return !window.dummyAttribute;
} catch(e) {
// Exception will be raised when the top is in different domain
return true;
}
}
If you have a DataFrame with only one row, then access the first (only) row as a Series using iloc
, and then the value using the column name:
In [3]: sub_df
Out[3]:
A B
2 -0.133653 -0.030854
In [4]: sub_df.iloc[0]
Out[4]:
A -0.133653
B -0.030854
Name: 2, dtype: float64
In [5]: sub_df.iloc[0]['A']
Out[5]: -0.13365288513107493
As jeremyjjbrow said, :active
pseudo won't persist. But there's a hack for doing it on pure css. You can wrap it on a <a>
tag, and apply the :active
on it, like this:
<a class="test">
<img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />
</a>
And the css:
.test:active .crossRotate {
transform: rotate(45deg);
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
}
Try it out... It works (at least on Chrome)!
I prefer a more general solution that will work with either DOS or Unix input. Assuming the input is from STDIN:
while (defined(my $ln = <>))
{
chomp($ln);
chop($ln) if ($ln =~ m/\r$/);
# filter and write
}
On Oracle:
Determine all indexes on table:
SELECT index_name
FROM user_indexes
WHERE table_name = :table
Determine columns indexes and columns on index:
SELECT index_name
, column_position
, column_name
FROM user_ind_columns
WHERE table_name = :table
ORDER BY index_name, column_order
References:
The characters '<', and '>', are to indicate a place-holder, you should remove them to read:
php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME
Internet Explorer has a new feature since IE9 RC: adding <-loopback>
to the proxy bypass list causes WinInet (the network library used by IE) to send requests destined for localhost
and 127.0.0.1
through the defined proxy.
Here's the original announcement by @EricLaw: http://blogs.msdn.com/b/fiddler/archive/2011/02/10/fiddler-is-better-with-internet-explorer-9.aspx
Yes you can use simply
$input_data = $_POST;
or extract() may be useful for you.
For Windows 10 with Anaconda 4.4 Python 3.6:
1st step) conda create -n tensorflow python=3.6
2nd step) activate tensorflow
3rd step) pip3 install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.2.1-cp36-cp36m-win_amd64.whl
Turn on grep
's line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)
tail -f file | grep --line-buffered my_pattern
It looks like a while ago --line-buffered
didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, --line-buffered
is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).
There are 2 methods technically same
First put your cursor on the word and press F2. Replace your word and press Enter.
First put your cursor on the word and left click it. Click "Rename Symbol" option. Replace your word and press Enter.
If you want a more accurate measurement than the answer above:
set statistics time on
-- Query 1 goes here
-- Query 2 goes here
set statistics time off
The results will be in the Messages window.
Update (2015-07-29):
By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats
that may also be of value:
-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.
-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';
SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0))
AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
(OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
(DB_NAME(database_id)=@DbName OR @DbName IS NULL)
And if you want to retain any of the aggregation info from the second level of the multiindex you can try this:
In [1]: new_cols = [''.join(t) for t in df.columns]
Out[1]:
['USAF',
'WBAN',
'day',
'month',
's_CDsum',
's_CLsum',
's_CNTsum',
's_PCsum',
'tempfamax',
'tempfamin',
'year']
In [2]: df.columns = new_cols
In the current version on select2
- v4.0.1
you can set the value like this:
var $example = $('.js-example-programmatic').select2();_x000D_
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });_x000D_
_x000D_
// Option 2 if you can't trigger the change event._x000D_
var $exampleDestroy = $('.js-example-programmatic-destroy').select2();_x000D_
$(".js-programmatic-set-val").on("click", function () { $exampleDestroy.val("CA").select2('destroy').select2(); });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />_x000D_
_x000D_
using "trigger(change)"_x000D_
<select class="js-example-programmatic">_x000D_
<optgroup label="Alaskan/Hawaiian Time Zone">_x000D_
<option value="AK">Alaska</option>_x000D_
<option value="HI">Hawaii</option>_x000D_
</optgroup>_x000D_
<optgroup label="Pacific Time Zone">_x000D_
<option value="CA">California</option>_x000D_
<option value="NV">Nevada</option>_x000D_
<option value="OR">Oregon</option>_x000D_
<option value="WA">Washington</option>_x000D_
</optgroup>_x000D_
<optgroup label="Mountain Time Zone">_x000D_
<option value="AZ">Arizona</option>_x000D_
<option value="CO">Colorado</option>_x000D_
<option value="ID">Idaho</option>_x000D_
<option value="MT">Montana</option>_x000D_
<option value="NE">Nebraska</option>_x000D_
<option value="NM">New Mexico</option>_x000D_
<option value="ND">North Dakota</option>_x000D_
<option value="UT">Utah</option>_x000D_
<option value="WY">Wyoming</option>_x000D_
</optgroup>_x000D_
<optgroup label="Central Time Zone">_x000D_
<option value="AL">Alabama</option>_x000D_
<option value="AR">Arkansas</option>_x000D_
<option value="IL">Illinois</option>_x000D_
<option value="IA">Iowa</option>_x000D_
<option value="KS">Kansas</option>_x000D_
<option value="KY">Kentucky</option>_x000D_
<option value="LA">Louisiana</option>_x000D_
<option value="MN">Minnesota</option>_x000D_
<option value="MS">Mississippi</option>_x000D_
<option value="MO">Missouri</option>_x000D_
<option value="OK">Oklahoma</option>_x000D_
<option value="SD">South Dakota</option>_x000D_
<option value="TX">Texas</option>_x000D_
<option value="TN">Tennessee</option>_x000D_
<option value="WI">Wisconsin</option>_x000D_
</optgroup>_x000D_
<optgroup label="Eastern Time Zone">_x000D_
<option value="CT">Connecticut</option>_x000D_
<option value="DE">Delaware</option>_x000D_
<option value="FL">Florida</option>_x000D_
<option value="GA">Georgia</option>_x000D_
<option value="IN">Indiana</option>_x000D_
<option value="ME">Maine</option>_x000D_
<option value="MD">Maryland</option>_x000D_
<option value="MA">Massachusetts</option>_x000D_
<option value="MI">Michigan</option>_x000D_
<option value="NH">New Hampshire</option>_x000D_
<option value="NJ">New Jersey</option>_x000D_
<option value="NY">New York</option>_x000D_
<option value="NC">North Carolina</option>_x000D_
<option value="OH">Ohio</option>_x000D_
<option value="PA">Pennsylvania</option>_x000D_
<option value="RI">Rhode Island</option>_x000D_
<option value="SC">South Carolina</option>_x000D_
<option value="VT">Vermont</option>_x000D_
<option value="VA">Virginia</option>_x000D_
<option value="WV">West Virginia</option>_x000D_
</optgroup>_x000D_
</select>_x000D_
_x000D_
using destroy: _x000D_
<select class="js-example-programmatic">_x000D_
<optgroup label="Alaskan/Hawaiian Time Zone">_x000D_
<option value="AK">Alaska</option>_x000D_
<option value="HI">Hawaii</option>_x000D_
</optgroup>_x000D_
<optgroup label="Pacific Time Zone">_x000D_
<option value="CA">California</option>_x000D_
<option value="NV">Nevada</option>_x000D_
<option value="OR">Oregon</option>_x000D_
<option value="WA">Washington</option>_x000D_
</optgroup>_x000D_
<optgroup label="Mountain Time Zone">_x000D_
<option value="AZ">Arizona</option>_x000D_
<option value="CO">Colorado</option>_x000D_
<option value="ID">Idaho</option>_x000D_
<option value="MT">Montana</option>_x000D_
<option value="NE">Nebraska</option>_x000D_
<option value="NM">New Mexico</option>_x000D_
<option value="ND">North Dakota</option>_x000D_
<option value="UT">Utah</option>_x000D_
<option value="WY">Wyoming</option>_x000D_
</optgroup>_x000D_
<optgroup label="Central Time Zone">_x000D_
<option value="AL">Alabama</option>_x000D_
<option value="AR">Arkansas</option>_x000D_
<option value="IL">Illinois</option>_x000D_
<option value="IA">Iowa</option>_x000D_
<option value="KS">Kansas</option>_x000D_
<option value="KY">Kentucky</option>_x000D_
<option value="LA">Louisiana</option>_x000D_
<option value="MN">Minnesota</option>_x000D_
<option value="MS">Mississippi</option>_x000D_
<option value="MO">Missouri</option>_x000D_
<option value="OK">Oklahoma</option>_x000D_
<option value="SD">South Dakota</option>_x000D_
<option value="TX">Texas</option>_x000D_
<option value="TN">Tennessee</option>_x000D_
<option value="WI">Wisconsin</option>_x000D_
</optgroup>_x000D_
<optgroup label="Eastern Time Zone">_x000D_
<option value="CT">Connecticut</option>_x000D_
<option value="DE">Delaware</option>_x000D_
<option value="FL">Florida</option>_x000D_
<option value="GA">Georgia</option>_x000D_
<option value="IN">Indiana</option>_x000D_
<option value="ME">Maine</option>_x000D_
<option value="MD">Maryland</option>_x000D_
<option value="MA">Massachusetts</option>_x000D_
<option value="MI">Michigan</option>_x000D_
<option value="NH">New Hampshire</option>_x000D_
<option value="NJ">New Jersey</option>_x000D_
<option value="NY">New York</option>_x000D_
<option value="NC">North Carolina</option>_x000D_
<option value="OH">Ohio</option>_x000D_
<option value="PA">Pennsylvania</option>_x000D_
<option value="RI">Rhode Island</option>_x000D_
<option value="SC">South Carolina</option>_x000D_
<option value="VT">Vermont</option>_x000D_
<option value="VA">Virginia</option>_x000D_
<option value="WV">West Virginia</option>_x000D_
</optgroup>_x000D_
</select>_x000D_
_x000D_
<button class="js-programmatic-set-val">set value</button>
_x000D_
Well it depends, if you want to bind datas, there shouldn't be any formatting in it, otherwise you can bind-html
and do description.replace(/\\n/g, '<br>')
not sure it's what you want though.
Or... You could place the image in an anchor tag. Cause I had the same problem and it fixed it without issue. A lot of people use local paths before they publish their site and photos. Just make sure you go back and fix that in the final editing phase.
Another source of this error is that you have 2 or more same table names which have the same foreign key names. This sometimes happens to people who use modelling and design software, like Mysql Workbench, and later generate the script from the design.
var ul = document.getElementById("yourElementId");
while (ul.firstChild)
ul.removeChild(ul.firstChild);
I would have thought this would have been answered already - but surely what you want is this: box-shadow: 0 0 3px #CC0000;
Example: http://jsfiddle.net/vmzLW/
Two suggestions:
std::deque
instead of std::vector
for better performance in your specific case and use the method std::deque::pop_front()
.&
in std::vector<ScanRule>& topPriorityRules;
Running ps -e
does the trick. Found the answer here.
You use the error_page property in the nginx config.
For example, if you intend to set the 404 error page to /404.html
, use
error_page 404 /404.html;
Setting the 500 error page to /500.html
is just as easy as:
error_page 500 /500.html;
When looking at an input with a type of number, you'll notice the spinner buttons (up/down) on the right-hand side of the input field. These spinners aren't always desirable, thus the code below removes such styling to render an input that resembles that of an input with a type of text.
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
}
import java.util.LinkedList;
import java.util.Queue;
class MyStack {
Queue<Integer> queue1 = new LinkedList<Integer>();
Queue<Integer> queue2 = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
if(isEmpty()){
queue1.offer(x);
}else{
if(queue1.size()>0){
queue2.offer(x);
int size = queue1.size();
while(size>0){
queue2.offer(queue1.poll());
size--;
}
}else if(queue2.size()>0){
queue1.offer(x);
int size = queue2.size();
while(size>0){
queue1.offer(queue2.poll());
size--;
}
}
}
}
// Removes the element on top of the stack.
public void pop() {
if(queue1.size()>0){
queue1.poll();
}else if(queue2.size()>0){
queue2.poll();
}
}
// Get the top element. You can make it more perfect just example
public int top() {
if(queue1.size()>0){
return queue1.peek();
}else if(queue2.size()>0){
return queue2.peek();
}
return 0;
}
// Return whether the stack is empty.
public boolean isEmpty() {
return queue1.isEmpty() && queue2.isEmpty();
}
}
When initializing your repository, skip the git command that contains
-u
and it shouldn't be an issue.
Get FullName in ListBox of files (full path) list (Thomas Levesque answer modificaton, thanks Thomas):
...
string tmpStr = "";
foreach (var item in listBoxFiles.SelectedItems)
{
tmpStr += listBoxFiles.GetItemText(item) + "\n";
}
MessageBox.Show(tmpStr);
...
Use the TextFieldParser class built into the .Net framework.
Here's some code copied from an MSDN forum post by Paul Clement. It converts the CSV into a new in-memory DataTable and then binds the DataGridView to the DataTable
Dim TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Documents and Settings\...\My Documents\My Database\Text\SemiColonDelimited.txt")
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
Dim TextFileTable As DataTable = Nothing
Dim Column As DataColumn
Dim Row As DataRow
Dim UpperBound As Int32
Dim ColumnCount As Int32
Dim CurrentRow As String()
While Not TextFileReader.EndOfData
Try
CurrentRow = TextFileReader.ReadFields()
If Not CurrentRow Is Nothing Then
''# Check if DataTable has been created
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
''# Get number of columns
UpperBound = CurrentRow.GetUpperBound(0)
''# Create new DataTable
For ColumnCount = 0 To UpperBound
Column = New DataColumn()
Column.DataType = System.Type.GetType("System.String")
Column.ColumnName = "Column" & ColumnCount
Column.Caption = "Column" & ColumnCount
Column.ReadOnly = True
Column.Unique = False
TextFileTable.Columns.Add(Column)
Next
End If
Row = TextFileTable.NewRow
For ColumnCount = 0 To UpperBound
Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
Next
TextFileTable.Rows.Add(Row)
End If
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
TextFileReader.Dispose()
frmMain.DataGrid1.DataSource = TextFileTable
As Johnathan Suggested, you would either want to save it in a cookie or a session.
The easier way would be to use a Session variable.
session_start();
if(!isset($_SESSION['org_referer']))
{
$_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}
Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.
Approach 2 will always return a count that matches your result set.
I suggest you link the sub-query to your outer query though, to guarantee that the condition on your count matches the condition on the dataset.
SELECT
mt.my_row,
(SELECT COUNT(mt2.my_row) FROM my_table mt2 WHERE mt2.foo = mt.foo) as cnt
FROM my_table mt
WHERE mt.foo = 'bar';
A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :
@Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
1
2
Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.
So this is a Queue only if used in conjunction with add.
Try this :
@Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.push(1);
queue.push(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
2
1
According to my research there is no way to do this exactly the way you want. You can manually re-create the table and copy the data, or SSMS can (and will) do this for you (when you drag and drop a column to a different order, it does this). In fact it souldn't matter what order the columns are... As an alternative solution you can select the data you want in the order you desired. For example, instead of using asterisk (*) in select, specify the column names in some order... Lets say MyTable has col1, col2, col3, colNew columns.
Instead of:
SELECT * FROM MyTable
You can use:
SELECT col1, colNew, col2, col3 FROM MyTable
Guid.NewGuid()
, as it creates GUIDs as intended.
Guid.NewGuid()
creates an empty Guid
object, initializes it by calling CoCreateGuid
and returns the object.
new Guid()
merely creates an empty GUID (all zeros, I think).
I guess they had to make the constructor public as Guid
is a struct
.
You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode
Edit: in case something happens to kill the msdn link, here is the content:
Specifying Document Compatibility Modes
You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.
<html> <head> <!-- Enable IE9 Standards mode --> <meta http-equiv="X-UA-Compatible" content="IE=9" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.
The following example specifies EmulateIE7 mode.
<html> <head> <!-- Mimic Internet Explorer 7 --> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.
view = MyCustomView(frame: CGRectZero)
In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.
You can use a Contains
query for this:
var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));
I encountered the similar problem after installing new software. In my case, the problem was solved by: (1) restoring .p2 subdirectory under my home directory; and (2) editing eclipse.init file to have the updated java directory.
Using autoview
image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true
JAX-WS - is Java API for the XML-Based Web Services - a standard way to develop a Web- Services in SOAP notation (Simple Object Access Protocol).
Calling of the Web Services is performed via remote procedure calls. For the exchange of information between the client and the Web Service is used SOAP protocol. Message exchange between the client and the server performed through XML- based SOAP messages.
Clients of the JAX-WS Web- Service need a WSDL file to generate executable code that the clients can use to call Web- Service.
JAX-RS - Java API for RESTful Web Services. RESTful Web Services are represented as resources and can be identified by Uniform Resource Identifiers (URI). Remote procedure call in this case is represented a HTTP- request and the necessary data is passed as parameters of the query. Web Services RESTful - more flexible, can use several different MIME- types. Typically used for XML data exchange or JSON (JavaScript Object Notation) data exchange...
In my case, the issue was new sites had an implicit deny of all IP addresses unless an explicit allow was created. To fix: Under the site in Features View: Under the IIS Section > IP Address and Domain Restrictions > Edit Feature Settings > Set 'Access for unspecified clients:' to 'Allow'
you should do as:
getline(name, sizeofname, '\n');
strtok(name, " ");
This will give you the "joht" in name then to get next token,
temp = strtok(NULL, " ");
temp will get "smith" in it. then you should use string concatination to append the temp at end of name. as:
strcat(name, temp);
(you may also append space first, to obtain a space in between).
You can use the form reference which exists on all inputs, this is much faster than .closest()
(5-10 times faster in Chrome and IE8). Works on IE6 & 7 too.
var input = $('input[type=submit]');
var form = input.length > 0 ? $(input[0].form) : $();
ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:
p.GetCoordinates(out var x, out _); // I only care about x
P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.
Here's a 2020 answer with a Hook:
function useDragging() {
const [isDragging, setIsDragging] = useState(false);
const [pos, setPos] = useState({ x: 0, y: 0 });
const ref = useRef(null);
function onMouseMove(e) {
if (!isDragging) return;
setPos({
x: e.x - ref.current.offsetWidth / 2,
y: e.y - ref.current.offsetHeight / 2,
});
e.stopPropagation();
e.preventDefault();
}
function onMouseUp(e) {
setIsDragging(false);
e.stopPropagation();
e.preventDefault();
}
function onMouseDown(e) {
if (e.button !== 0) return;
setIsDragging(true);
setPos({
x: e.x - ref.current.offsetWidth / 2,
y: e.y - ref.current.offsetHeight / 2,
});
e.stopPropagation();
e.preventDefault();
}
// When the element mounts, attach an mousedown listener
useEffect(() => {
ref.current.addEventListener("mousedown", onMouseDown);
return () => {
ref.current.removeEventListener("mousedown", onMouseDown);
};
}, [ref.current]);
// Everytime the isDragging state changes, assign or remove
// the corresponding mousemove and mouseup handlers
useEffect(() => {
if (isDragging) {
document.addEventListener("mouseup", onMouseUp);
document.addEventListener("mousemove", onMouseMove);
} else {
document.removeEventListener("mouseup", onMouseUp);
document.removeEventListener("mousemove", onMouseMove);
}
return () => {
document.removeEventListener("mouseup", onMouseUp);
document.removeEventListener("mousemove", onMouseMove);
};
}, [isDragging]);
return [ref, pos.x, pos.y, isDragging];
}
Then a component that uses the hook:
function Draggable() {
const [ref, x, y, isDragging] = useDragging();
return (
<div
ref={ref}
style={{
position: "absolute",
width: 50,
height: 50,
background: isDragging ? "blue" : "gray",
left: x,
top: y,
}}
></div>
);
}
Unset will destroy a particular session variable whereas session_destroy()
will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
If you want to ignore namespaces completely, you can use this:
static void Main(string[] args)
{
string xml =
"<My_RootNode xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"\">\n" +
" <id root=\"2.16.840.1.113883.3.51.1.1.1\" extension=\"someIdentifier\" xmlns=\"urn:hl7-org:v3\" />\n" +
" <creationTime xsi:nil=\"true\" xmlns=\"urn:hl7-org:v3\" />\n" +
"</My_RootNode>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode idNode = doc.SelectSingleNode("/*[local-name()='My_RootNode']/*[local-name()='id']");
}
Try it
<!- HTML -->
<tr onmouseover="mOvr(this,'#ffa');" onmouseout="mOut(this,'#FFF');">
<script>
function mOvr(src,clrOver) {
if (!src.contains(event.fromElement)) {
src.bgColor = clrOver;
}
}
function mOut(src,clrIn) {
if (!src.contains(event.toElement)) {
src.bgColor = clrIn;
}
}
</script>
- Abstract class
is one which can't be instantiated, i.e. its object
cannot be created.
- Abstract method
are method's declaration without its definition.
- A Non-abstract class
can only have Non-abstract methods.
- An Abstract class
can have both the Non-abstract as well as Abstract methods.
- If the Class
has an Abstract method
then the class must also be Abstract.
- An Abstract method
must be implemented by the very first Non-Abstract sub-class.
- Abstract class
in Design patterns
are used to encapsulate the behaviors that keeps changing.
Your method showFile() declares that it can throw an IOException. Since this is a checked exception, any call to showFile() method must handle the exception somehow. One option is to wrap the call to showFile() in a try-catch block.
try {
showFile();
}
catch(IOException e) {
// Code to handle an IOException here
}
protected void Application_Start(object sender, EventArgs e)
{
string path = Server.MapPath("/");
//or
string path2 = Server.MapPath("~");
//depends on your application needs
}
From the docs:-
Your app gradle file now has to explicitly list
com.google.firebase:firebase-core
as a dependency for Firebase services to work as expected.
Add:
implementation 'com.google.firebase:firebase-core:16.0.1'
and in top level gradle file use the latest version of google play services:
classpath 'com.google.gms:google-services:4.0.2'
https://firebase.google.com/support/release-notes/android
https://bintray.com/android/android-tools/com.google.gms.google-services
Note:
You need to add the google()
repo in the top level gradle file, as specified in the firebase docs and also it should be before jcenter()
:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'com.google.gms:google-services:4.0.2'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
I have had this same problem with the x64 version installation. It relates (in my case at least) to the dexplore.exe installation. I uninstalled dexplore, reinstalled it, did a heap of registry changes, etc. as per various blogs and SDKs all to no avail. What finally fixed it for me was editing this registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Installer\DisableBrowse
I changed the value to 0. Once the SDK had installed (quite happily this time) I set the value back to 1.
What alerted me to the possible error was the following in the SDK setup log:
12:19:42 PM Friday, 8 January 2010: SFX C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\SFX\dexplore.exe installation started with log file C:\TEMP\Microsoft Windows SDK for Windows 7_dd2d9383-116d-441f-85b3-7c16aeb3568e_SFX.log
12:19:47 PM Friday, 8 January 2010: C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\SFX\dexplore.exe installation failed with return code 1625
And this in the dexplore installation logfile:
MSI (s) (E4:7C) [12:19:46:680]: Machine policy value 'DisableBrowse' is 1
MSI (s) (E4:7C) [12:19:46:680]: Adding new sources is not allowed.
MSI (s) (E4:7C) [12:19:46:680]: Warning: rejected attempt to add new source 'c:\eb66d60e4283bfc2986755fa\' (product: {6753B40C-0FBD-3BED-8A9D-0ACAC2DCD85D})
MSI (s) (E4:7C) [12:19:46:680]: MSI_LUA: Elevation prompt disabled for silent installs
MSI (s) (E4:7C) [12:19:46:680]: Note: 1: 1729
MSI (s) (E4:7C) [12:19:46:680]: Product: Microsoft Document Explorer 2008 -- Configuration failed.
I hope this is of assistance in your situation.
var is a "contextual keyword" in C# meaning you can only use it as a local variable implicitly in the context of the same class that you are using the variable. If you try to use it in a class that you call from "Main" or some other exterior class, or an interface for example you will get the error CS0825 < https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs0825 >
See the remarks about when you can and can't use it in the documentation here: < https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables#remarks >
Basically, you should only use this when you are declaring a variable with an implicit value such as "var myValue = "This is the value"; This saves a little time in comparison to saying "string" for example but IMHO not much time is saved and places a constraint on the scalability of your project.
You can do like this
SELECT something
FROM
(a LEFT JOIN b ON a.a_id = b.b_id) LEFT JOIN c on a.a_aid = c.c_id
WHERE a.parent_id = 'rootID'
The function example:
func file_is_exists(f string) bool {
_, err := os.Stat(f)
if os.IsNotExist(err) {
return false
}
return err == nil
}
I know this is old but this answer still applies to newer Core releases.
If by chance your DbContext
implementation is in a different project than your startup project and you run ef migrations
, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations
know where they're at.
dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]
Both -s
and -p
are optionals that default to the current folder.
Here is an answer by way of example:
In order to make sure data loggers are online a cron
script runs every 15 minutes that looks like this:
#!/bin/bash
#
if ! ping -c 1 SOLAR &>/dev/null
then
echo "SUBJECT: SOLAR is not responding to ping" | ssmtp [email protected]
echo "SOLAR is not responding to ping" | ssmtp [email protected]
else
echo "SOLAR is up"
fi
#
if ! ping -c 1 OUTSIDE &>/dev/null
then
echo "SUBJECT: OUTSIDE is not responding to ping" | ssmtp [email protected]
echo "OUTSIDE is not responding to ping" | ssmtp [email protected]
else
echo "OUTSIDE is up"
fi
#
...and so on for each data logger that you can see in the montage at http://www.SDsolarBlog.com/montage
FYI, using &>/dev/null
redirects all output from the command, including errors, to /dev/null
(The conditional only requires the exit status
of the ping
command)
Also FYI, note that since cron
jobs run as root
there is no need to use sudo ping
in a cron
script.
In my case the controller class was annotated with @Controller
. Changing that to @RestController
resolved the problem.
Basically @RestController
is @Controller + @ResponseBody
So either use @RestController
, or @Controller
with @ResponseBody
annotation with each method.
Some useful notes here : https://www.genuitec.com/spring-frameworkrestcontroller-vs-controller/
Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.
A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId
attribute set to True
, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show
without creating a new instance of the class.
Step away from this, and treat your form as an object instead - expose Property Get
members and abstract away the form's controls - the calling code doesn't care about controls anyway:
Option Explicit
Private cancelling As Boolean
Public Property Get UserId() As String
UserId = txtUserId.Text
End Property
Public Property Get Password() As String
Password = txtPassword.Text
End Property
Public Property Get IsCancelled() As Boolean
IsCancelled = cancelling
End Property
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub CancelButton_Click()
cancelling = True
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
cancelling = True
Cancel = True
Me.Hide
End If
End Sub
Now the calling code can do this (assuming the UserForm was named LoginPrompt
):
With New LoginPrompt
.Show vbModal
If .IsCancelled Then Exit Sub
DoSomething .UserId, .Password
End With
Where DoSomething
would be some procedure that requires the two string parameters:
Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
'work with the parameter values, regardless of where they came from
End Sub
I used the svn2git script and works like a charm.
Have you checked strncpy?
char * strncpy ( char * destination, const char * source, size_t num );
You must realize that begin and end actually defines a num of bytes to be copied from one place to another.
Python has a keyboard module with many features. Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard # using module keyboard
while True: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except:
break # if user pressed a key other than the given key the loop will break
/*
* Child component
*/
class Child extends React.Component {
render() {
return (
<div id="child">
<h1 ref={(node) => { this.heading = node; }}>
Child
</h1>
</div>
);
}
}
/*
* Parent component
*/
class Parent extends React.Component {
componentDidMount() {
// Access child component refs via parent component instance like this
console.log(this.child.heading.getDOMNode());
}
render() {
return (
<div>
<Child
ref={(node) => { this.child = node; }}
/>
</div>
);
}
}
No one actually wrote this yet I guess but you can do:
round(12, -1) --> 10
round(18, -1) --> 20
Depending on your version:
Python 2.x:
for key, val in PIX0.iteritems():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
Python 3.x:
for key, val in PIX0.items():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))
You should also get in the habit of using the new string formatting syntax ({}
instead of %
operator) from PEP 3101:
UITextView doesn't provide an intrinsicContentSize, so you need to subclass it and provide one. To make it grow automatically, invalidate the intrinsicContentSize in layoutSubviews. If you use anything other than the default contentInset (which I do not recommend), you may need to adjust the intrinsicContentSize calculation.
@interface AutoTextView : UITextView
@end
#import "AutoTextView.h"
@implementation AutoTextView
- (void) layoutSubviews
{
[super layoutSubviews];
if (!CGSizeEqualToSize(self.bounds.size, [self intrinsicContentSize])) {
[self invalidateIntrinsicContentSize];
}
}
- (CGSize)intrinsicContentSize
{
CGSize intrinsicContentSize = self.contentSize;
// iOS 7.0+
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {
intrinsicContentSize.width += (self.textContainerInset.left + self.textContainerInset.right ) / 2.0f;
intrinsicContentSize.height += (self.textContainerInset.top + self.textContainerInset.bottom) / 2.0f;
}
return intrinsicContentSize;
}
@end
Here's what I found.
stop:
schtasks /end /s <machine name> /tn <task name>
start:
schtasks /run /s <machine name> /tn <task name>
C:\>schtasks /?
SCHTASKS /parameter [arguments]
Description:
Enables an administrator to create, delete, query, change, run and
end scheduled tasks on a local or remote system. Replaces AT.exe.
Parameter List:
/Create Creates a new scheduled task.
/Delete Deletes the scheduled task(s).
/Query Displays all scheduled tasks.
/Change Changes the properties of scheduled task.
/Run Runs the scheduled task immediately.
/End Stops the currently running scheduled task.
/? Displays this help message.
Examples:
SCHTASKS
SCHTASKS /?
SCHTASKS /Run /?
SCHTASKS /End /?
SCHTASKS /Create /?
SCHTASKS /Delete /?
SCHTASKS /Query /?
SCHTASKS /Change /?
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
If I may quote my answer to the question StompChicken mentioned:
The core issue here is that stemming algorithms operate on a phonetic basis with no actual understanding of the language they're working with.
As they have no understanding of the language and do not run from a dictionary of terms, they have no way of recognizing and responding appropriately to irregular cases, such as "run"/"ran".
If you need to handle irregular cases, you'll need to either choose a different approach or augment your stemming with your own custom dictionary of corrections to run after the stemmer has done its thing.
If you need textarea with auto height, Use follows with pure javascript,
function auto_height(elem) { /* javascript */_x000D_
elem.style.height = "1px";_x000D_
elem.style.height = (elem.scrollHeight)+"px";_x000D_
}
_x000D_
.auto_height { /* CSS */_x000D_
width: 100%;_x000D_
}
_x000D_
<textarea rows="1" class="auto_height" oninput="auto_height(this)"></textarea>
_x000D_
What makes the code ugly is the special-handling for the first case. Most of the lines in this small snippet are devoted, not to doing the code's routine job, but to handling that special case. And that's what alternatives like gimel's solve, by moving the special handling outside the loop. There is one special case (well, you could see both start and end as special cases - but only one of them needs to be treated specially), so handling it inside the loop is unnecessarily complicated.
javascript:document.getElementsByClassName("video-stream html5-main-video")[0].playbackRate = 0.1;
you can put any number here just don't go to far so you don't overun your computer.
The constructor needs to be like a factory method and return what you want. If you need additional methods/properties, you can add them to the object before returning it.
function NotImplementedError(message) { return new Error("Not implemented", message); }
x = new NotImplementedError();
Though I'm not sure why you'd need to do this. Why not just use new Error...
? Custom exceptions don't really add much in JavaScript (or probably any untyped language).
Here's a funny answer.
You can declare a final one-element array and change the elements of the array all you want apparently. I'm sure it breaks the very reason why this compiler rule was implemented in the first place but it's handy when you're in a time-bind as I was today.
I actually can't claim credit for this one. It was IntelliJ's recommendation! Feels a bit hacky. But doesn't seem as bad as a global variable so I thought it worth mentioning here. It's just one solution to the problem. Not necessarily the best one.
final int[] tapCount = {0};
addSiteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tapCount[0]++;
}
});
Multiplatform, stable, best solution:
use fkill to kill process which is taking your port:
fkill -f :8080
To install fkill use command: npm i -g fkill
This works for me for video in a div container.
.videoContainer _x000D_
{_x000D_
position:absolute;_x000D_
height:100%;_x000D_
width:100%;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.videoContainer video _x000D_
{_x000D_
min-width: 100%;_x000D_
min-height: 100%;_x000D_
}
_x000D_
Reference: http://www.codesynthesis.co.uk/tutorials/html-5-full-screen-and-responsive-videos
My approach would be:
/// <summary>
/// Appends CSS Class seprated by a space character
/// </summary>
/// <param name="control">Target control</param>
/// <param name="cssClass">CSS class name to append</param>
public static void AppendCss(HtmlGenericControl control, string cssClass)
{
// Ensure CSS class is definied
if (string.IsNullOrEmpty(cssClass)) return;
// Append CSS class
if (string.IsNullOrEmpty(control.Attributes["class"]))
{
// Set our CSS Class as only one
control.Attributes["class"] = cssClass;
}
else
{
// Append new CSS class with space as seprator
control.Attributes["class"] += (" " + cssClass);
}
}
On instances of object you also have the:
__class__
attribute. Here is a sample taken from Python 3.3 console
>>> str = "str"
>>> str.__class__
<class 'str'>
>>> i = 2
>>> i.__class__
<class 'int'>
>>> class Test():
... pass
...
>>> a = Test()
>>> a.__class__
<class '__main__.Test'>
Beware that in python 3.x and in New-Style classes (aviable optionally from Python 2.6) class and type have been merged and this can sometime lead to unexpected results. Mainly for this reason my favorite way of testing types/classes is to the isinstance built in function.
Tested On Ubuntu 20, sudo chown -R $USER:$USER /var/www
Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:
my_string = "The quick brown dog " \
"jumped over the lazy fox"
If you run SHOW VARIABLES
from a mysql console you can look for basedir.
When I run the following:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'basedir';
on my system I get /usr/local/mysql
as the Value returned.
(I am not using MAMP - I installed MySQL with homebrew.
mysqld
on my machine is in /usr/local/mysql/bin
so the basedir is where most everything will be installed to.
Also util:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'datadir';
To find where the DBs are stored.
For more: http://dev.mysql.com/doc/refman/5.0/en/show-variables.html
and http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_basedir