Same issue on Fedora 23
. I had to reinstall python3-pip
to generate the proper pip3
folders in /usr/bin/
.
sudo dnf reinstall python3-pip
you can use
<a href="\\computername\folder">Open folder</a>
in Internet Explorer
I had this issue as well, and was tripped up for a while on it. I wanted to display 0.00 as 0 and otherwise keep the decimal point. The following didn't work:
CASE WHEN Amount= 0 THEN CONVERT(VARCHAR(30), Amount, 1) ELSE Amount END
Because the resulting column was forced to be a MONEY column. To resolve it, the following worked
CASE WHEN Amount= 0 THEN CONVERT(VARCHAR(30), '0', 1) ELSE CONVERT (VARCHAR(30), Amount, 1) END
This mattered because my final destination column was a VARCHAR(30), and the consumers of that column would error out if an amount was '0.00' instead of '0'.
make sure you check Environment variables versions of java , it could be just the difference between the versions of JAVA_HOME
(JDK path) and JRE_HOME
(JRE path) , that cause the problem
You can also use String.valueOf((Object) nullableString)
like
switch (String.valueOf((Object) nullableString)) {
case "someCase"
//...
break;
...
case "null": // or default:
//...
break;
}
See interesting SO Q/A: Why does String.valueOf(null) throw a NullPointerException
You say
The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything).
In fact, it does do something (it causes your code to throw a FormatException
:"Invalid character in a Base-64 string") because the Convert.FromBase64String
does not consider "\0" to be a valid Base64 character.
byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
byte[] data2 = Convert.FromBase64String("AAAA"); // Works
Solution: Get rid of the zero termination. (Maybe call .Trim("\0")
)
Notes:
The MSDN docs for Convert.FromBase64String
say it will throw a FormatException
when
The length of s, ignoring white space characters, is not zero or a multiple of 4.
-or-
The format of s is invalid. s contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
and that
The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'.
find /usr/lib/jvm/java-1.x.x-openjdk
vim /etc/profile
Prepend sudo if logged in as not-privileged user, ie. sudo vim
add:
export JAVA_HOME="path that you found"
export PATH=$JAVA_HOME/bin:$PATH
source /etc/profile
to apply changes immediately in your current shellthe problem here is that by using the apostrophes you are setting the value being passed to be a string, when in fact, as @Shijo stated from the documentation, the function is expecting a label or list, but not a string! If the list contains each of the name of the columns beings passed for both the left and right dataframe, then each column-name must individually be within apostrophes. With what has been stated, we can understand why this is inccorect:
new_df = pd.merge(A_df, B_df, how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')
And this is the correct way of using the function:
new_df = pd.merge(A_df, B_df, how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])
I doubt that this is what you want but your question is a little bit vague
Dim totalCount As Int32 = DataTable1.Columns.Count * DataTable1.Rows.Count
If all your columns are numeric-columns you might want this:
You could use DataTable.Compute to Sum
all values in the column.
Dim totalCount As Double
For Each col As DataColumn In DataTable1.Columns
totalCount += Double.Parse(DataTable1.Compute(String.Format("SUM({0})", col.ColumnName), Nothing).ToString)
Next
After you've edited your question and added more informations, this should work:
Dim totalRow = DataTable1.NewRow
For Each col As DataColumn In DataTable1.Columns
totalRow(col.ColumnName) = Double.Parse(DataTable1.Compute("SUM(" & col.ColumnName & ")", Nothing).ToString)
Next
DataTable1.Rows.Add(totalRow)
This also need.
<?php
header("Access-Control-Allow-Origin: *");
Yes, views can have a clustered index assigned and, when they do, they'll store temporary results that can speed up resulting queries.
Update: At least three people have voted me down on this one. With all due respect, I think that they are just wrong; Microsoft's own documentation makes it very clear that Views can improve performance.
First, simple views are expanded in place and so do not directly contribute to performance improvements - that much is true. However, indexed views can dramatically improve performance.
Let me go directly to the documentation:
After a unique clustered index is created on the view, the view's result set is materialized immediately and persisted in physical storage in the database, saving the overhead of performing this costly operation at execution time.
Second, these indexed views can work even when they are not directly referenced by another query as the optimizer will use them in place of a table reference when appropriate.
Again, the documentation:
The indexed view can be used in a query execution in two ways. The query can reference the indexed view directly, or, more importantly, the query optimizer can select the view if it determines that the view can be substituted for some or all of the query in the lowest-cost query plan. In the second case, the indexed view is used instead of the underlying tables and their ordinary indexes. The view does not need to be referenced in the query for the query optimizer to use it during query execution. This allows existing applications to benefit from the newly created indexed views without changing those applications.
This documentation, as well as charts demonstrating performance improvements, can be found here.
Update 2: the answer has been criticized on the basis that it is the "index" that provides the performance advantage, not the "View." However, this is easily refuted.
Let us say that we are a software company in a small country; I'll use Lithuania as an example. We sell software worldwide and keep our records in a SQL Server database. We're very successful and so, in a few years, we have 1,000,000+ records. However, we often need to report sales for tax purposes and we find that we've only sold 100 copies of our software in our home country. By creating an indexed view of just the Lithuanian records, we get to keep the records we need in an indexed cache as described in the MS documentation. When we run our reports for Lithuanian sales in 2008, our query will search through an index with a depth of just 7 (Log2(100) with some unused leaves). If we were to do the same without the VIEW and just relying on an index into the table, we'd have to traverse an index tree with a search depth of 21!
Clearly, the View itself would provide us with a performance advantage (3x) over the simple use of the index alone. I've tried to use a real-world example but you'll note that a simple list of Lithuanian sales would give us an even greater advantage.
Note that I'm just using a straight b-tree for my example. While I'm fairly certain that SQL Server uses some variant of a b-tree, I don't know the details. Nonetheless, the point holds.
Update 3: The question has come up about whether an Indexed View just uses an index placed on the underlying table. That is, to paraphrase: "an indexed view is just the equivalent of a standard index and it offers nothing new or unique to a view." If this was true, of course, then the above analysis would be incorrect! Let me provide a quote from the Microsoft documentation that demonstrate why I think this criticism is not valid or true:
Using indexes to improve query performance is not a new concept; however, indexed views provide additional performance benefits that cannot be achieved using standard indexes.
Together with the above quote regarding the persistence of data in physical storage and other information in the documentation about how indices are created on Views, I think it is safe to say that an Indexed View is not just a cached SQL Select that happens to use an index defined on the main table. Thus, I continue to stand by this answer.
You can use this methode to check if a view has children or not .
public static boolean hasChildren(ViewGroup viewGroup) {
return viewGroup.getChildCount() > 0;
}
You should use $(document)
. It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction)
, where the second argument specifies which specific element to target. In this case every element inside the body.
$(document).on('click','body *',function(){
// $(this) = your current element that clicked.
// additional code
});
A more reliable REST endpoint would be http://freegeoip.net/json/
Returns the ip address along with the geo-location too. Also has cross-domain requests enabled (Access-Control-Allow-Origin: *) so you don't have to code around JSONP.
There are basically two most popular answers. The first one basically says
Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.
optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.
or
Optimistic locking works best when you have rare collisions
As it is put on this page.
I created my answer to explain how "keep connection" is related to "low collisions".
To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?
You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.
You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.
In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.
I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.
You don't need floats. In fact, they're useless because floats are ignored in flexbox.
You also don't need CSS positioning.
There are several flex methods available. auto
margins have been mentioned in another answer.
Here are two other options:
justify-content: space-between
and the order
property.justify-content: space-between
and reverse the order of the divs..parent {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
<div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
<div>another child </div>_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
You should be able to cite at least one from the JDK itself. Look in the java.util.collections
package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map
and why Joshua Bloch wrote it that way.
you can use COUNT(DISTINCT ip)
, this will only count distinct values
With bootstrap 3 the best way to go about achieving what you want is ...with offsetting columns. Please see these examples for more detail:
http://getbootstrap.com/css/#grid-offsetting
In short, and without seeing your divs here's an example what might help, without using any custom classes. Just note how the "col-6" is used and how half of that is 3 ...so the "offset-3" is used. Splitting equally will allow the centered spacing you're going for:
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
your centered, floating column
</div></div>
You are using setTimeout
wrong way. The (one of) function signature is setTimeout(callback, delay)
. So you can easily specify what code should be run after what delay.
var codeAddress = (function() {
var index = 0;
var delay = 100;
function GeocodeCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
console.log(results);
}
else alert("Geocode was not successful for the following reason: " + status);
};
return function(vPostCode) {
if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);
index++;
};
})();
This way, every codeAddress()
call will result in geocoder.geocode()
being called 100ms later after previous call.
I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay
variable.
Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)
Method One:
Using the strtotime()
to time is the best format to change the date to the given format.
strtotime()
- Parse about any English textual datetime description into a Unix timestamp
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
Example:
<?php
$timestamp = strtotime( "February 26, 2007" );
print date('Y-m-d', $timestamp );
?>
Output:
2007-02-26
Method Two:
date_format()
- Return a new DateTime object, and then format the date:
<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>
Output:
2013/03/15 00:00:00
In my case, I used the ssl
module to "workaround" the certification like so:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
Then to read your link content, you can use:
urllib.request.urlopen(urllink)
You are not allowed to have a CNAME record for the domain, as the CNAME is an aliasing feature that covers all data types (regardless of whether the client looks for MX, NS or SOA records). CNAMEs also always refer to a new name, not an ip-address, so there are actually two errors in the single line
@ IN CNAME 88.198.38.XXX
Changing that CNAME to an A record should make it work, provided the ip-address you use is the correct one for your Heroku app.
The only correct way in DNS to make a simple domain.com
name work in the browser, is to point the domain to an IP-adress with an A record.
Delete the hidden .git
folder (that you can locate within your project folder) and again start the process of creating a git repository using git init
command.
To change the directory for target dll/exe, use this in your pro file:
CONFIG(debug, debug|release) {
DESTDIR = build/debug
} else {
DESTDIR = build/release
}
You might also want to change directories for other build targets like object files and moc files (check qmake variable reference for details or qmake CONFIG() function reference).
As someone more experienced with Oracle DB, I was concerned about this limit too. I carried out a performance test for a query with ~10'000 parameters in an IN
-list, fetching prime numbers up to 100'000 from a table with the first 100'000 integers by actually listing all the prime numbers as query parameters.
My results indicate that you need not worry about overloading the query plan optimizer or getting plans without index usage, since it will transform the query to use = ANY({...}::integer[])
where it can leverage indices as expected:
-- prepare statement, runs instantaneous:
PREPARE hugeplan (integer, integer, integer, ...) AS
SELECT *
FROM primes
WHERE n IN ($1, $2, $3, ..., $9592);
-- fetch the prime numbers:
EXECUTE hugeplan(2, 3, 5, ..., 99991);
-- EXPLAIN ANALYZE output for the EXECUTE:
"Index Scan using n_idx on primes (cost=0.42..9750.77 rows=9592 width=5) (actual time=0.024..15.268 rows=9592 loops=1)"
" Index Cond: (n = ANY ('{2,3,5,7, (...)"
"Execution time: 16.063 ms"
-- setup, should you care:
CREATE TABLE public.primes
(
n integer NOT NULL,
prime boolean,
CONSTRAINT n_idx PRIMARY KEY (n)
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.primes
OWNER TO postgres;
INSERT INTO public.primes
SELECT generate_series(1,100000);
However, this (rather old) thread on the pgsql-hackers mailing list indicates that there is still a non-negligible cost in planning such queries, so take my word with a grain of salt.
Beside of read.csv(url("..."))
you also can use read.table("http://...")
.
Example:
> sample <- read.table("http://www.ats.ucla.edu/stat/examples/ara/angell.txt")
> sample
V1 V2 V3 V4 V5
1 Rochester 19.0 20.6 15.0 E
2 Syracuse 17.0 15.6 20.2 E
...
43 Atlanta 4.2 70.6 32.6 S
>
You should deploy "Client Profile" instead of "Full Framework" inside a corporation mostly in one case only: you want explicitly deny some .NET features are running on the client computers. The only real case is denying of ASP.NET on the client machines of the corporation, for example, because of security reasons or the existing corporate policy.
Saving of less than 8 MB on client computer can not be a serious reason of "Client Profile" deployment in a corporation. The risk of the necessity of the deployment of the "Full Framework" later in the corporation is higher than costs of 8 MB per client.
This is a solution that saves the profile directory for Firefox (similar to the user-data-dir
(user data directory) in Chrome) (it involves manually copying the directory around. I haven't been able to find another way):
It was tested on Linux.
Short version:
driver.execute_script("window.close()")
time.sleep(0.5)
currentProfilePath = driver.capabilities["moz:profile"]
profileStoragePath = "/tmp/abc"
shutil.copytree(currentProfilePath, profileStoragePath,
ignore_dangling_symlinks=True
)
driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
firefox_profile=FirefoxProfile(profileStoragePath)
)
Long version (with demonstration that it works and a lot of explanation -- see comments in the code)
The code uses localStorage
for demonstration, but it works with cookies as well.
#initial imports
from selenium.webdriver import Firefox, FirefoxProfile
import shutil
import os.path
import time
# Create a new profile
driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
# * I'm using this particular version. If yours is
# named "geckodriver" and placed in system PATH
# then this is not necessary
)
# Navigate to an arbitrary page and set some local storage
driver.get("https://DuckDuckGo.com")
assert driver.execute_script(r"""{
const tmp = localStorage.a; localStorage.a="1";
return [tmp, localStorage.a]
}""") == [None, "1"]
# Make sure that the browser writes the data to profile directory.
# Choose one of the below methods
if 0:
# Wait for some time for Firefox to flush the local storage to disk.
# It's a long time. I tried 3 seconds and it doesn't work.
time.sleep(10)
elif 1:
# Alternatively:
driver.execute_script("window.close()")
# NOTE: It might not work if there are multiple windows!
# Wait for a bit for the browser to clean up
# (shutil.copytree might throw some weird error if the source directory changes while copying)
time.sleep(0.5)
else:
pass
# I haven't been able to find any other, more elegant way.
#`close()` and `quit()` both delete the profile directory
# Copy the profile directory (must be done BEFORE driver.quit()!)
currentProfilePath = driver.capabilities["moz:profile"]
assert os.path.isdir(currentProfilePath)
profileStoragePath = "/tmp/abc"
try:
shutil.rmtree(profileStoragePath)
except FileNotFoundError:
pass
shutil.copytree(currentProfilePath, profileStoragePath,
ignore_dangling_symlinks=True # There's a lock file in the
# profile directory that symlinks
# to some IP address + port
)
driver.quit()
assert not os.path.isdir(currentProfilePath)
# Selenium cleans up properly if driver.quit() is called,
# but not necessarily if the object is destructed
# Now reopen it with the old profile
driver=Firefox(executable_path="geckodriver-v0.28.0-linux64",
firefox_profile=FirefoxProfile(profileStoragePath)
)
# Note that the profile directory is **copied** -- see FirefoxProfile documentation
assert driver.profile.path!=profileStoragePath
assert driver.capabilities["moz:profile"]!=profileStoragePath
# Confusingly...
assert driver.profile.path!=driver.capabilities["moz:profile"]
# And only the latter is updated.
# To save it again, use the same method as previously mentioned
# Check the data is still there
driver.get("https://DuckDuckGo.com")
data = driver.execute_script(r"""return localStorage.a""")
assert data=="1", data
driver.quit()
assert not os.path.isdir(driver.capabilities["moz:profile"])
assert not os.path.isdir(driver.profile.path)
What doesn't work:
Firefox(capabilities={"moz:profile": "/path/to/directory"})
-- the driver will not be able to connect.options=Options(); options.add_argument("profile"); options.add_argument("/path/to/directory"); Firefox(options=options)
-- same as above.Look this:
List<Client> result = clients
.stream()
.filter(c ->
(users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
.collect(Collectors.toList());
It seems you've found your answer already but since you mentioned the active form I'll contribute with one more, even if it differs only ever so slightly.
<?php
$form = ActiveForm::begin();
echo $form->field($model, 'attribute')
->dropDownList(
$items, // Flat array ('id'=>'label')
['prompt'=>''] // options
);
ActiveForm::end();
?>
You mean something like this?
<?php
$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo "{$trend->name}\n";
}
I second Blindy's suggestion to use the MAC address of the (first?) network adapter. Yes, the MAC address can be spoofed, but this has side effects (you don't want two PCs with the same MAC address in the same network), and it's something that "your average pirate" won't do just to be able to use your software. Considering that there's no 100% solution against software piracy, the MAC address is a good compromise, IMO.
Note, however, that the address will change when the user adds, replaces or removes a network card (or replaces his old PC altogether), so be prepared to help your customers and give them a new key when they change their hardware configuration.
As of Django 1.5, there is an update_fields property on model save. eg:
obj.save(update_fields=['field1', 'field2', ...])
https://docs.djangoproject.com/en/dev/ref/models/instances/
I prefer this approach because it doesn't create an atomicity problem if you have multiple web app instances changing different parts of a model instance.
Sooner or later you will have property with special character. You can either use index or combination of index and property.
dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use
<android.support.design.widget.TabLayout
android:id="@+id/tabList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:tabMode="scrollable"/>
You can use FindIndex
var index = Array.FindIndex(myArray, row => row.Author == "xyz");
Edit: I see you have an array of string, you can use any code to match, here an example with a simple contains:
var index = Array.FindIndex(myArray, row => row.Contains("Author='xyz'"));
Maybe you need to match using a regular expression?
int a = 1;
char * c = (char*)(&a); //In C++ should be intermediate cst to void*
This is what I used to kill the progress on port 4200
For linux users:
sudo kill $(sudo lsof -t -i:4200)
You could also try this:
sudo kill `sudo lsof -t -i:4200`
For windows users:
Port number 4200 is already in use. Open the cmd as administrator. Type below command in cmd:
netstat -a -n -o
And then, find port with port number 4200 by right click on terminal and click find, enter 4200 in "find what" and click "find next": Let say you found that port number 4200 is used by pid 18932. Type below command in cmd:
taskkill -f /pid 18932
For UNIX:
alias ngf='kill -9 $(lsof -t -i:4200);ng serve'
Now run ngf (instead of ng serve) in terminal from the project folder. This will kill all processes using the port 4200 and runs your Angular project.
Why not just load the frame off screen or hidden and then display it once it has finished loading. You could show a loading icon in its place to begin with to give the user immediate feedback that it's loading.
You may use crudini
tool to get ini values, e.g.:
DATABASE_VERSION=$(crudini --get parameters.ini '' database_version)
JPA's behaviour is correct (meaning as per the specification): objects aren't deleted simply because you've removed them from a OneToMany collection. There are vendor-specific extensions that do that but native JPA doesn't cater for it.
In part this is because JPA doesn't actually know if it should delete something removed from the collection. In object modeling terms, this is the difference between composition and "aggregation*.
In composition, the child entity has no existence without the parent. A classic example is between House and Room. Delete the House and the Rooms go too.
Aggregation is a looser kind of association and is typified by Course and Student. Delete the Course and the Student still exists (probably in other Courses).
So you need to either use vendor-specific extensions to force this behaviour (if available) or explicitly delete the child AND remove it from the parent's collection.
I'm aware of:
I am not sure what you are trying to accomplish, but you may want to consider that passing a class may not be what you really need to be doing. In many cases, dealing with Class like this is easily encapsulated within a factory pattern of some type and the use of that is done through an interface. here's one of dozens of articles on that pattern: http://today.java.net/pub/a/today/2005/03/09/factory.html
using a class within a factory can be accomplished in a variety of ways, most notably by having a config file that contains the name of the class that implements the required interface. Then the factory can find that class from within the class path and construct it as an object of the specified interface.
$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';
$array = array_values($array);
through this function you can reset your array
$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';
A more compact and efficient way would be perhaps:
cols = ['frame', 'count']
N = 4
dat = pd.DataFrame(columns = cols)
for i in range(N):
dat = dat.append({'frame': str(i), 'count':i},ignore_index=True)
output would be:
>>> dat
frame count
0 0 0
1 1 1
2 2 2
3 3 3
Try this curious example. In the example below if a were a numeric initialized at 0, you'd see 0 and then 1. Except a is an object and javascript will pass f1 a pointer of a rather than a copy of it. The result is that you get the same alert both times.
var a = new Date();
function f1(b)
{
b.setDate(b.getDate()+1);
alert(b.getDate());
}
f1(a);
alert(a.getDate());
The problem is almost certainly that you're not using the MPI compiler wrappers. Whenever you're compiling an MPI program, you should use the MPI wrappers:
mpicc
mpiCC
, mpicxx
, mpic++
mpifort
, mpif77
, mpif90
These wrappers do all of the dirty work for you of making sure that all of the appropriate compiler flags, libraries, include directories, library directories, etc. are included when you compile your program.
Try use absolute path:
exclude:path.resolve(__dirname, "node_modules")
I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked
html2canvas(document.querySelector('#toPrint')).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:
<script src='javascript.php'></script>
Then your script file:
<?php header("Content-type: application/javascript"); ?>
$(function() {
$( "#progressbar" ).progressbar({
value: <?php echo $_SESSION['value'] ?>
});
// ... more javascript ...
If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
find /folder -type f -mtime -90 | grep -E "(.txt|.php|.inc|.root|.gif)" | xargs ls -l > WWWlastActivity.log
if x is a string and you search for y which also a string their is two cases : case 1: y is exist in x so x.find(y) = the index (the position) of the y in x . case 2: y is not exist so x.find (y) = -1 this mean y is not found in x.
I'm putting this in a new answer because no linebreaks / codeblocks in comments. I assume you want those nans to turn into a blank string? I couldn't find a nice way to do this, only do the ugly method:
s = pd.Series([1001.,1002.,None])
a = s.loc[s.isnull()].fillna('')
b = s.loc[s.notnull()].astype(int).astype(str)
result = pd.concat([a,b])
I had the same problem. Don't remember where I found it on the web, but here is what I did:
Click "Start button"
in the search box, enter "Turn windows features on or off"
in the features window, Click: "Internet Information Services"
Click: "World Wide Web Services"
Click: "Application Development Features"
Check (enable) the features. I checked all but CGI.
IIS - this configuration section cannot be used at this path (configuration locking?)
Using the ArrayObject from Std or building your own
(new \ArrayObject($existingStdClass))
you can use the build in method on the new class:
getArrayCopy()
or pass the new object to
iterator_to_array
You might get Component unavailable
if you import the jQuery script directly.
Maybe it's what @Conley was talking about...
You can use
@require http://userscripts.org/scripts/source/85365.user.js
which is an modified version to work on Greasemonkey, and then get the jQuery object
var $ = unsafeWindow.jQuery;
$("div").css("display", "none");
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.
in bootstrap use .list-inline
css class
<ul class="list-inline">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h
"origin/master" refers to the reference poiting to the HEAD commit of branch "origin/master".
A reference is a human-friendly alias name to a Git object, typically a commit object.
"origin/master" reference only gets updated when you git push
to your remote (http://git-scm.com/book/en/v2/Git-Internals-Git-References#Remotes).
From within the root of your project, run:
cat .git/refs/remotes/origin/master
Compare the displayed commit ID with:
cat .git/refs/heads/master
They should be the same, and that's why Git says master
is up-to-date with origin/master
.
When you run
git fetch origin master
That retrieves new Git objects locally under .git/objects folder. And Git updates .git/FETCH_HEAD so that now, it points to the latest commit of the fetched branch.
So to see the differences between your current local branch, and the branch fetched from upstream, you can run
git diff HEAD FETCH_HEAD
I need a regex able to match everything but except a string starting with
index.php
a specific pattern (specifically index.php and what follows, like index.php?id=2342343)
Use method Exec
let match,_x000D_
arr = [],_x000D_
myRe = /([\s\S]+?)(?:index\.php\?id.+)/g;_x000D_
_x000D_
var str = 'http://regular-viragenia/index.php?id=2342343';_x000D_
_x000D_
while ((match = myRe.exec(str)) != null) {_x000D_
arr.push(match[1]);_x000D_
} _x000D_
_x000D_
console.log(arr);
_x000D_
var myRe = /([\s\S]+?)(?:index\.php\?id=.+)/g;_x000D_
var str = 'http://regular-viragenia/index.php?id=2342343';_x000D_
var matches_array = myRe.exec(str);_x000D_
console.log(matches_array[1]);
_x000D_
OR OTHER MATCH
let match,_x000D_
arr = [],_x000D_
myRe = /index.php\?id=((?:(?!index)[\s\S])*)/g;_x000D_
_x000D_
var str = 'http://regular-viragenia/index.php?id=2342343index.php?id=111index.php?id=222';_x000D_
_x000D_
while ((match = myRe.exec(str)) != null) {_x000D_
arr.push(match[1]);_x000D_
} _x000D_
_x000D_
console.log(arr);
_x000D_
If you cannot utilize the ActiveDirectory
Module or the Get-ADGroupMember
cmdlet, you can do it with the LDAP "in chain"-matching rule:
$GroupDN = "CN=MyGroup,OU=Groups,DC=mydomain,DC=tld"
$LDAPFilter = "(&(objectClass=user)(objectCategory=Person)(memberOf:1.2.840.113556.1.4.1941:=$GroupDN))"
# Ideally using an instance of adsisearcher here:
Get-ADObject -LDAPFilter $LDAPFilter
See MSDN for additional LDAP matching rules implemented in Active Directory
I played with JMeter. One think it could not not test was ASP.NET Webforms. The viewstate broke my tests. I am not shure why, but there are a couple of tools out there that dont handle viewstate right. My current project is ASP.NET MVC and JMeter works well with it.
Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016.
For this reason I think, the correct calculation should be like the below simply;
var d = new Date(),
dayInMs = 1000 * 60 * 60 * 24,
weekInMs = dayInMs * 7,
startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
todayElapsedTime = d.valueOf() - startOfToday,
dayDiff = d.getDay() * dayInMs,
dateDiff = dayDiff + todayElapsedTime,
// finally
startOfWeek = d.valueOf() - dateDiff,
endOfWeek = startOfWeek + weekInMs - 1;
If anyone is interested in getting the localized string from the property with DisplayAttribute and ResourceType like this:
[Display(Name = "Year", ResourceType = typeof(ArrivalsResource))]
public int Year { get; set; }
Use the following after displayAttribute != null
(as shown above by @alex' answer):
ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);
var entry = resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
.OfType<DictionaryEntry>()
.FirstOrDefault(p => p.Key.ToString() == displayAttribute.Name);
return entry.Value.ToString();
Convert one of them to a double first. This form works in many languages:
real_result = (int_numerator + 0.0) / int_denominator
there is also an Android Studio (1.4) setting to optimze imports on the fly: see Settings->Editor->General->Auto Import.
I agree with the DialogResult
-Solution as the more straight forward one.
In VB.NET however, typecast is required to get the CloseReason
-Property
Private Sub MyForm_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
Dim eCast As System.Windows.Forms.FormClosingEventArgs
eCast = TryCast(e, System.Windows.Forms.FormClosingEventArgs)
If eCast.CloseReason = Windows.Forms.CloseReason.None Then
MsgBox("Button Pressed")
Else
MsgBox("ALT+F4 or [x] or other reason")
End If
End Sub
* offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.
* clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.
* scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.
Same is the case for all of these with width instead of height.
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
I have faced the same problem with a character that I never managed to match with a where query - CHARINDEX, LIKE, REPLACE
, etc. did not work. Then I have used a brute force solution which is awful, heavy but works:
Step 1: make a copy of the complete data set - keep track of the original names with an source_id referencing the pk of the source table (and keep this source id in all the subsequent tables).
Step 2: LTRIM RTRIM
the data, and replace all double spaces, tab, etc (basically all the CHAR(1) to CHAR(32) by one space. Lowercase the whole set as well.
Step 3: replace all the special characters that you know (get the list of all the quotes, double quotes, etc.) by something from a-z (I suggest z). Basically replace everything that is not standard English characters by a z (using nested REPLACE of REPLACE in a loop).
Step 4: split by word into a second copy, where each word is in a separate row - the split is a SUBSTRING
based on the position of the space characters - at this point, we should miss the ones where there's a hidden space that we did not catche earlier.
Step 5: split each word into a third copy, where each letter is in a separate row (I know it makes a very large table) - keep track of the charindex of each letter in a separate column.
Step 6: Select everything in the above table which is not LIKE [a-z]. This is the list of the unidentified characters we want to exclude.
From the output of step 6 we have enough data to make a series of substring of the source to select everything but the unknown character we want to exclude.
Note 1: there are smart ways to optimize this, depending on the size of the original expression (steps 4, 5 and 6 can be made in one go).
Note 2: this is not very fast, but the fastest way to get this done for a large data set, because the split of lines into words and words into letters is made by substring, which slices all the table into one character slices. However, this is quite heavy to build. With a smaller set, it may be enough to parse each record one by one and search for character which is not in a list of all English characters plus all special characters.
You need to use ng-disabled directive
<input data-ng-model="userInf.username"
class="span12 editEmail"
type="text"
placeholder="[email protected]"
pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}"
required
ng-disabled="<expression to disable>" />
Assuming you're on a Unix-like platform (so that ps -A
exists),
>>> import subprocess, signal
>>> import os
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()
gives you ps -A
's output in the out
variable (a string). You can break it down into lines and loop on them...:
>>> for line in out.splitlines():
... if 'iChat' in line:
... pid = int(line.split(None, 1)[0])
... os.kill(pid, signal.SIGKILL)
...
(you could avoid importing signal
, and use 9
instead of signal.SIGKILL
, but I just don't particularly like that style, so I'd rather used the named constant this way).
Of course you could do much more sophisticated processing on these lines, but this mimics what you're doing in shell.
If what you're after is avoiding ps
, that's hard to do across different Unix-like systems (ps
is their common API to get a process list, in a sense). But if you have a specific Unix-like system in mind, only (not requiring any cross-platform portability), it may be possible; in particular, on Linux, the /proc
pseudo-filesystem is very helpful. But you'll need to clarify your exact requirements before we can help on this latter part.
you pass the context to class B in it's constructor, and make sure you pass getApplicationContext() instead of a activityContext()
Goto your_severpath/apache_ver/conf/
Open the file httpd.conf
in Notepad.
Find this line:
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
Remove the hash symbol:
LoadModule vhost_alias_module modules/mod_vhost_alias.so
Then goto <Directory />
and change to:
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
Then restart your local server.
You need to make some changes in the compiler. In Dev C++ Compiler: 1. Go to compiler settings/compiler Options. 2. Click on General Tab 3. Check the checkbox (Add the following commands when calling the compiler. 4. write -std=c++11 5. click Ok
You probably included your JavaScript before the HTML: example.
You should either execute your JavaScript when the window loads (or better, when the DOM is fully loaded), or you should include your JavaScript after your HTML: example.
The best "Pythonic" way to do this, exploiting the with
statement, is listed as Example #6 in PEP 343, which gives the background of the statement.
@contextmanager
def opened_w_error(filename, mode="r"):
try:
f = open(filename, mode)
except IOError, err:
yield None, err
else:
try:
yield f, None
finally:
f.close()
Used as follows:
with opened_w_error("/etc/passwd", "a") as (f, err):
if err:
print "IOError:", err
else:
f.write("guido::0:0::/:/bin/sh\n")
Use jdbcTemplate.update(String sql, Object... args)
method:
jdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
var1, var2
);
or jdbcTemplate.update(String sql, Object[] args, int[] argTypes)
, if you need to map arguments to SQL types manually:
jdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
);
The <NAME>
you use in multer's upload.single(<NAME>)
function must be the same as the one you use in <input type="file" name="<NAME>" ...>
.
So you need to change
var type = upload.single('file')
to
var type = upload.single('recfile')
in you app.js
Hope this helps.
If the two tables use the same ID or have a common UNIQUE key:
1) Insert the selected record in table 2
INSERT INTO table2 SELECT * FROM table1 WHERE (conditions)
2) delete the selected record from table1 if presents in table2
DELETE FROM table1 as A, table2 as B WHERE (A.conditions) AND (A.ID = B.ID)
Update
Original
var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");
string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding
request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;
var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();
Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:
throw new TransactionProblemException(transNbr, originalException);
The stack trace will look like
TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...
Well, one practical use I've found out is reducing boiler plate code. For example:
void process_z_vec(vector<int>& vec)
{
auto print_2d = [](const vector<int>& board, int bsize)
{
for(int i = 0; i<bsize; i++)
{
for(int j=0; j<bsize; j++)
{
cout << board[bsize*i+j] << " ";
}
cout << "\n";
}
};
// Do sth with the vec.
print_2d(vec,x_size);
// Do sth else with the vec.
print_2d(vec,y_size);
//...
}
Without lambda, you may need to do something for different bsize
cases. Of course you could create a function but what if you want to limit the usage within the scope of the soul user function? the nature of lambda fulfills this requirement and I use it for that case.
Just note that maybe your Entity have primary key but your table in database doesn't have primary key.
Well guys, the solution to the problem is the following:
1) Folder 00A: 2) Counter: the last number 3) Help: the last number
Folder Perflib:
Last Counter: 00A folder´s Counter
Last Help: 00A folder´s Help
Ready, verify the same number in both. success
In Netbeans 8.2
1. Dowload the binaries from the web source. The Apache Commos are in: [http://commons.apache.org/components.html][1] In this case, you must select the "Logging" in the Components menu and follow the link to downloads in the Releases part. Direct URL: [http://commons.apache.org/proper/commons-logging/download_logging.cgi][2] For me, the correct download was the file: commons-logging-1.2-bin.zip from the Binaries.
2. Unzip downloaded content. Now, you can see several jar files inside the directory created from the zip file.
3. Add the library to the project. Right click in the project, select Properties and click in Libraries (in the left side). Click the button "Add Jar/Folder". Go to the previously unzipped contents and select the properly jar file. Clic in "Open" and click in"Ok". The library has been loaded!
Use negative lookaround: (?!
pattern
)
Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.
These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):
There is no goto
in bash.
Here is some dirty workaround using trap
which jumps only backwards:)
#!/bin/bash -e
trap '
echo I am
sleep 1
echo here now.
' EXIT
echo foo
goto trap 2> /dev/null
echo bar
Output:
$ ./test.sh
foo
I am
here now.
This shouldn't be used in that way, but only for educational purposes. Here is why this works:
trap
is using exception handling to achieve the change in code flow.
In this case the trap
is catching anything that causes the script to EXIT. The command goto
doesn't exist, and hence throws an error, which would ordinarily exit the script. This error is being caught with trap
, and the 2>/dev/null
hides the error message that would ordinarily be displayed.
This implementation of goto is obviously not reliable, since any non-existent command (or any other error, for that manner), would execute the same trap command. In particular, you cannot choose which label to go-to.
Basically in real scenario you don't need any goto statements, they're redundant as random calls to different places only make your code difficult to understand.
If your code is invoked many times, then consider to use loop and changing its workflow to use continue
and break
.
If your code repeats it-self, consider writing the function and calling it as many times as you want.
If your code needs to jump into specific section based on the variable value, then consider using case
statement.
If you can separate your long code into smaller pieces, consider moving it into separate files and call them from the parent script.
Apple changed the canOpenURL method on iOS 9. Apps which are checking for URL Schemes on iOS 9 and iOS 10 have to declare these Schemes as it is submitted to Apple.
javascript:alert("Inspect Element On");
javascript:document.body.contentEditable = 'true';
document.designMode='on';
void 0;
javascript:alert(document.documentElement.innerHTML);
Highlight this and drag it to your bookmarks bar and click it when you wanna edit and view the current sites source code.
In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker1'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<script type="text/javascript">_x000D_
$(function () {_x000D_
$('#datetimepicker1').datetimepicker();_x000D_
});_x000D_
</script>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Or run a pip install --upgrade pip enum34
I have written this article about the ICommand interface.
The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param)
is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param))
.
Requires the method to switching event CanExecuteChanged
. It is called from the user interface elements for switching the state CanExecute()
command.
public class ModelCommand : ICommand
{
#region Constructors
public ModelCommand(Action<object> execute)
: this(execute, null) { }
public ModelCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}
public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}
public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#endregion
private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}
I was also having this issue of "You have mail" coming up every time I started Terminal.
What I discovered is this.
Something I'd installed (not entirely sure what, but possibly a script or something associated with an Alfred Workflow [at a guess]) made a change to the OS X system to start presenting Terminal bash notifications. Prior to that, it appears Wordpress had attempted to use the Local Mail system to send a message. The message bounced, due to it having an invalid Recipient address. The bounced message then ended up in the local system mail inbox. So Terminal (bash) was then notifying me that "You have mail".
You can access the mail by simply using the command
mail
This launches you into Mail, and it will right away show you a list of messages that are stored there. If you want to see the content of the first message, use
t
This will show you the content of the first message, in full. You'll need to scroll down through the message to view it all, by hitting the down-arrow
key.
If you want to jump to the end of the message, use the
spacebar
If you want to abort viewing the message, use
q
To view the next message in the queue use
n
... assuming there's more than one message.
NOTE: You need to use these commands at the mail ?
command prompt. They won't work whilst you are in the process of viewing a message. Hitting n
whilst viewing a message will just cause an error message related to regular expressions. So, if in the midst of viewing a message, hit q
to quit from that, or hit spacebar
to jump to the end of the message, and then at the ?
prompt, hit n
.
Viewing the content of the messages in this way may help you identify what attempted to send the message(s).
You can also view a specific message by just inputting its number at the ?
prompt. 3
, for instance, will show you the content of the third message (if there are that many in there).
Use the d
command (at the ?
command prompt )
d [message number]
To delete each message when you are done looking at them. For example, d 2
will delete message number 2. Or you can delete a list of messages, such as d 1 2 5 7
. Or you can delete a range of messages with (for example), d 3-10
.
You can find the message numbers in the list of messages mail shows you.
To delete all the messages, from the mail prompt (?
) use the command d *
.
As per a comment on this post, you will need to use q
to quit mail, which also saves any changes.
If you'd like to see the mail all in one output, use this command at the bash prompt (i.e. not from within mail, but from your regular command prompt):
cat /var/mail/<username>
And, if you wish to delete the emails all in one hit, use this command
sudo rm /var/mail/<username>
In my particular case, there were a number of messages. It looks like the one was a returned message that bounced. It was sent by a local Wordpress installation. It was a notification for when user "Admin" (me) changed its password. Two additional messages where there. Both seemed to be to the same incident.
What I don't know, and can't answer for you either, is WHY I only recently started seeing this mail notification each time I open Terminal. The mails were generated a couple of months ago, and yet I only noticed this "you have mail" appearing in the last few weeks. I suspect it's the result of something a workflow I installed in Alfred, and that workflow using Terminal bash to provide notifications... or something along those lines.
If you have no interest in determining the source of the messages, and just wish to get rid of them, it may be easier to do so without using the mail
command (which can be somewhat fiddly). As pointed out by a few other people, you can use this command instead:
sudo rm /var/mail/YOURUSERNAME
Its even easier than that.
<style name="MyTextStyle">
<item name="android:textCursorDrawable">#000000</item>
</style>
This works in ICS and beyond. I haven't tested it in other versions.
private int[,] MirrorH(int[,] matrix) //the method will return mirror horizintal of matrix
{
int[,] MirrorHorizintal = new int[4, 4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j ++)
{
MirrorHorizintal[i, j] = matrix[i, 3 - j];
}
}
return MirrorHorizintal;
}
In my experience the plugins worked with HTTP but not with the latest httpClient. Also, configuring the CORS response headers on the server wasn't really an option. So, I created a proxy.conf.json
file to act as a proxy server.
Read more about this here.
proxy.conf.json
file:
{
"/posts": {
"target": "https://example.com",
"secure": true,
"pathRewrite": {
"^/posts": ""
},
"changeOrigin": true
}
}
I placed the proxy.conf.json
file right next the the package.json
file in the same directory.
Then I modified the start command in the package.json file:
"start": "ng serve --proxy-config proxy.conf.json"
The HTTP call from my app component:
return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
console.log(returnedStuff);
});
Lastly to run my app, I'd have to use npm start
or ng serve --proxy-config proxy.conf.json
For this, you need to declare the variable as global. However, a global variable is also accessible from outside the module by using module_name.var_name
. Add this as the first line of your module:
global __DBNAME__
I have successfully captured HTTP traffic using Fiddler2 as a proxy, which can be installed on any Windows PC on your network.
Simple Way without using any external import is to use this method
I created csv files named with billing_201208.csv ,billing_201209.csv ,billing_201210.csv and it looks like working fine.
Output will be the following if files listed above exists
found billing_201208.csv
found billing_201209.csv
found billing_201210.csv
//Use Import ->import java.io.File public static void main(String[] args) { String pathToScan = "."; String target_file ; // fileThatYouWantToFilter File folderToScan = new File(pathToScan);File[] listOfFiles = folderToScan.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { target_file = listOfFiles[i].getName(); if (target_file.startsWith("billing") && target_file.endsWith(".csv")) { //You can add these files to fileList by using "list.add" here System.out.println("found" + " " + target_file); } } } }
You can check if you typed forEach correctly, if you typed foreach like in other programming languages it won't work.
my problem (git on macOS) was solved by using
sudo git
instead of just git
in all add
and commit
commands
STR_TO_DATE('12/31/2011', '%m/%d/%Y')
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you, Thierry
Edit: Fixed the fill statement and template syntax.
The href is a required attribute of an anchor element, so without it, you cannot expect all browsers to handle it equally. Anyway, I read somewhere in a comment that you only want the link to be underlined when hovering, and not otherwise. You can use the following to achieve this, and it will only apply to links with the hover-class:
<a class="hover" href="">click</a>
a.hover {
text-decoration: none;
}
a.hover:hover {
text-decoration:underline;
}
If you are consuming an internal service via AJAX, make sure the url points to https, this cleared up the error for me.
Initial AJAX URL: "http://XXXXXX.com/Core.svc/" + ApiName
Corrected AJAX URL: "https://XXXXXX.com/Core.svc/" + ApiName,
Use
git clone --depth=1 --branch=master git://someserver/somerepo dirformynewrepo
rm -rf ./dirformynewrepo/.git
dirformynewrepo
not a Git repository any more.Or, if you need to access the element that has that property and it does not use an id, you could go this route:
$("img").each(function () {
if ($(this).css("float") == "left") { $(this).addClass("left"); }
if ($(this).css("float") == "right") { $(this).addClass("right"); }
})
/Java Resources/resources/config.properties
for loading properties.
Properties prop = new Properties();
InputStream input = null;
try {
input = getClass().getClassLoader().getResourceAsStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below are various ways to convert to char c to String s (in decreasing order of speed and efficiency)
char c = 'a';
String s = String.valueOf(c); // fastest + memory efficient
String s = Character.toString(c);
String s = new String(new char[]{c});
String s = String.valueOf(new char[]{c});
String s = new Character(c).toString();
String s = "" + c; // slowest + memory inefficient
The issue is because the local is not up-to-date with the master branch that is why we are supposed to pull the code before pushing it to the git
git add .
git commit -m 'Comments to be added'
git pull origin master
git push origin master
Just add:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
If someone uses AndroidStudio make sure that the assets folder is placed in
app/src/main/assets
directory.
You may do it using xargs
if you like, but the main idea is still the same:
find *.txt | xargs -I{} sh -c "cat {}; echo ''" > finalfile.txt
UPDATE `Table A` a
SET a.`text`=(
SELECT group_concat(b.`B-num`,' from ',b.`date` SEPARATOR ' / ')
FROM `Table B` b WHERE (a.`A-num`=b.`A-num`)
)
To store the third line into a variable, use below syntax:
variable=`echo "$1" | sed '3q;d' urfile`
To store the changed line into a variable, use below syntax:
variable=echo 'overflow' | sed -e "s/over/"OVER"/g"
output:OVERflow
You can try restful.js, a framework-agnostic RESTful client, using a syntax similar to the popular Restangular.
I have found that, when trying to install dev dependencies for a package that contains a node addon, you cannot avoid building the addon when running npm install --dev even if you just want to install the devDependencies. So, I had to go around npm's back:
node -e 'console.log( Object.keys( require( "./package.json" ).devDependencies ) );' | \
sed -e "s/^[^']*'//" -e "s/'.*$//" | \
xargs npm install
Or, better (and more succinctly) yet,
node -e 'Object.keys( require( "./package.json" ).devDependencies )
.map( function( item ){ console.log( item ) } );' | xargs npm install
If using sqlplus you can define a variable thus:
define <varname>=<varvalue>
And you can display the value by:
define <varname>
And then use it in a query as, for example:
select *
from tab1
where col1 = '&varname';
Here is a simple class that handles both raw
and asset
files :
public class ReadFromFile {
public static String raw(Context context, @RawRes int id) {
InputStream is = context.getResources().openRawResource(id);
int size = 0;
try {
size = is.available();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
public static String asset(Context context, String fileName) {
InputStream is = null;
int size = 0;
try {
is = context.getAssets().open(fileName);
AssetFileDescriptor fd = null;
fd = context.getAssets().openFd(fileName);
size = (int) fd.getLength();
fd.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
private static String readFile(int size, InputStream is) {
try {
byte buffer[] = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
For example :
ReadFromFile.raw(context, R.raw.textfile);
And for asset files :
ReadFromFile.asset(context, "file.txt");
When a thread is executing and you want to execute the main UI thread which is blocked by current thread, then use the below:
current thread:
Dispatcher.CurrentDispatcher.Invoke(MethodName,
new object[] { parameter1, parameter2 }); // if passing 2 parameters to method.
Main UI thread:
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background, new Action(() => MethodName(parameter)));
requests
does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.
Python comes with built-in XML parsers. I recommend you use the ElementTree API:
import requests
from xml.etree import ElementTree
response = requests.get(url)
tree = ElementTree.fromstring(response.content)
or, if the response is particularly large, use an incremental approach:
response = requests.get(url, stream=True)
# if the server sent a Gzip or Deflate compressed response, decompress
# as we read the raw stream:
response.raw.decode_content = True
events = ElementTree.iterparse(response.raw)
for event, elem in events:
# do something with `elem`
The external lxml project builds on the same API to give you more features and power still.
JButton b3 = new JButton("CLOSE");
b3.setBounds(50, 375, 250, 50);
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
Check to see if the Andriod Device is installed on PC. See steps below. The 'Other device' will change to 'Andriod Device' once the USB drive is installed. The browse path should be \extras\google\usb_driver\ not the sub directories under it. Otherwise the installation will not find the package.
To install the Android USB driver on Windows 7 for the first time:
Connect your Android-powered device to your computer's USB port. Right-click on Computer from your desktop or Windows Explorer, and select Manage. Select Devices in the left pane. Locate and expand Other device in the right pane. Right-click the device name (such as Nexus S) and select Update Driver Software. This will launch the Hardware Update Wizard. Select Browse my computer for driver software and click Next. Click Browse and locate the USB driver folder. (The Google USB Driver is located in \extras\google\usb_driver.) Click Next to install the driver.
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
To answer a little more conceptually:
SelectedValuePath
defines which property (by its name) of the objects bound to the ListBox's ItemsSource
will be used as the item's SelectedValue
.
For example, if your ListBox is bound to a collection of Person
objects, each of which has Name
, Age
, and Gender
properties, SelectedValuePath=Name
will cause the value of the selected Person
's Name
property to be returned in SelectedValue
.
Note that if you override the ListBox's ControlTemplate (or apply a Style) that specifies what property should display, SelectedValuePath
cannot be used.
SelectedItem
, meanwhile, returns the entire Person
object currently selected.
(Here's a further example from MSDN, using TreeView)
Update: As @Joe pointed out, the DisplayMemberPath property is unrelated to the Selected* properties. Its proper description follows:
Note that these values are distinct from DisplayMemberPath
(which is defined on ItemsControl, not Selector), but that property has similar behavior to SelectedValuePath
: in the absence of a style/template, it identifies which property of the object bound to item should be used as its string representation.
Simple
var a=[{a:4}], b=[{b:5}]
angular.merge(a,b) // [{a:4, b:5}]
Tested on angular 1.4.1
Use SequenceEqual
to check for sequence equality because Equals
method checks for reference equality.
var a = ints1.SequenceEqual(ints2);
Or if you don't care about elements order use Enumerable.All
method:
var a = ints1.All(ints2.Contains);
The second version also requires another check for Count
because it would return true even if ints2
contains more elements than ints1
. So the more correct version would be something like this:
var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;
In order to check inequality just reverse the result of All
method:
var a = !ints1.All(ints2.Contains)
Duplicated id
for pairs name
and city
:
select s.id, t.*
from [stuff] s
join (
select name, city, count(*) as qty
from [stuff]
group by name, city
having count(*) > 1
) t on s.name = t.name and s.city = t.city
java.util.Date date = ...
DateTime dateTime = new DateTime(date);
Make sure date
isn't null
, though, otherwise it acts like new DateTime()
- I really don't like that.
If you are using Jackson do a lot of JsonNode
building in code, you may be interesting in the following set of utilities. The benefit of using them is that they support a more natural chaining style that better shows the structure of the JSON under construction.
Here is an example usage:
import static JsonNodeBuilders.array;
import static JsonNodeBuilders.object;
...
val request = object("x", "1").with("y", array(object("z", "2"))).end();
Which is equivalent to the following JSON:
{"x":"1", "y": [{"z": "2"}]}
Here are the classes:
import static lombok.AccessLevel.PRIVATE;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;
/**
* Convenience {@link JsonNode} builder.
*/
@NoArgsConstructor(access = PRIVATE)
public final class JsonNodeBuilders {
/**
* Factory methods for an {@link ObjectNode} builder.
*/
public static ObjectNodeBuilder object() {
return object(JsonNodeFactory.instance);
}
public static ObjectNodeBuilder object(@NonNull String k1, boolean v1) {
return object().with(k1, v1);
}
public static ObjectNodeBuilder object(@NonNull String k1, int v1) {
return object().with(k1, v1);
}
public static ObjectNodeBuilder object(@NonNull String k1, float v1) {
return object().with(k1, v1);
}
public static ObjectNodeBuilder object(@NonNull String k1, String v1) {
return object().with(k1, v1);
}
public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2) {
return object(k1, v1).with(k2, v2);
}
public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2,
@NonNull String k3, String v3) {
return object(k1, v1, k2, v2).with(k3, v3);
}
public static ObjectNodeBuilder object(@NonNull String k1, JsonNodeBuilder<?> builder) {
return object().with(k1, builder);
}
public static ObjectNodeBuilder object(JsonNodeFactory factory) {
return new ObjectNodeBuilder(factory);
}
/**
* Factory methods for an {@link ArrayNode} builder.
*/
public static ArrayNodeBuilder array() {
return array(JsonNodeFactory.instance);
}
public static ArrayNodeBuilder array(@NonNull boolean... values) {
return array().with(values);
}
public static ArrayNodeBuilder array(@NonNull int... values) {
return array().with(values);
}
public static ArrayNodeBuilder array(@NonNull String... values) {
return array().with(values);
}
public static ArrayNodeBuilder array(@NonNull JsonNodeBuilder<?>... builders) {
return array().with(builders);
}
public static ArrayNodeBuilder array(JsonNodeFactory factory) {
return new ArrayNodeBuilder(factory);
}
public interface JsonNodeBuilder<T extends JsonNode> {
/**
* Construct and return the {@link JsonNode} instance.
*/
T end();
}
@RequiredArgsConstructor
private static abstract class AbstractNodeBuilder<T extends JsonNode> implements JsonNodeBuilder<T> {
/**
* The source of values.
*/
@NonNull
protected final JsonNodeFactory factory;
/**
* The value under construction.
*/
@NonNull
protected final T node;
/**
* Returns a valid JSON string, so long as {@code POJONode}s not used.
*/
@Override
public String toString() {
return node.toString();
}
}
public final static class ObjectNodeBuilder extends AbstractNodeBuilder<ObjectNode> {
private ObjectNodeBuilder(JsonNodeFactory factory) {
super(factory, factory.objectNode());
}
public ObjectNodeBuilder withNull(@NonNull String field) {
return with(field, factory.nullNode());
}
public ObjectNodeBuilder with(@NonNull String field, int value) {
return with(field, factory.numberNode(value));
}
public ObjectNodeBuilder with(@NonNull String field, float value) {
return with(field, factory.numberNode(value));
}
public ObjectNodeBuilder with(@NonNull String field, boolean value) {
return with(field, factory.booleanNode(value));
}
public ObjectNodeBuilder with(@NonNull String field, String value) {
return with(field, factory.textNode(value));
}
public ObjectNodeBuilder with(@NonNull String field, JsonNode value) {
node.set(field, value);
return this;
}
public ObjectNodeBuilder with(@NonNull String field, @NonNull JsonNodeBuilder<?> builder) {
return with(field, builder.end());
}
public ObjectNodeBuilder withPOJO(@NonNull String field, @NonNull Object pojo) {
return with(field, factory.pojoNode(pojo));
}
@Override
public ObjectNode end() {
return node;
}
}
public final static class ArrayNodeBuilder extends AbstractNodeBuilder<ArrayNode> {
private ArrayNodeBuilder(JsonNodeFactory factory) {
super(factory, factory.arrayNode());
}
public ArrayNodeBuilder with(boolean value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(@NonNull boolean... values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(int value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(@NonNull int... values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(float value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(String value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(@NonNull String... values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(@NonNull Iterable<String> values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(JsonNode value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(@NonNull JsonNode... values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(JsonNodeBuilder<?> value) {
return with(value.end());
}
public ArrayNodeBuilder with(@NonNull JsonNodeBuilder<?>... builders) {
for (val builder : builders)
with(builder);
return this;
}
@Override
public ArrayNode end() {
return node;
}
}
}
Note that the implementation uses Lombok, but you can easily desugar it to fill in the Java boilerplate.
I honestly doubt it, for a number of reasons, but the most important one is that there are some instructions that are allowed in 32-bit mode, but not in 64-bit mode. Specifically, the REX prefix that is used to encode some instructions and registers in 64-bit mode is a byte of the form 0x4f:0x40, but in 32 bit mode the same byte is either INC or DEC with a fixed operand.
Because of this, any 64-bit instruction that is prefixed by REX will be interpreted as either INC or DEC, and won't give the VMM the chance to emulate the 64-bit instruction (for instance by signaling an undefined opcode exception).
The only way it might be done is to use a trap exception to return to the VMM after each and every instruction so that it can see if it needs special 64-bit handling. I simply can't see that happening.
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
mysql> DROP INDEX email ON fuinfo;
where email is the unique key (rather than the column name). You find the name of the unique key by
mysql> SHOW CREATE TABLE fuinfo;
here you see the name of the unique key, which could be email_2, for example. So...
mysql> DROP INDEX email_2 ON fuinfo;
mysql> DESCRIBE fuinfo;
This should show that the index is removed
If you want to use two decimal digits in your entire project, you can define:
bcscale(2);
Then the following function will produce your desired result:
$myvalue = 10.165445;
echo bcadd(0, $myvalue);
// result=10.11
But if you don't use the bcscale function, you need to write the code as follows to get your desired result.
$myvalue = 10.165445;
echo bcadd(0, $myvalue, 2);
// result=10.11
To know more
Intersection of two list of different object based on common key - Java 8
private List<User> intersection(List<User> users, List<OtherUser> list) {
return list.stream()
.flatMap(OtherUser -> users.stream()
.filter(user -> user.getId()
.equalsIgnoreCase(OtherUser.getId())))
.collect(Collectors.toList());
}
If you get your string from stdin().read_line
, you have to trim it first.
let my_num: i32 = my_num.trim().parse()
.expect("please give me correct string number!");
Assuming you have a byte string like so
"\x12\x45\x00\xAB"
and you know the amount of bytes and their type you can also use this approach
import struct
bytes = '\x12\x45\x00\xAB'
val = struct.unpack('<BBH', bytes)
#val = (18, 69, 43776)
As I specified little endian (using the '<' char) at the start of the format string the function returned the decimal equivalent.
0x12 = 18
0x45 = 69
0xAB00 = 43776
B is equal to one byte (8 bit) unsigned
H is equal to two bytes (16 bit) unsigned
More available characters and byte sizes can be found here
The advantages are..
You can specify more than one byte and the endian of the values
Disadvantages..
You really need to know the type and length of data your dealing with
(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))
To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].
You can break a line at an operator, list separator, or period.
You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.
bool isFirst = compareString.Contains(firstString);
bool isSecond = compareString.Contains(secondString );
Some applications may detect click source at low OS level. If you really need that kind of hack, you may just run target app in virtual machine's window, and run cliker in host OS, it can help.
Use:
/* @var $objs Test[] */
foreach ($objs as $obj) {
// Typehinting will occur after typing $obj->
}
when typehinting inline variables, and
class A {
/** @var Test[] */
private $items;
}
for class properties.
Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:
The best you can do is say,
foreach ($Objs as $Obj)
{
/* @var $Obj Test */
// You should be able to get hinting after the preceding line if you type $Obj->
}
I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.
VS Code 1.6.0 and Greater
As mentioned by aloisdg below, editor.renderWhitespace
is now an enum taking either none
, boundary
or all
. To view all whitespaces:
"editor.renderWhitespace": "all",
Before VS Code 1.6.0
Before 1.6.0, you had to set editor.renderWhitespace
to true
:
"editor.renderWhitespace": true
Just to help out anyone who has landed on this page after updating VS2015 to update 2 and trying to manage packages on a website, receiving the "NuGet configuration file is invalid" error, this is a known and acknowledged issue:
I got mine working again by installing package manager 3.4.4 (beta) from http://dist.nuget.org/index.html
They do also state update 3 for Visual Studio will also contain a fix
Other than the advantages listed in the answers given, one more advantage of NestedScrollView over ScrollView is its compatibility with CoordinatorLayout. The ScrollView does not cooperate with the CoordinatorLayout. You have to use NestedScrollView to get "scroll off-screen" behaviour for the toolbar.
Toolbar will not collapse with Scrollview as child of CoordinatorLayout
if you dont use every time use line-height:'..'; property its control the height of textarea and width property for width of textarea.
or you can make use of font-size by following css:
#sbr {
font-size: 16px;
line-height:1.4;
width:100%;
}
For supporting all UTF-16 (also non-BMP/supplementary characters) from ES6 the string.codePointAt() method is available;
This method is an improved version of charCodeAt which could support only unicode codepoints < 65536 ( 216 - a single 16bit ) .
I wanted to do counts and sums over full resultset. I achieved grouping by all with GROUP BY 1=1
.
You want to do
git fetch --prune origin
git reset --hard origin/master
git clean -f -d
This makes your local repo exactly like your remote repo.
Remember to replace origin and master with the remote and branch that you want to synchronize with.
From a performance perspective, outside is (much) better.
public static void outside() {
double intermediateResult;
for(int i=0; i < Integer.MAX_VALUE; i++){
intermediateResult = i;
}
}
public static void inside() {
for(int i=0; i < Integer.MAX_VALUE; i++){
double intermediateResult = i;
}
}
I executed both functions 1 billion times each. outside() took 65 milliseconds. inside() took 1.5 seconds.
You could make those submit buttons and inside the servlet your are submitting the form to you could test the name of the button which was pressed and render the corresponding jsp page.
<input type="submit" value="Creazione Nuovo Corso" name="CreateCourse" />
<input type="submit" value="Gestione Autorizzazioni" name="AuthorizationManager" />
Inside the TrainerMenu
servlet if request.getParameter("CreateCourse")
is not empty then the first button was clicked and you could render the corresponding jsp.
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
I spent the better part of a day fiddling with this problem. Turned out the RowBackground Property on the DataGrid - which I had set - was overriding all attempts to change it in . As soon as I deleted it, everything worked. (Same goes for Foreground set in DataGridTextColumn, by the way).
Generate QR Code Image in ASP.NET Using Google Chart API
Google Chart API returns an image in response to a URL GET or POST request. All the data required to create the graphic is included in the URL, including the image type and size.
var url = string.Format("http://chart.apis.google.com/chart?cht=qr&chs={1}x{2}&chl={0}", txtCode.Text, txtWidth.Text, txtHeight.Text);
WebResponse response = default(WebResponse);
Stream remoteStream = default(Stream);
StreamReader readStream = default(StreamReader);
WebRequest request = WebRequest.Create(url);
response = request.GetResponse();
remoteStream = response.GetResponseStream();
readStream = new StreamReader(remoteStream);
System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);
img.Save("D:/QRCode/" + txtCode.Text + ".png");
response.Close();
remoteStream.Close();
readStream.Close();
txtCode.Text = string.Empty;
txtWidth.Text = string.Empty;
txtHeight.Text = string.Empty;
lblMsg.Text = "The QR Code generated successfully";
Click here for complete source code to download
Demo of application for free QR Code generator using C#
<a href="#Foo" onclick="return runMyFunction();">Do it!</a>
and
function runMyFunction() {
//code
return true;
}
This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.
Add Content-length
header describing size of zip file in bytes.
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Content-length: " . filesize($archive_file_name));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
Also make sure that there is absolutely no white space before <?
and after ?>
. I see a space here:
?
<?php
$file_names = array('iMUST Operating Manual V1.3a.pdf','iMUST Product Information Sheet.pdf');
The short way
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
This might help
let allElements = Array.from(document.querySelectorAll('.widget.hover'))
for (let element of allElements) {
element.classList.remove('hover')
}
If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*")
to get a list of all the filenames, loop over the list and use shutil.copy
to copy each file.
for filename in glob.glob(os.path.join(source_dir, '*.*')):
shutil.copy(filename, dest_dir)
There are several ways to do that. Using HTML alone, you can write
<table border=1 frame=void rules=rows>
or, if you want a border above the first row and below the last row too,
<table border=1 frame=hsides rules=rows>
This is rather inflexible, though; you cannot e.g. make the lines dotted this way, or thicker than one pixel. This is why in the past people used special separator rows, consisting of nothing but some content intended to produce a line (it gets somewhat dirty, especially when you need to make rows e.g. just a few pixels high, but it’s possible).
For the most of it, people nowadays use CSS border
properties for the purpose. It’s fairly simple and cross-browser. But note that to make the lines continuous, you need to prevent spacing between cells, using either the cellspacing=0
attribute in the table
tag or the CSS rule table { border-collapse: collapse; }
. Removing such spacing may necessitate adding some padding (with CSS, preferably) inside the cells.
At the simplest, you could use
<style>
table {
border-collapse: collapse;
}
tr {
border: solid;
border-width: 1px 0;
}
</style>
This puts a border above the first row and below the last row too. To prevent that, add e.g. the following into the style sheet:
tr:first-child {
border-top: none;
}
tr:last-child {
border-bottom: none;
}
You can also implement the like queries using Spring Data JPA supported keyword "Containing".
List<Registration> findByPlaceContaining(String place);
There is an inbuilt option to get the week number of the year
**select datepart(week,getdate())**
$ join -v 1 -t '' file1 file2
line2
line3
The -t
makes sure that it compares the whole line, if you had a space in some of the lines.
Even though it's an old question I'd like to show another solution:
Just define your own operation using java generics and java 8 streams:
public static <S, T> List<T> map(Collection<S> collection, Function<S, T> mapFunction) {
return collection.stream().map(mapFunction).collect(Collectors.toList());
}
Than you can write code like this:
List<String> hex = map(Arrays.asList(10, 20, 30, 40, 50), Integer::toHexString);
Your app is crashing at:
welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");
because mPlayer=null
.
You forgot to initialize Player mPlayer
in your PlayGame Activity.
mPlayer = new Player(context,"");
Fragment PHP (in console Cloud9):
echo "\n";
echo "1: first_srt=1\nsecnd_srt=2\n";
echo "\n";
echo '2: first_srt=1\nsecnd_srt=2\n';
echo "\n";
echo "==============\n";
echo "\n";
resulting output:
1: first_srt=1
secnd_srt=2
2: first_srt=1\nsecnd_srt=2\n
==============
Difference between 1 and 2: " versus '
You don't need to do anything special, actually. You can mix JavaScript and PHP together to get variables from PHP straight into JavaScript.
var param1val = '<?php echo $_GET['param1'] ?>';
Just Javascript (as requested)
Add this function somewhere on your page (preferably in the <head>
)
function clearBox(elementID)
{
document.getElementById(elementID).innerHTML = "";
}
Then add the button on click event:
<button onclick="clearBox('cart_item')" />
In JQuery (for reference)
If you prefer JQuery you could do:
$("#cart_item").html("");
The way I am trying to do this in my question actually works!
# environment/development.rb
ENV['admin_password'] = "secret"
I just had to restart the server. I thought running reload!
in rails console would be enough but I also had to restart the web server.
I am picking my own answer because I feel this is a better place to put and set the ENV variables
\r\n will not work until you set body type as text.
message.setBody(MessageBody.getMessageBodyFromText(msg));
BodyType type = BodyType.Text;
message.getBody().setBodyType(type);
This is another method which will definitely work, but I cant get it to read multiple text files to view in multiple textviews in a single activity, anyone can help?
TextView helloTxt = (TextView)findViewById(R.id.yourTextView);
helloTxt.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
You need to deal with the optional Rank parameter of UBound
.
Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1) '? returns 4
Debug.Print UBound(arr, 2) '? returns 3
More at: UBound Function (Visual Basic)
Simply just enter any of below in the command line,
ng --version
ORng v
ORng -v
The Output would be like,
Not only the Angular version but also the Node version is also mentioned there. I use Angular 6.
I had this same problem with my pre-launch site EnGrip. I went live with this issue. But after a few trials finally this has worked for me:
background-size: cover;
background-repeat: no-repeat;
position: fixed;
background-attachment: scroll;
background-position: 50% 50%;
top: 0;
right: 0;
bottom: 0;
left: 0;
content: "";
z-index: 0;
pure CSS solution. I don't have any JS/JQuery fix over here. Even am new to this UI development. Just thought I would share a working solution since I read this thread yesterday.
Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.
@Path("/hello")
public class Hello {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {
String input = (String) inputJsonObj.get("input");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
And, your client code should look like this:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter());
WebResource service = client.resource(getBaseURI());
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("input", "Value");
System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));
In MySQL, certain words like SELECT
, INSERT
, DELETE
etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.
As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
...
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
...
The identifier quote character is the backtick ("
`
"):
A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.
You have two options.
The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.
Doing this has a couple of advantages:
It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.
The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.
Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.
If renaming the table or column isn't possible, wrap the offending identifier in backticks (`
) as described in the earlier quote from 10.2 Schema Object Names.
An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):
mysql> CREATE TABLE interval (begin INT, end INT); ERROR 1064 (42000): You have an error in your SQL syntax. near 'interval (begin INT, end INT)'
mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)
Similarly, the query from the question can be fixed by wrapping the keyword key
in backticks, as shown below:
INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)"; ^ ^
This look like a duplicate of JSTL conditional check.
The error is having the &&
outside the expression. Instead use
<c:if test="${ISAJAX == 0 && ISDATE == 0}">
We can check files and thire Folders.
import java.io.*;
public class fileCheck
{
public static void main(String arg[])
{
File f = new File("C:/AMD");
if (f.exists() && f.isDirectory()) {
System.out.println("Exists");
//if the file is present then it will show the msg
}
else{
System.out.println("NOT Exists");
//if the file is Not present then it will show the msg
}
}
}
In bash 4.3, the '-v' test for set variables was introduced. At the same time, 'nameref' declaration was added. These two features together with the indirection operator (!) enable a simplified version of the previous example:
get_value()
{
declare -n var_name=$1
if [[ -v var_name ]]
then
echo "${var_name}"
else
echo "variable with name <${!var_name}> is not set"
fi
}
test=123
get_value test
123
test="\$(echo \"something nasty\")"
get_value test
$(echo "something nasty")
unset test
get_value test
variable with name <test> is not set
As this approach eliminates the need for 'eval', it is safer. This code checked under bash 5.0.3(1).
Seems your resource POST
method won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).
Since in you already add Access-Control-Allow-Origin
headers to your Response, you can add new OPTIONS
method to your resource class.
@OPTIONS
@Path("{path : .*}")
public Response options() {
return Response.ok("")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "2000")
.build();
}
Another way to do it is using a limit
method:
Listing::limit(10)->get();
This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:
Listing::inRandomOrder()->limit(10)->get();
It's a quick fix, I hope it helps.
<div id="content">
content...
</div>
<footer>
content footer...
</footer>
css:
#content{min-height: calc(100vh - 100px);}
100vh is 100% height of device and 100px is height of footer
If the content is higher than height of device, the footer will stay on bottom. And the content is shorter than height of device, the footer will stay on bottom of screen
from tkinter import *
window = tk()
window.geometry("300x300")
def close_window ():
window.destroy()
button = Button ( text = "Good-bye", command = close_window)
button.pack()
window.mainloop()
I add on Nick's question: when are hard links useful or necessary? The only application that comes to my mind, in which symbolic links wouldn't do the job, is providing a copy of a system file in a chrooted environment.
You can try changing it to this:
If myTableData.Rows.Count > 0 Then
For i As Integer = 0 To myTableData.Rows.Count - 1
''Dim DataType() As String = myTableData.Rows(i).Item(1)
ListBox2.Items.Add(myTableData.Rows(i)(1))
Next
End If
Note: Your loop needs to be one less than the row count since it's a zero-based index.
In Windows, if you have mapped network drives and you don't know the UNC path for them, you can start a command prompt (Start ? Run ? cmd.exe) and use the net use
command to list your mapped drives and their UNC paths:
C:\>net use
New connections will be remembered.
Status Local Remote Network
-------------------------------------------------------------------------------
OK Q: \\server1\foo Microsoft Windows Network
OK X: \\server2\bar Microsoft Windows Network
The command completed successfully.
Note that this shows the list of mapped and connected network file shares for the user context the command is run under. If you run cmd.exe
under your own user account, the results shown are the network file shares for yourself. If you run cmd.exe
under another user account, such as the local Administrator, you will instead see the network file shares for that user.
Yes this is possible
Since the question is update, this solution can only gives you the embed url not the HLS url, check @JAL answer.
with the ressource search.list
and the parameters:
* part: id
* channelId: UCURGpU4lj3dat246rysrWsw
* eventType: live
* type: video
Request :
GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCURGpU4lj3dat246rysrWsw&eventType=live&type=video&key={YOUR_API_KEY}
Result:
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/enc3-yCp8APGcoiU_KH-mSKr4Yo\"",
"id": {
"kind": "youtube#video",
"videoId": "WVZpCdHq3Qg"
}
},
Then get the videoID
value WVZpCdHq3Qg for example and add the value to this url:
https://www.youtube.com/embed/ + videoID
https://www.youtube.com/watch?v= + videoID
Try this, it worked for me!
If you happen to have Eclipse not responding anymore sometimes, the reason could be that you sit on a 64bit machine where eclipse needs more memory. Be sure to have (at least) the following configurations in your eclipse.ini (I even use bigger values for the PermSizes):
-Xms512m
-Xmx1024m
-XX:PermSize=64m
-XX:MaxPermSize=128m
My problem was solved by uhlocking the screen rotation on my android the app which was causing me a problem now works perfectly
You have to use the FormulaEvaluator, as shown here. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :
FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
if (cell!=null) {
switch (evaluator.evaluateFormulaCell(cell)) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
System.out.println(cell.getErrorCellValue());
break;
// CELL_TYPE_FORMULA will never occur
case Cell.CELL_TYPE_FORMULA:
break;
}
}
if you need the exact contant (ie the formla if the cell contains a formula), then this is shown here.
Edit : Added a few example to help you.
first you get the cell (just an example)
Row row = sheet.getRow(rowIndex+2);
Cell cell = row.getCell(1);
If you just want to set the value into the cell using the formula (without knowing the result) :
String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)";
cell.setCellFormula(formula);
cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground);
if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like
IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100))
(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error).
if you want to get the value corresponding to the formula, then you have to use the evaluator.
Hope this help,
Guillaume
Go to the XML layout Text where the widget (button or other View) indicates error, focus the cursor there and press alt+enter and select missing constraints attributes.
Must be too late now, but the right version would be:
for(var i = 0; i < restaurants.restaurant.length; i++)
{
if(restaurants.restaurant[i].food == 'chicken')
{
return restaurants.restaurant[i].name;
}
}
If you are not sure Object.keys() is going to return you the keys in the right order, you can try this logic instead
var keys = []
var obj = {
'key1' : 'value1',
'key2' : 'value2',
'key3' : 'value3',
}
for (var key in obj){
keys.push(key)
}
console.log(obj[keys[1]])
console.log(obj[keys[2]])
console.log(obj[keys[3]])
Try like this
<script>
$(document).ready(function(){
$("#order_ship_date").datepicker({
changeMonth:true,
changeYear:true,
dateFormat:"yy-mm-dd",
minDate: +2,
});
});
</script>
html code is given below
<input id="order_ship_date" type="text" class="input" style="width:80px;" />
I figured out the demo and implemented it the following way:
$.datepicker.setDefaults(
$.extend(
{'dateFormat':'dd-mm-yy'},
$.datepicker.regional['nl']
)
);
I needed to set the default for the dateformat too ...
As mentioned above the "accepted" solution fails on reparse points - yet people still mark it up(???). There's a much shorter solution that properly replicates the functionality:
public static void rmdir(string target, bool recursive)
{
string tfilename = Path.GetDirectoryName(target) +
(target.Contains(Path.DirectorySeparatorChar.ToString()) ? Path.DirectorySeparatorChar.ToString() : string.Empty) +
Path.GetRandomFileName();
Directory.Move(target, tfilename);
Directory.Delete(tfilename, recursive);
}
I know, doesn't handle the permissions cases mentioned later, but for all intents and purposes FAR BETTER provides the expected functionality of the original/stock Directory.Delete() - and with a lot less code too.
You can safely carry on processing because the old dir will be out of the way ...even if not gone because the 'file system is still catching up' (or whatever excuse MS gave for providing a broken function).
As a benefit, if you know your target directory is large/deep and don't want to wait (or bother with exceptions) the last line can be replaced with:
ThreadPool.QueueUserWorkItem((o) => { Directory.Delete(tfilename, recursive); });
You are still safe to carry on working.