Select id,name,age
from
(
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
) results
order by name
Have you tried adding both to $_SESSION
?
Then at the top of your page2.php just add:
<?php
session_start();
My issue was that my local branch had a different name than the remote branch. I was able to push by doing the following:
$ git push origin local-branch-name:remote-branch-name
(Credit to https://penandpants.com/2013/02/07/git-pushing-to-a-remote-branch-with-a-different-name/)
UPDATE: I have created a video on sending multipart/form-data requests to explain this better.
Actually, Postman can do this. Here is a screenshot
Newer version : Screenshot captured from postman chrome extension
Another version
Older version
Make sure you check the comment from @maxkoryukov
Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.
Even more useful, if you have multiple parameters you can access any/all of them with:
_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
.Returns((string a, string b, string c) => string.Concat(a,b,c));
You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.
The one I found very useful is the following:
<xsl:choose>
<xsl:when test="not(number(myNode))">
<!-- myNode is a not a number or empty(NaN) or zero -->
</xsl:when>
<xsl:otherwise>
<!-- myNode is a number (!= zero) -->
</xsl:otherwise>
</xsl:choose>
Make a div and give it a class. Then drop a img in it.
<div class="mydiv">
<img src="location/of/your/image" ></img>
</div>
Set the size of your div and make it relative.
.mydiv {
position: relative;
height:300px;
width: 100%;
overflow: hidden;
}
then style your image
img {
width: 100%;
height: auto;
overflow: hidden;
}
Hope that helps
If you're in Rails, .blank?
should be the method you are looking for:
a = nil
b = []
c = ""
a.blank? #=> true
b.blank? #=> true
c.blank? #=> true
d = "1"
e = ["1"]
d.blank? #=> false
e.blank? #=> false
So the answer would be:
variable = id if variable.blank?
If you have used Visual Studio Community or any other edition for your angular project , then go to the project folder , first type
C:\Project Folder>npm install -g http-server You will see as follows: + [email protected] added 25 packages in 4.213s
Then type C:\Project Folder>http-server –o
You will see that your application automatically comes up at http://127.0.0.1:8080/
Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here
Open the sources.list
file:
sudo nano /etc/apt/sources.list
Add a line with the source from where the packages will be retrieved. For example:
deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
Replace https://cloud.r-project.org
with whatever mirror you would like to use, and replace
version/
with whatever version of Ubuntu you are using (eg, trusty/
, xenial/
, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/
and version/
.
Fetch the secure APT key:
gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
or
gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
Add it to keyring:
gpg -a --export E084DAB9 | sudo apt-key add -
Update your sources and upgrade your installation:
sudo apt-get update && sudo apt-get upgrade
Install the new version
sudo apt-get install r-base-dev
Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:
-- copy the packages from R-oldversion/library
to R-newversion/library
, (do not overwrite a package if it already exists in the new version!).
-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE)
.
without duplicating the property
void Main()
{
var client = new Client();
NullSafeSet("test", s => client.Name = s);
Debug.Assert(person.Name == "test");
NullSafeSet("", s => client.Name = s);
Debug.Assert(person.Name == "test");
NullSafeSet(null, s => client.Name = s);
Debug.Assert(person.Name == "test");
}
void NullSafeSet(string value, Action<string> setter)
{
if (!string.IsNullOrEmpty(value))
{
setter(value);
}
}
For fields where NULL
is acceptable, you could use var_export($var, true)
to output the string
, integer
, or NULL
literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.
For example:
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");
OK, I think I have managed to find a work-flow that will get you back to where you need to be (as if you had not done the pop).
TAKE A BACKUP BEFOREHAND!! I don't know whether this will work for you, so copy your whole repo just in case it doesn't work.
1) Fix the merge problems and fix all the conflict by selecting all the changes that come from the patch (in tortoisemerge, this shows up as one.REMOETE (theirs)).
git mergetool
2) Commit these changes (they will already be added via the mergetool command). Give it a commit message of "merge" or something you remember.
git commit -m "merge"
3) Now you will still have your local unstaged changes that you started originally, with a new commit from the patch (we can get rid of this later). Now commit your unstaged changes
git add .
git add -u .
git commit -m "local changes"
4) Reverse the patch. This can be done with the following command:
git stash show -p | git apply -R
5) Commit these changes:
git commit -a -m "reversed patch"
6) Get rid of the patch/unpatch commits
git rebase -i HEAD^^^
from this, remove the two lines with 'merge' and 'reversed patch' in it.
7) Get your unstanged changes back and undo the 'local changes' commit
git reset HEAD^
I've run through it with a simple example and it gets you back to where you want to be - directly before the stash was popped, with your local changes and with the stash still being available to pop.
SELECT name
FROM orders,company
WHERE orderID = 1
AND companyID IN (attachedCompanyIDs)
attachedCompanyIDs
is a scalar value which is cast into INT
(type of companyID
).
The cast only returns numbers up to the first non-digit (a comma in your case).
Thus,
companyID IN ('1,2,3') = companyID IN (CAST('1,2,3' AS INT)) = companyID IN (1)
In PostgreSQL
, you could cast the string into array (or store it as an array in the first place):
SELECT name
FROM orders
JOIN company
ON companyID = ANY (('{' | attachedCompanyIDs | '}')::INT[])
WHERE orderID = 1
and this would even use an index on companyID
.
Unfortunately, this does not work in MySQL
since the latter does not support arrays.
You may find this article interesting (see #2
):
Update:
If there is some reasonable limit on the number of values in the comma separated lists (say, no more than 5
), so you can try to use this query:
SELECT name
FROM orders
CROSS JOIN
(
SELECT 1 AS pos
UNION ALL
SELECT 2 AS pos
UNION ALL
SELECT 3 AS pos
UNION ALL
SELECT 4 AS pos
UNION ALL
SELECT 5 AS pos
) q
JOIN company
ON companyID = CAST(NULLIF(SUBSTRING_INDEX(attachedCompanyIDs, ',', -pos), SUBSTRING_INDEX(attachedCompanyIDs, ',', 1 - pos)) AS UNSIGNED)
You can try this
DECLARE @Table TABLE(
Val INT
)
INSERT INTO @Table SELECT 3
INSERT INTO @Table SELECT 30
DECLARE @NumberPrefix INT
SET @NumberPrefix = 2
SELECT REPLICATE('0', @NumberPrefix - LEN(Val)) + CAST(Val AS VARCHAR(10))
FROM @Table
I found the solution to this with path name: /usr/lib/jvm/java-8-oracle
I'm on mint 18.1
If you are dealing with multiple projects needing different Java versions to build, there is no need to set a new JAVA_HOME
environment variable value for each build. Instead execute Maven like:
JAVA_HOME=/path/to/your/jdk mvn clean install
It will build using the specified JDK, but it won't change your environment variable.
Demo:
$ mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 11.0.6, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ JAVA_HOME=/opt/jdk1.8.0_201 mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 1.8.0_201, vendor: Oracle Corporation, runtime: /opt/jdk1.8.0_201/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ export | grep JAVA_HOME
declare -x JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
The compiler needs to know the size of the second dimension in your two dimensional array. For example:
void print_graph(g_node graph_node[], double weight[][5], int nodes);
The first case is telling the web server that you are posting JSON data as in:
{ Name : 'John Smith', Age: 23}
The second option is telling the web server that you will be encoding the parameters in the URL as in:
Name=John+Smith&Age=23
This is really easy: Example
//my object
var sendData = {field1:value1, field2:value2};
//add element
sendData['field3'] = value3;
No answers have worked for me.
All policies were correct but I have the error when installing a package
Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first.
The solution : I have uninstalled the nuget package manager plugin and reinstalled it.
curl -X GET -H "Accept: application/vnd.api+json" localhost:8082/v3/clusters
where localhost:8082
is Kafka Proxy address.
I was also facing the same issue where I was receiving the Transaction_Date as YYYYMMDD in bigint format. So I converted it into Datetime format using below query and saved it in new column with datetime format. I hope this will help you as well.
SELECT
convert( Datetime, STUFF(STUFF(Transaction_Date, 5, 0, '-'), 8, 0, '-'), 120) As [Transaction_Date_New]
FROM mydb
In C++11 you can. A note beforehand: Don't new
the array, there's no need for that.
First, string[] strArray
is a syntax error, that should either be string* strArray
or string strArray[]
. And I assume that it's just for the sake of the example that you don't pass any size parameter.
#include <string>
void foo(std::string* strArray, unsigned size){
// do stuff...
}
template<class T>
using alias = T;
int main(){
foo(alias<std::string[]>{"hi", "there"}, 2);
}
Note that it would be better if you didn't need to pass the array size as an extra parameter, and thankfully there is a way: Templates!
template<unsigned N>
void foo(int const (&arr)[N]){
// ...
}
Note that this will only match stack arrays, like int x[5] = ...
. Or temporary ones, created by the use of alias
above.
int main(){
foo(alias<int[]>{1, 2, 3});
}
You have to add extra parameter -g, which generates source level debug information. It will look like:
gcc -g prog.c
After that you can use gdb in common way.
You could try this:
if($(this).is('h1')){
doStuff();
}
See the docs for more on is().
If you want to convert all *.ipynb
files from current directory to python script, you can run the command like this:
jupyter nbconvert --to script *.ipynb
Yes this is safe.
The c language uses a feature called integer promotion to increase the number of bits in a value before performing calculations. Therefore your CLAMP255 macro will operate at integer (probably 32 bit) precision. The result is assigned to a jbyte, which reduces the integer precision back to 8 bits fit in to the jbyte.
Try with this link: http://download.eclipse.org/egit/github/updates
1)Go to Help-> Install new Software
2)Click on Add...
3)Name: eGit Location:http://download.eclipse.org/egit/github/updates
4)Click on OK
5)Accept the licence.
You are good to go
I set the content-type in the MarshallingView in the ContentNegotiatingViewResolver bean. It works easily, clean and smoothly:
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
</constructor-arg>
<property name="contentType" value="application/xml;charset=UTF-8" />
</bean>
</list>
</property>
It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an id
was given, and assign it to req.user
.
Below, you could have a route like:
app.get('/users', function(req, res) {
// check for and maybe do something with req.user
});
Since /users/123 will match the route in your example first, that will first check and find user 123
; then /users
can do something with the result of that.
Route middleware is a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a Users
model with an async findOne()
:
function loadUser(req, res, next) {
if (req.params.userId) {
Users.findOne({ id: req.params.userId }, function(err, user) {
if (err) {
next(new Error("Couldn't find user: " + err));
return;
}
req.user = user;
next();
});
} else {
next();
}
}
// ...
app.get('/user/:userId', loadUser, function(req, res) {
// do something with req.user
});
app.get('/users/:userId?', loadUser, function(req, res) {
// if req.user was set, it's because userId was specified (and we found the user).
});
// Pretend there's a "loadItem()" which operates similarly, but with itemId.
app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {
req.user.items.append(req.item.name);
});
Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:
/**
* Only allows the page to be accessed if the user is an admin.
* Requires use of `loadUser` middleware.
*/
function requireAdmin(req, res, next) {
if (!req.user || !req.user.admin) {
next(new Error("Permission denied."));
return;
}
next();
}
app.get('/top/secret', loadUser, requireAdmin, function(req, res) {
res.send('blahblahblah');
});
Hope this gave you some inspiration!
I know there's plenty of answers here already but I think newspaper3k also deserves a mention. I recently needed to complete a similar task of extracting the text from articles on the web and this library has done an excellent job of achieving this so far in my tests. It ignores the text found in menu items and side bars as well as any JavaScript that appears on the page as the OP requests.
from newspaper import Article
article = Article(url)
article.download()
article.parse()
article.text
If you already have the HTML files downloaded you can do something like this:
article = Article('')
article.set_html(html)
article.parse()
article.text
It even has a few NLP features for summarizing the topics of articles:
article.nlp()
article.summary
Try
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here
The assert computer statement is analogous to the statement make sure in English.
First and foremost, the "pass by value vs. pass by reference" distinction as defined in the CS theory is now obsolete because the technique originally defined as "pass by reference" has since fallen out of favor and is seldom used now.1
Newer languages2 tend to use a different (but similar) pair of techniques to achieve the same effects (see below) which is the primary source of confusion.
A secondary source of confusion is the fact that in "pass by reference", "reference" has a narrower meaning than the general term "reference" (because the phrase predates it).
Now, the authentic definition is:
When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable.
When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.
Things to note in this definition are:
"Variable" here means the caller's (local or global) variable itself -- i.e. if I pass a local variable by reference and assign to it, I'll change the caller's variable itself, not e.g. whatever it is pointing to if it's a pointer.
The meaning of "reference" in "pass by reference". The difference with the general "reference" term is that this "reference" is temporary and implicit. What the callee basically gets is a "variable" that is somehow "the same" as the original one. How specifically this effect is achieved is irrelevant (e.g. the language may also expose some implementation details -- addresses, pointers, dereferencing -- this is all irrelevant; if the net effect is this, it's pass-by-reference).
Now, in modern languages, variables tend to be of "reference types" (another concept invented later than "pass by reference" and inspired by it), i.e. the actual object data is stored separately somewhere (usually, on the heap), and only "references" to it are ever held in variables and passed as parameters.3
Passing such a reference falls under pass-by-value because a variable's value is technically the reference itself, not the referred object. However, the net effect on the program can be the same as either pass-by-value or pass-by-reference:
As you may see, this pair of techniques is almost the same as those in the definition, only with a level of indirection: just replace "variable" with "referenced object".
There's no agreed-upon name for them, which leads to contorted explanations like "call by value where the value is a reference". In 1975, Barbara Liskov suggested the term "call-by-object-sharing" (or sometimes just "call-by-sharing") though it never quite caught on. Moreover, neither of these phrases draws a parallel with the original pair. No wonder the old terms ended up being reused in the absence of anything better, leading to confusion.4
NOTE: For a long time, this answer used to say:
Say I want to share a web page with you. If I tell you the URL, I'm passing by reference. You can use that URL to see the same web page I can see. If that page is changed, we both see the changes. If you delete the URL, all you're doing is destroying your reference to that page - you're not deleting the actual page itself.
If I print out the page and give you the printout, I'm passing by value. Your page is a disconnected copy of the original. You won't see any subsequent changes, and any changes that you make (e.g. scribbling on your printout) will not show up on the original page. If you destroy the printout, you have actually destroyed your copy of the object - but the original web page remains intact.
This is mostly correct except the narrower meaning of "reference" -- it being both temporary and implicit (it doesn't have to, but being explicit and/or persistent are additional features, not a part of the pass-by-reference semantic, as explained above). A closer analogy would be giving you a copy of a document vs inviting you to work on the original.
1Unless you are programming in Fortran or Visual Basic, it's not the default behavior, and in most languages in modern use, true call-by-reference is not even possible.
2A fair amount of older ones support it, too
3In several modern languages, all types are reference types. This approach was pioneered by the language CLU in 1975 and has since been adopted by many other languages, including Python and Ruby. And many more languages use a hybrid approach, where some types are "value types" and others are "reference types" -- among them are C#, Java, and JavaScript.
4There's nothing bad with recycling a fitting old term per se, but one has to somehow make it clear which meaning is used each time. Not doing that is exactly what keeps causing confusion.
That's all fine and good -- but what if you want to select an existing element as the default? In my issue there is no "--select a value--" option.
Here's my code -- you could make it into a one liner if you didn't want to check for no results I suppose...
private void LoadCombo(ComboBox cb, string itemType, string defVal = "")
{
cb.DisplayMember = "Name";
cb.ValueMember = "ItemCode";
cb.DataSource = db.Items.Where(q => q.ItemTypeId == itemType).ToList();
if (!string.IsNullOrEmpty(defVal))
{
var i = ((List<GCC_Pricing.Models.Item>)cb.DataSource).FindIndex(q => q.ItemCode == defVal);
if (i>=0) cb.SelectedIndex = i;
}
}
For anyone on a Mac who has Docker Desktop installed. I was able to just click the tray icon and say Restart Docker
. Once it restarted was able to delete the containers.
Posting it from my project.
<select name="parent" id="parent"><option value="0">None</option>
<?php
$select="select=selected";
$allparent=mysql_query("select * from tbl_page_content where parent='0'");
while($parent=mysql_fetch_array($allparent))
{?>
<option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
<?php
}
?></select>
@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy()
(or .values
for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.
For example, you can use ndarray.max()
along the first axis.
# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
A B
0 1 -2
1 2 8
2 3 1
df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns,
# df['C'] = df.values.max(1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If your data has NaN
s, you will need numpy.nanmax
:
df['C'] = np.nanmax(df.values, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
You can also use numpy.maximum.reduce
. numpy.maximum
is a ufunc (Universal Function), and every ufunc has a reduce
:
df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
np.maximum.reduce
and np.max
appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max
. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).
The graph was generated using perfplot. Benchmarking code, for reference:
import pandas as pd
import perfplot
np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))
perfplot.show(
setup=lambda n: pd.concat([df_] * n, ignore_index=True),
kernels=[
lambda df: df.assign(new=df.max(axis=1)),
lambda df: df.assign(new=df.values.max(1)),
lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
],
labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
n_range=[2**k for k in range(0, 15)],
xlabel='N (* len(df))',
logx=True,
logy=True)
This is old question, but if somebody finds it today chances are php will be run via php-fpm and mod_fastcgi. In that case nothing here will help with extending execution time because Apache will terminate connection to a process which does not output anything for 30 seconds. Only way to extend it is to change -idle-timeout in apache (module/site/vhost) config.
FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi -socket /run/php/php7.0-fpm.sock -idle-timeout 900 -pass-header Authorization
More details - Increase PHP-FPM idle timeout setting
In following solution, table occupies 100% of the parent container, no absolute sizes required. It's pure CSS, flex layout is used.
Here is how it looks:
Possible disadvantages:
HTML (shortened):
<div class="table-container">
<table>
<thead>
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>content1</td>
<td>content2</td>
<td>content3</td>
<td>content4</td>
</tr>
<tr>
<td>content1</td>
<td>content2</td>
<td>content3</td>
<td>content4</td>
</tr>
...
</tbody>
</table>
</div>
CSS, with some decorations omitted for clarity:
.table-container {
height: 10em;
}
table {
display: flex;
flex-flow: column;
height: 100%;
width: 100%;
}
table thead {
/* head takes the height it requires,
and it's not scaled when table is resized */
flex: 0 0 auto;
width: calc(100% - 0.9em);
}
table tbody {
/* body takes all the remaining available space */
flex: 1 1 auto;
display: block;
overflow-y: scroll;
}
table tbody tr {
width: 100%;
}
table thead, table tbody tr {
display: table;
table-layout: fixed;
}
Same code in LESS so you can mix it in:
.table-scrollable() {
@scrollbar-width: 0.9em;
display: flex;
flex-flow: column;
thead,
tbody tr {
display: table;
table-layout: fixed;
}
thead {
flex: 0 0 auto;
width: ~"calc(100% - @{scrollbar-width})";
}
tbody {
display: block;
flex: 1 1 auto;
overflow-y: scroll;
tr {
width: 100%;
}
}
}
Simplest way I can think of:
# checking whether foo is a boolean
!!foo == foo
If someone wants the answer, I think I just got it. Try this:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait.toRaw().hashValue | UIInterfaceOrientationMask.PortraitUpsideDown.toRaw().hashValue
}
Hope it helps !
EDIT :
To force rotation, use the following code :
let value = UIInterfaceOrientation.LandscapeRight.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
It works for iOS 7 & 8 !
This can also happen in case you have enabled ProGuard. In buildTypes set minifyEnabled false, shrinkResources false, useProguard false
1.This will search XMLHelpers/XMLHelpers.psm1 in current folder
Import-Module (Resolve-Path('XMLHelpers'))
2.This will search XMLHelpers.psm1 in current folder
Import-Module (Resolve-Path('XMLHelpers.psm1'))
Doubles are approximations of the decimal numbers in your Java source. You're seeing the consequence of the mismatch between the double (which is a binary-coded value) and your source (which is decimal-coded).
Java's producing the closest binary approximation. You can use the java.text.DecimalFormat to display a better-looking decimal value.
you need to use the sqlite, security apit to store the passwords. here is best example, which stores passwords, -- passwordsafe. here is link for the source and explanation -- http://code.google.com/p/android-passwordsafe/
Adding on to what Hubro said, apparently get_highest_row()
has been deprecated. Using the max_row
and max_column
properties returns the row and column count. For example:
wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]
row_count = sheet.max_row
column_count = sheet.max_column
As far as Angular CLI: 7.1.4, there are two common ways to achieve changing the default port.
In the angular.json
, add the --port
option to serve
part and use ng serve
to start the server.
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "demos:build",
"port": 1337
},
"configurations": {
"production": {
"browserTarget": "demos:build:production"
}
}
},
In the package.json
, add the --port
option to ng serve
and use npm start
to start the server.
"scripts": {
"ng": "ng",
"start": "ng serve --port 8000",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
Try this:
(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
$_.LastWriteTime -gt (Get-Date).AddDays(-3)
}).Count
For Razor put the file DateTime.cshtml in the Views/Shared/EditorTemplates folder. DateTime.cshtml contains two lines and produces a TextBox with a date formatted 9/11/2001.
@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })
rm -f /home/user/.ssh/known_hosts
or open it up and delete the entry for the offending ip/hostname
(P.S. It tells you exactly this in the error message you posted)
In short slug help get rid of those ugly looking urls with valid-urls for examples in an ecommerec site instead of showing the url as www.myecom.com/product/5432156
i can show it like www.myecom.com/product/iphone11
with the help of slug
I think it will be easier using syntax-based query:
var entryPoint = (from ep in dbContext.tbl_EntryPoint
join e in dbContext.tbl_Entry on ep.EID equals e.EID
join t in dbContext.tbl_Title on e.TID equals t.TID
where e.OwnerID == user.UID
select new {
UID = e.OwnerID,
TID = e.TID,
Title = t.Title,
EID = e.EID
}).Take(10);
And you should probably add orderby
clause, to make sure Top(10)
returns correct top ten items.
See the documentation on plt.axis()
. This:
plt.axis('equal')
doesn't work because it changes the limits of the axis to make circles appear circular. What you want is:
plt.axis('square')
This creates a square plot with equal axes.
Even faster than a bad query:
SELECT count((1)) as `ct` FROM INFORMATION_SCHEMA.TABLES where table_schema ='yourdatabasename' and table_name='yourtablename';
This way you can just retrieve one field and one value. .016 seconds for my slower system.
Chain selectors are not limited just to classes, you can do it for both classes and ids.
Classes
.classA.classB {
/*style here*/
}
Class & Id
.classA#idB {
/*style here*/
}
Id & Id
#idA#idB {
/*style here*/
}
All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".
For your case
li.left.ui-class-selector {
/*style here*/
}
or
.left.ui-class-selector {
/*style here*/
}
Try this:
UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:
mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> UPDATE business AS b
-> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
-> SET b.mapx = g.latitude,
-> b.mapy = g.longitude
-> WHERE (b.mapx = '' or b.mapx = 0) and
-> g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
See? No syntax error. I tested against MySQL 5.5.8.
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;
For the instance:
if (obj is IMyInterface) {}
For the class:
Check if typeof(MyClass).GetInterfaces()
contains the interface.
I just did the following to change the type of an input:
$('#ID_of_element')[0].type = 'text';
and it works.
I was needing to do this because I was using jQuery UI datepickers' in an ASP NET Core 3.1 project and they were not working properly on Chromium-based browsers (see: https://stackoverflow.com/a/61296225/7420301).
Ajax.ActionLink only sends an ajax request to the server. What happens ahead really depends upon type of data returned and what your client side script does with it. You may send a partial view for ajax call or json, xml etc. Ajax.ActionLink however have different callbacks and parameters that allow you to write js code on different events. You can do something before request is sent or onComplete
. similarly you have an onSuccess callback. This is where you put your JS code for manipulating result returned by server. You may simply put it back in UpdateTargetID or you can do fancy stuff with this result using jQuery or some other JS library.
THE CORRECT WAY IS :
UPDATE test1
INNER JOIN test2 ON (test1.id = test2.id)
SET test1.data = test2.data
For me what worked is, as this error may occur for memory requirement of git. I have added these lines to my global git configuration file .gitconfig which is present in $USER_HOME i.e C:\Users\<USER_NAME>\.gitconfig
[core]
packedGitLimit = 512m
packedGitWindowSize = 512m
[pack]
deltaCacheSize = 2047m
packSizeLimit = 2047m
windowMemory = 2047m
I like to stick with the standard meaning of the words used: An article
would apply to, well, articles. I would define blog posts, documents, and news articles as articles
. Sections on the other hand, would refer to layout/ux items: sidebar, header, footer would be sections. However this is all my own personal interpretation -- as you pointed out, the specification for these elements are not well defined.
Supporting this, the w3c defines an article
element as a section of content that can independently stand on its own. A blog post could stand on it's own as a valuable and consumable item of content. However, a header would not.
Here is an interesting article about one mans madness in trying to differenciate between the two new elements. The basic point of the article, that I also feel is correct, is to try and use what ever element you feel best actually represents what it contains.
What’s more problematic is that article and section are so very similar. All that separates them is the word “self-contained”. Deciding which element to use would be easy if there were some hard and fast rules. Instead, it’s a matter of interpretation. You can have multiple articles within a section, you can have multiple sections within and article, you can nest sections within sections and articles within sections. It’s up to you to decide which element is the most semantically appropriate in any given situation.
Here is a very good answer to the same question here on SO
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
A bunch of great answers in this thread, but none quite matched my needs. I have a tabbed app with navigation controllers in each tab, and one view needed to rotate, while the others needed to be locked in portrait. The navigation controller wasn't resizing it's subviews properly, for some reason. Found a solution (in Swift 3) by combining with this answer, and the layout issues disappeared. Create the struct as suggest by @bmjohns:
import UIKit
struct OrientationLock {
static func lock(to orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lock(to orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) {
self.lock(to: orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
Then subclass UITabBarController:
import UIKit
class TabBarController: UITabBarController, UITabBarControllerDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
}
func tabBarControllerSupportedInterfaceOrientations(_ tabBarController: UITabBarController) -> UIInterfaceOrientationMask {
if tabBarController.selectedViewController is MyViewControllerNotInANavigationControllerThatShouldRotate {
return .allButUpsideDown
} else if let navController = tabBarController.selectedViewController as? UINavigationController, navController.topViewController is MyViewControllerInANavControllerThatShouldRotate {
return .allButUpsideDown
} else {
//Lock view that should not be able to rotate
return .portrait
}
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController is MyViewControllerNotInANavigationControllerThatShouldRotate {
OrientationLock.lock(to: .allButUpsideDown)
} else if let navController = viewController as? UINavigationController, navController.topViewController is MyViewControllerInANavigationControllerThatShouldRotate {
OrientationLock.lock(to: .allButUpsideDown)
} else {
//Lock orientation and rotate to desired orientation
OrientationLock.lock(to: .portrait, andRotateTo: .portrait)
}
return true
}
}
Don't forget to change the class of the TabBarController in the storyboard to the newly created subclass.
Use ProcessInfo.RedirectStandardOutput to redirect the output when creating your console process.
Then you can use Process.StandardOutput to read the program output.
The second link has a sample code how to do it.
Using just scipy, glob and having PIL installed (pip install pillow
) you can use scipy's imread method:
from scipy import misc
import glob
for image_path in glob.glob("/home/adam/*.png"):
image = misc.imread(image_path)
print image.shape
print image.dtype
According to the doc, scipy.misc.imread
is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead
. See the answer by Charles.
Most of the answers are correct but I want to add little more. The ternary operator is right-associative, which means it can be chained in the following way if … else-if … else-if … else
:
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
Equivalent to:
function example() {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
}
More details is here
for get week number in jalai calendar you can use this:
$weeknumber = date("W"); //number week in year
$dayweek = date("w"); //number day in week
if ($dayweek == "6")
{
$weeknumberint = (int)$weeknumber;
$date2int++;
$weeknumber = (string)$date2int;
}
echo $date2;
result:
15
week number change in saturday
I have resolve the problem by using the command:
- Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\tools\bin\ (If the folder is not available then download the android SDK first, or you can install it from the android studio installation process.)
- Shift+Left click and Press W,then Enter to open CMD on the folder path
- Type in the cmd: sdkmanager --licenses
- Once press enter, you need to accept all the licenses by pressing y
CHECKING THE LICENSES
- Go to: C:\Users[PC NAME]\AppData\Local\Android\sdk\
- Check the folder named licenses
android-googletv-license
android-sdk-license
android-sdk-preview-license
google-gdk-license
intel-android-extra-license
mips-android-sysimage-license
WAS TESTED ON CORDOVA USING THE COMMAND:
cordova build android
-- UPDATE NEW FOLDER PATH --
Open Android Studio, Tools > Sdk Manager > Android SDK Command-Line Tools (Just Opt-in)
SDKManager will be store in :
- Go to C:\Users\ [PC NAME] \AppData\Local\Android\Sdk\cmdline-tools\latest\bin
- Type in the cmd: sdkmanager --licenses
Documentation to using the Android SDK: https://developer.android.com/studio/command-line/sdkmanager.html
Struggling with this myself. This is my take:
https://gist.github.com/2639448:
require 'csv'
class CSV
def CSV.unparse array
CSV.generate do |csv|
array.each { |i| csv << i }
end
end
end
CSV.unparse [ %w(your array), %w(goes here) ]
As a follow-up to this question - since it relates specifically to creation time and discusses obtaining it via the new nio classes - it seems right now in JDK7's implementation you're out of luck. Addendum: same behaviour is in OpenJDK7.
On Unix filesystems you cannot retrieve the creation timestamp, you simply get a copy of the last modification time. So sad, but unfortunately true. I'm not sure why that is but the code specifically does that as the following will demonstrate.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
public class TestFA {
static void getAttributes(String pathStr) throws IOException {
Path p = Paths.get(pathStr);
BasicFileAttributes view
= Files.getFileAttributeView(p, BasicFileAttributeView.class)
.readAttributes();
System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
}
public static void main(String[] args) throws IOException {
for (String s : args) {
getAttributes(s);
}
}
}
You can also use CopyOnWriteArrayList instead of an ArrayList. This is the latest recommended approach by from JDK 1.5 onwards.
As of Xcode 6.0.1 (at least, not sure when they added it), your original example now works:
class MyClass {
var count = 0
}
let mc = MyClass()
mc.dynamicType === MyClass.self // returns `true`
To answer the original question, you can actually use the Objective-C runtime with plain Swift objects successfully.
Try the following:
import Foundation
class MyClass { }
class SubClass: MyClass { }
let mc = MyClass()
let m2 = SubClass()
// Both of these return .Some("__lldb_expr_35.SubClass"), which is the fully mangled class name from the playground
String.fromCString(class_getName(m2.dynamicType))
String.fromCString(object_getClassName(m2))
// Returns .Some("__lldb_expr_42.MyClass")
String.fromCString(object_getClassName(mc))
You can accomplish this (if I understand what you are trying to do) using dynamic SQL.
The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.
So you can use something like this approach:
SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue
+ ' AS fld1 FROM tbl' + @KeyValue
EXEC (@stmt)
First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:
'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'
At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE
(or EXEC
for short).
The old-school sp_executesql
procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.
FOLLOWUP
EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.
Consider what would happen if @KeyValue
contained the string:
'1 AS foo; DROP TABLE students; -- '
The string we would produce as a SQL statement would be:
'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'
When we EXECUTE that string as a SQL statement:
INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...
And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)
One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'
. If an illegal character is found, then reject the value, and exit without executing any SQL.
For httpclient 4.1.x you can set the proxy like this (taken from this example):
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpGet req = new HttpGet("/");
System.out.println("executing request to " + target + " via " + proxy);
HttpResponse rsp = httpclient.execute(target, req);
...
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
I used this:
String.format("%1$tH:%1$tM:%1$tS.%1$tL", millis);
See description of class Formatter.
See runnable example using input of 2400 ms.
Override method authenticationManagerBean
in WebSecurityConfigurerAdapter
to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder)
as a Spring bean:
For example:
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
I think 'git ls-remote' ( http://git-scm.com/docs/git-ls-remote ) should do what you want. Without force fetch or pull.
This worked for me fine:
File 1:
<html>
<head></head>
<body>
<a href="#" onclick="window.open('file:///D:/Examples/file2.html'); return false">CLICK ME</a>
</body>
<footer></footer>
</html>
File 2:
<html>
...
</html>
This method works regardless of whether or not the 2 files are in the same directory, BUT both files must be local.
For obvious security reasons, if File 1 is located on a remote server you absolutely cannot open a file on some client's host computer and trying to do so will open a blank target.
Note: cuongle's helfpul answer has all the ingredients, but the solution can be streamlined (no need for .ItemArray
) and can be reframed to better match the question as asked.
To create an (isolated) clone of a given System.Data.DataRow
instance, you can do the following:
// Assume that variable `table` contains the source data table.
// Create an auxiliary, empty, column-structure-only clone of the source data table.
var tableAux = table.Clone();
// Note: .Copy(), by contrast, would clone the data rows also.
// Select the data row to clone, e.g. the 2nd one:
var row = table.Rows[1];
// Import the data row of interest into the aux. table.
// This creates a *shallow clone* of it.
// Note: If you'll be *reusing* the aux. table for single-row cloning later, call
// tableAux.Clear() first.
tableAux.ImportRow(row);
// Extract the cloned row from the aux. table:
var rowClone = tableAux.Rows[0];
Note: Shallow cloning is performed, which works as-is with column values that are value type instances, but more work would be needed to also create independent copies of column values containing reference type instances (and creating such independent copies isn't always possible).
Try this:
max.setOnKeyListener(new OnKeyListener(){
@Override
public boolean onKey(View v, int keyCode, KeyEvent event){
if(keyCode == event.KEYCODE_ENTER){
//do what you want
}
}
});
Small observation. Automation mechanism to dynamically generate SQL using the 'partition by' it is much simpler to implement in relation to the 'group by'. In the case of 'group by', We must take care of the content of 'select' column.
Sorry for My English.
My research is x:Name
as global variable. However, Name
as local variable. Does that mean x:Name you can call it anywhere in your XAML file but Name is not.
Example:
<StackPanel>
<TextBlock Text="{Binding Path=Content, ElementName=btn}" />
<Button Content="Example" Name="btn" />
</StackPanel>
<TextBlock Text="{Binding Path=Content, ElementName=btn}" />
You can't Binding
property Content
of Button
with Name is "btn" because it outside StackPanel
npm install --save bootstrap
afterwards, inside angular.json
(previously .angular-cli.json
) inside the project's root folder, find styles and add the bootstrap css file like this:
for angular 6
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
for angular 7
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.css"
],
You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree
option for single commands, or the GIT_WORK_TREE
environment variable. There is also the core.worktree
configuration option but it will not work in a bare repository (check the man page for what it does).
# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status
This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.
In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.
Now sure why it worked, but it did.
Your issue is that your selector is for an anchor element <a>
. You are treating the <a>
tag as if it represents the page which is not the case.
$('head')
will work as long as this selector is being executed by the page that needs the css.
Why not simply add the css file to the page in question. Any particular reason to attempt this dynamically from another page? I am not even familiar with a way to inject css to remote pages like this ... seems like it would be a major security hole.
ADDENDUM to your reasoning:
Then you should simply pass a parameter to the page, read it using javascript, and then do whatever is needed based on the parameter.
You can try 'input[name="pwd"]':
function checkForm(){
var form = document.forms[0];
var selectElement = form.querySelector('input[name="pwd"]');
var selectedValue = selectElement.value;
}
take a look a this http://jsfiddle.net/2ZL4G/1/
I checked and it worked for me.
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" style="margin-top:100px;"><!--style with margin-top according to your need-->
<ul class="nav navbar-nav navbar-right">
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
Android studio is based on Intellij Idea. In Intellij Idea you have to do the following from the GUI menu.
Build -> Rebuild Project
/^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/
The ?
character signifies that the preceding group should be matched zero or one times. The group (-|\s)
will match either a -
or a |
character.
The MongoDB find
method does not return a single result, but a list of results in the form of a Cursor
. This latter is an iterator, so you can go through it with a for
loop.
For your case, just use the findOne
method instead of find
. This will returns you a single document as a dictionary.
urls.py:
#...
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),
views.py:
from django.shortcuts import redirect
from .models import Element
def element_info(request):
# ...
element = Element.object.get(pk=1)
return redirect('element_update', pk=element.id)
def element_update(request, pk)
# ...
No, this will not work. The best you will be able to do is to iterate through all values and check them yourself:
boolean empty = true;
for (Object item : arrayList) {
if (item != null) {
empty = false;
break;
}
}
For WINDOWS users, Follow the instruction here. https://software.intel.com/en-us/xdk/docs/installing-android-debug-bridge-adb-usb-driver-on-windows
Basically, MTP/PTP all is not needed. You need to configure your device from device manager by following the instruction in screenshots of the page.
Hope it helps.
Exceptions should only be used in truly exceptional cases
It seems like the use of exceptions has run rampant on the projects I've worked on recently.
Here's an example:
We have filters that intercept web requests. The filter calls a screener, and the screener's job is to check to see if the request has certain input parameters and validate the parameters. You set the fields to check for, and the abstract class makes sure the parameters are not blank, then calls a screen() method implemented by your particular class to do more extended validation:
public boolean processScreener(HttpServletRequest req, HttpServletResponse resp, FilterConfig filterConfig) throws Exception{
//
if (!checkFieldExistence(req)){
return false;
}
return screen(req,resp,filterConfig);
}
That checkFieldExistance(req) method never returns false. It returns true if none of the fields are missing, and throws an exception if a field is missing.
I know that this is bad design, but part of the problem is that some architects here believe that you need to throw an exception every time you hit something unexpected.
Also, I am aware that the signature of checkFieldExistance(req) does throw an Exception, its just that almost all of our methods do - so it didn't occur to me that the method might throw an exception instead of returning false. Only until I dug through the code I noticed it.
This implementation is totally based on Sinaesthetic's, but adding CancellationToken
and keeping the same execution thread and context; that is, delegating the use of Task.Run()
up to the caller depending on whether condition
needs to be evaluated in the same thread or not.
Also, notice that, if you don't really need to throw a TimeoutException
and breaking the loop is enough, you might want to make use of cts.CancelAfter()
or new CancellationTokenSource(millisecondsDelay)
instead of using timeoutTask
with Task.Delay
plus Task.WhenAny
.
public static class AsyncUtils
{
/// <summary>
/// Blocks while condition is true or task is canceled.
/// </summary>
/// <param name="ct">
/// Cancellation token.
/// </param>
/// <param name="condition">
/// The condition that will perpetuate the block.
/// </param>
/// <param name="pollDelay">
/// The delay at which the condition will be polled, in milliseconds.
/// </param>
/// <returns>
/// <see cref="Task" />.
/// </returns>
public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
{
try
{
while (condition())
{
await Task.Delay(pollDelay, ct).ConfigureAwait(true);
}
}
catch (TaskCanceledException)
{
// ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
// In this case, we only want to stop polling and finish this async Task.
}
}
/// <summary>
/// Blocks until condition is true or task is canceled.
/// </summary>
/// <param name="ct">
/// Cancellation token.
/// </param>
/// <param name="condition">
/// The condition that will perpetuate the block.
/// </param>
/// <param name="pollDelay">
/// The delay at which the condition will be polled, in milliseconds.
/// </param>
/// <returns>
/// <see cref="Task" />.
/// </returns>
public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
{
try
{
while (!condition())
{
await Task.Delay(pollDelay, ct).ConfigureAwait(true);
}
}
catch (TaskCanceledException)
{
// ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
// In this case, we only want to stop polling and finish this async Task.
}
}
/// <summary>
/// Blocks while condition is true or timeout occurs.
/// </summary>
/// <param name="ct">
/// The cancellation token.
/// </param>
/// <param name="condition">
/// The condition that will perpetuate the block.
/// </param>
/// <param name="pollDelay">
/// The delay at which the condition will be polled, in milliseconds.
/// </param>
/// <param name="timeout">
/// Timeout in milliseconds.
/// </param>
/// <exception cref="TimeoutException">
/// Thrown after timeout milliseconds
/// </exception>
/// <returns>
/// <see cref="Task" />.
/// </returns>
public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
{
if (ct.IsCancellationRequested)
{
return;
}
using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
Task waitTask = WaitWhileAsync(cts.Token, condition, pollDelay);
Task timeoutTask = Task.Delay(timeout, cts.Token);
Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);
if (!ct.IsCancellationRequested)
{
cts.Cancel(); // Cancel unfinished task
await finishedTask.ConfigureAwait(true); // Propagate exceptions
if (finishedTask == timeoutTask)
{
throw new TimeoutException();
}
}
}
}
/// <summary>
/// Blocks until condition is true or timeout occurs.
/// </summary>
/// <param name="ct">
/// Cancellation token
/// </param>
/// <param name="condition">
/// The condition that will perpetuate the block.
/// </param>
/// <param name="pollDelay">
/// The delay at which the condition will be polled, in milliseconds.
/// </param>
/// <param name="timeout">
/// Timeout in milliseconds.
/// </param>
/// <exception cref="TimeoutException">
/// Thrown after timeout milliseconds
/// </exception>
/// <returns>
/// <see cref="Task" />.
/// </returns>
public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
{
if (ct.IsCancellationRequested)
{
return;
}
using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
Task waitTask = WaitUntilAsync(cts.Token, condition, pollDelay);
Task timeoutTask = Task.Delay(timeout, cts.Token);
Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);
if (!ct.IsCancellationRequested)
{
cts.Cancel(); // Cancel unfinished task
await finishedTask.ConfigureAwait(true); // Propagate exceptions
if (finishedTask == timeoutTask)
{
throw new TimeoutException();
}
}
}
}
}
# yum groupinstall "Development tools"
# yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel
Download and install Python 3.3.0
# wget http://python.org/ftp/python/3.3.0/Python-3.3.0.tar.bz2
# tar xf Python-3.3.0.tar.bz2
# cd Python-3.3.0
# ./configure --prefix=/usr/local
# make && make altinstall
Download and install Distribute for Python 3.3
# wget http://pypi.python.org/packages/source/d/distribute/distribute-0.6.35.tar.gz
# tar xf distribute-0.6.35.tar.gz
# cd distribute-0.6.35
# python3.3 setup.py install
Install and use virtualenv for Python 3.3
# easy_install-3.3 virtualenv
# virtualenv-3.3 --distribute otherproject
New python executable in otherproject/bin/python3.3
Also creating executable in otherproject/bin/python
Installing distribute...................done.
Installing pip................done.
# source otherproject/bin/activate
# python --version
Python 3.3.0
String value = "True";
boolean result = value.equalsIgnoreCase("true") ? true : false;
If the situation is an urgent one, and you just want to do what the questioner asked in a quick and dirty way, assuming your project is under a directory called, for example, "my project":
QUICK AND DIRTY: depending on the circumstances, quick and dirty may in fact be very GOOD. What my solution here does is NOT replace irreversibly the files you have in your working directory with files hauled up/extracted from the depths of the git repository lurking beneath your .git/ directory using fiendishly clever and diabolically powerful git commands, of which there are many. YOU DO NOT HAVE TO DO SUCH DEEP-SEA DIVING TO RECOVER what may appear to be a disastrous situation, and attempting to do so without sufficient expertise may prove fatal.
Copy the whole directory and call it something else, like "my project - copy". Assuming your git repository ("repo") files are under the "my project" directory (the default place for them, under a directory called ".git"), you will now have copied both your work files and your repo files.
Do this in the directory "my project":
.../my project $ git reset --hard [first-4-letters&numbers-of-commit's-SHA]
This will return the state of the repo under "my project" to what it was when you made that commit (a "commit" means a snapshot of your working files). All commits since then will be lost forever under "my project", BUT... they will still be present in the repo under "my project - copy" since you copied all those files - including the ones under .../.git/.
You then have two versions on your system... you can examine or copy or modify files of interest, or whatever, from the previous commit. You can completely discard the files under "my project - copy", if you have decided the new work since the restored commit was going nowhere...
The obvious thing if you want to carry on with the state of the project without actually discarding the work since this retrieved commit is to rename your directory again: Delete the project containing the retrieved commit (or give it a temporary name) and rename your "my project - copy" directory back to "my project". Then maybe try to understand some of the other answers here, and probably do another commit fairly soon.
Git is a brilliant creation but absolutely no-one is able to just "pick it up on the fly": also people who try to explain it far too often assume prior knowledge of other VCS [Version Control Systems] and delve far too deep far too soon, and commit other crimes, like using interchangeable terms for "checking out" - in ways which sometimes appear almost calculated to confuse a beginner.
To save yourself much stress, learn from my scars. You have to pretty much have to read a book on Git - I'd recommend "Version Control with Git". Do it sooner rather than later. If you do, bear in mind that much of the complexity of Git comes from branching and then remerging: you can skip those parts in any book. From your question there's no reason why people should be blinding you with science.
Especially if, for example, this is a desperate situation and you're a newbie with Git!
PS: One other thought: It is (now) actually quite simple to keep the Git repo in a directory other than the one with the working files. This would mean you would not have to copy the entire Git repository using the above quick & dirty solution. See the answer by Fryer using --separate-git-dir
here. Be warned, though: If you have a "separate-directory" repository which you don't copy, and you do a hard reset, all versions subsequent to the reset commit will be lost forever, unless you have, as you absolutely should, regularly backed up your repository, preferably to the Cloud (e.g. Google Drive) among other places.
On this subject of "backing up to the Cloud", the next step is to open an account (free of course) with GitHub or (better in my view) GitLab. You can then regularly do a git push
command to make your Cloud repo up-to-date "properly". But again, talking about this may be too much too soon.
I think the most up to date gem for the new bootstrap version is form anjlab.
But I don't know if it currently works good with other gems like simple_form when you do rails generate simple_form:install --bootstrap
, etc. you may have to edit some initializers or configurations to fit the new bootstrap version.
Building off of deepee1 and this, here's how to accept a class name in a string, and then use it to read and write to a database with LINQ. I use "dynamic" instead of deepee1's casting because it allows me to assign properties, which allows us to dynamically select and operate on any table we want.
Type tableType = Assembly.GetExecutingAssembly().GetType("NameSpace.TableName");
ITable itable = dbcontext.GetTable(tableType);
//prints contents of the table
foreach (object y in itable) {
string value = (string)y.GetType().GetProperty("ColumnName").GetValue(y, null);
Console.WriteLine(value);
}
//inserting into a table
dynamic tableClass = Activator.CreateInstance(tableType);
//Alternative to using tableType, using Tony's tips
dynamic tableClass = Activator.CreateInstance(null, "NameSpace.TableName").Unwrap();
tableClass.Word = userParameter;
itable.InsertOnSubmit(tableClass);
dbcontext.SubmitChanges();
//sql equivalent
dbcontext.ExecuteCommand("INSERT INTO [TableNme]([ColumnName]) VALUES ({0})", userParameter);
My favourite way of doing this is "splitting and popping":
var str = "test_23";
alert(str.split("_").pop());
// -> 23
var str2 = "adifferenttest_153";
alert(str2.split("_").pop());
// -> 153
split() splits a string into an array of strings using a specified separator string.
pop() removes the last element from an array and returns that element.
Generally, I agree with @kgrittn's advice. Go for it.
But to address your basic question about concat()
: The new function concat()
is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.
If you can rule out null values, the good old (SQL standard) concatenation operator ||
is still the best choice, and @luis' answer is just fine:
SELECT col_a || col_b;
If either of your columns can be null, the result would be null in that case. You could defend with COALESCE
:
SELECT COALESCE(col_a, '') || COALESCE(col_b, '');
But that get tedious quickly with more arguments. That's where concat()
comes in, which never returns null, not even if all arguments are null. Per documentation:
NULL arguments are ignored.
SELECT concat(col_a, col_b);
The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string ''
, but one might want null instead (at least I would). One possible way:
SELECT CASE
WHEN col_a IS NULL THEN col_b
WHEN col_b IS NULL THEN col_a
ELSE col_a || col_b
END;
This gets more complex with more columns quickly. Again, use concat()
but add a check for the special condition:
SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
ELSE concat(col_a, col_b) END;
How does this work?
(col_a, col_b)
is shorthand notation for a row type expression ROW (col_a, col_b)
. And a row type is only null if all columns are null. Detailed explanation:
Also, use concat_ws()
to add separators between elements (ws
for "with separator").
An expression like the one in Kevin's answer:
SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
is tedious to prepare for null values in PostgreSQL 8.3 (without concat()
). One way (of many):
SELECT COALESCE(
CASE
WHEN $1.zipcode IS NULL THEN $1.city
WHEN $1.city IS NULL THEN $1.zipcode
ELSE $1.zipcode || ' - ' || $1.city
END, '')
|| COALESCE(', ' || $1.state, '');
STABLE
concat()
and concat_ws()
are STABLE
functions, not IMMUTABLE
because they can invoke datatype output functions (like timestamptz_out
) that depend on locale settings.
Explanation by Tom Lane.
This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE
function wrapper. Example here:
If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:
var get = require('simple-get');
get('http://example.com', function (err, res) {
if (err) throw err;
console.log(res.statusCode); // 200
res.pipe(process.stdout); // `res` is a stream
});
The order of execution of ng-click
and ng-model
is ambiguous since they do not define clear priorities. Instead you should use ng-change
or a $watch
on the $scope
to ensure that you obtain the correct values of the model variable.
In your case, this should work:
<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
Update: This will create a second context same as in applicationContext.xml
or you can add this code snippet to your web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
instead of
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
The safest way to pass commands to psql
in a script is by piping a string or passing a here-doc.
The man docs for the -c/--command
option goes into more detail when it should be avoided.
-c command
--command=command
Specifies that psql is to execute one command string, command, and then exit. This is useful in shell scripts. Start-up files (psqlrc and ~/.psqlrc)
are ignored with this option.
command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single
backslash command. Thus you cannot mix SQL and psql meta-commands with this option. To achieve that, you could pipe the string into psql, for
example: echo '\x \\ SELECT * FROM foo;' | psql. (\\ is the separator meta-command.)
If the command string contains multiple SQL commands, they are processed in a single transaction, unless there are explicit BEGIN/COMMIT commands
included in the string to divide it into multiple transactions. This is different from the behavior when the same string is fed to psql's standard
input. Also, only the result of the last SQL command is returned.
Because of these legacy behaviors, putting more than one command in the -c string often has unexpected results. It's better to feed multiple
commands to psql's standard input, either using echo as illustrated above, or via a shell here-document, for example:
psql <<EOF
\x
SELECT * FROM foo;
EOF
Java does not support output parameters. You can use a return value, or pass in an object as a parameter and modify the object.
The answer given by minrk (included for completeness) is good, but there is another way that I like even more.
You can also render an entire cell as LaTeX
by typing %%latex
as the first line in a text cell. This is usefull if you
minrk's answer:
IPython notebook uses MathJax to render LaTeX inside html/markdown. Just put your LaTeX math inside
$$
.$$c = \sqrt{a^2 + b^2}$$
Or you can display LaTeX / Math output from Python, as seen towards the end of the notebook tour:
from IPython.display import display, Math, Latex display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
According to this document, you should be able to do it like so:
node {
sh "#!/bin/bash \n" +
"echo \"Hello from \$SHELL\""
}
The default location to put all the web projects in ubuntu
with LAMPP
is :
/var/www/
You may make symbolic link to public_html directory from this directory.Refered. Hope this is helpful.
I ran into the same issue. Whenever I ran my test, it kept saying classes not found in the classpath. I tried to fix the testng.xml file, clean up the project and pretty much everything the answers say here, but none worked. Finally I checked my referenced libraries in build path and there were 34 invalid libraries, turns out I had renamed one of the folders from the path that I had taken the jar files from. I fixed the path and the test ran successfully.
So it might be fruitful to check if there are any errors in the referenced jar files before trying the other methods to fix this issue.
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
Ok, here is a fetch DELETE
example too:
fetch('https://example.com/delete-item/' + id, {
method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))
UIDevice identifierForVendor
introduced in iOS 6 would work for your purposes.
identifierForVendor
is an alphanumeric string that uniquely identifies a device to the app’s vendor. (read-only)
@property(nonatomic, readonly, retain) NSUUID *identifierForVendor
The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps onthe same device that come from different vendors, and for apps on different devices regardles of vendor.
Available in iOS 6.0 and later and declared in UIDevice.h
For iOS 5 refer this link UIDevice-with-UniqueIdentifier-for-iOS-5
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
like often when you have a boolean numpy array like mask
[mylist[i] for i in np.arange(len(mask), dtype=int)[mask]]
A lambda that works for any sequence or np.array:
subseq = lambda myseq, mask : [myseq[i] for i in np.arange(len(mask), dtype=int)[mask]]
newseq = subseq(myseq, mask)
If using Nginx
and getting a similar problem, then this might help:
Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.
If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
I had the following scenario that was causing the same error:
Most files were small in size, however, a few were large, and so attempting to delete those resulted in the cannot access file error.
It was not easy to find, however, the solution was as simple as Waiting "for the task to complete execution":
using (var wc = new WebClient())
{
var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
tskResult.Wait();
}
With credits to previous answer https://stackoverflow.com/a/36549068/7149454
Boostrap compatible, adust your container width (300px in this example) and you're good to go:
<div class="embed-responsive embed-responsive-16by9" style="height: 100 %; width: 300px; ">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/LbLB0K-mXMU?start=1841" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0"></iframe>
</div>
/* cellpadding */
th, td { padding: 5px; }
/* cellspacing */
table { border-collapse: separate; border-spacing: 5px; } /* cellspacing="5" */
table { border-collapse: collapse; border-spacing: 0; } /* cellspacing="0" */
/* valign */
th, td { vertical-align: top; }
/* align (center) */
table { margin: 0 auto; }
In Swift, the == operator is equivalent to Objective C's isEqual: method (it calls the isEqual method instead of just comparing pointers, and there's a new === method for testing that the pointers are the same), so you can just write this as:
if username == "" || password == ""
{
println("Sign in failed. Empty character")
}
I found this answer to the question:
http://padcom13.blogspot.co.uk/2011/10/creating-standalone-applications-with.html
Not only do you get the dependent lib files in a lib folder, you also get a bin director with both a unix and a dos executable.
The executable ultimately calls java with a -cp argument that lists all of your dependent libs too.
The whole lot sits in an appasembly folder inside the target folder. Epic.
============= Yes I know this is an old thread, but it's still coming high on search results so I thought it might help someone like me.
Try this
I recently leaned about $wpdb->prepare
HERE and added into our Free Class Booking plugin, plugin approved on wordpress.org and will live soon:
global $wpdb;
$tablename = $wpdb->prefix . "submitted_form";
$name = "Kumkum"; //string value use: %s
$email = "[email protected]"; //string value use: %s
$phone = "3456734567"; //numeric value use: %d
$country = "India"; //string value use: %s
$course = "Database"; //string value use: %s
$message = "hello i want to read db"; //string value use: %s
$now = new DateTime(); //string value use: %s
$datesent = $now->format('Y-m-d H:i:s'); //string value use: %s
$sql = $wpdb->prepare("INSERT INTO `$tablename` (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) values (%s, %s, %d, %s, %s, %s, %s)", $name, $email, $phone, $country, $course, $message, $datesent);
$wpdb->query($sql);
Thanks -Frank
you can invoke it using window.function_name() or directly function_name()
Dart http's implementation process the bytes thanks to that "charset=utf-8", so i'm sure several implementations out there supports this, to avoid the "latin-1" fallback charset when reading the bytes from the response. In my case, I totally lose format on the response body string, so I have to do the bytes encoding manually to utf8, or add that header "inner" parameter on my server's API response.
homeDirectoryPath = NSHomeDirectory();
unexpandedPath = [homeDirectoryPath stringByAppendingString:@"/Pictures/"];
folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];
unexpandedImagePath = [folderPath stringByAppendingString:@"/image.png"];
imagePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL]) {
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath attributes:nil];
}
As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.
Generally speaking, if you need to generate numbers from min
to max
(including both), you write
random.nextInt(max - min + 1) + min
Imagine you are working on a machine where n
was just the right value for it only to be possible to hold two of your arrays in memory at one time, but the total memory available, via disk caching, was still sufficient to hold all four.
Assuming a simple LIFO caching policy, this code:
for(int j=0;j<n;j++){
a[j] += b[j];
}
for(int j=0;j<n;j++){
c[j] += d[j];
}
would first cause a
and b
to be loaded into RAM and then be worked on entirely in RAM. When the second loop starts, c
and d
would then be loaded from disk into RAM and operated on.
the other loop
for(int j=0;j<n;j++){
a[j] += b[j];
c[j] += d[j];
}
will page out two arrays and page in the other two every time around the loop. This would obviously be much slower.
You are probably not seeing disk caching in your tests but you are probably seeing the side effects of some other form of caching.
There seems to be a little confusion/misunderstanding here so I will try to elaborate a little using an example.
Say n = 2
and we are working with bytes. In my scenario we thus have just 4 bytes of RAM and the rest of our memory is significantly slower (say 100 times longer access).
Assuming a fairly dumb caching policy of if the byte is not in the cache, put it there and get the following byte too while we are at it you will get a scenario something like this:
With
for(int j=0;j<n;j++){
a[j] += b[j];
}
for(int j=0;j<n;j++){
c[j] += d[j];
}
cache a[0]
and a[1]
then b[0]
and b[1]
and set a[0] = a[0] + b[0]
in cache - there are now four bytes in cache, a[0], a[1]
and b[0], b[1]
. Cost = 100 + 100.
a[1] = a[1] + b[1]
in cache. Cost = 1 + 1.c
and d
.Total cost = (100 + 100 + 1 + 1) * 2 = 404
With
for(int j=0;j<n;j++){
a[j] += b[j];
c[j] += d[j];
}
cache a[0]
and a[1]
then b[0]
and b[1]
and set a[0] = a[0] + b[0]
in cache - there are now four bytes in cache, a[0], a[1]
and b[0], b[1]
. Cost = 100 + 100.
a[0], a[1], b[0], b[1]
from cache and cache c[0]
and c[1]
then d[0]
and d[1]
and set c[0] = c[0] + d[0]
in cache. Cost = 100 + 100.(100 + 100 + 100 + 100) * 2 = 800
This is a classic cache thrash scenario.
You can manual disable ssl verfiy, and try again. :)
git config --global http.sslverify false
Simulator doesn't have a Camera. If you want to access a camera you need a device. You can't test camera on simulator. You can only check the photo and video gallery.
Debug.Print
outputs to the "Immediate" window.
Also, you can simply type ?
and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:
This can be very handy to quickly output the property of an object...
? myWidget.name
...to set the property of an object...
myWidget.name = "thingy"
...or to even execute a function or line of code, while in debugging mode:
Sheet1.MyFunction()
Example:
SELECT TRIM(' Sample ');
Result: 'Sample'
UPDATE TableName SET ColumnName = TRIM(ColumnName)
The problem by using stream().forEach(..)
with a call to add
or put
inside the forEach
(so you mutate the external myMap
or myList
instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.
One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.
Map<Boolean, List<Map.Entry<K, V>>> partitions =
animalMap.entrySet()
.stream()
.collect(partitioningBy(e -> e.getValue() == null));
Map<K, V> myMap =
partitions.get(false)
.stream()
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
List<K> myList =
partitions.get(true)
.stream()
.map(Map.Entry::getKey)
.collect(toList());
... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2>
class exists, you can create your own), e.g:
public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
return Collector.of(
() -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
(pair, entry) -> {
if(entry.getValue() == null) {
pair._2.add(entry.getKey());
} else {
pair._1.put(entry.getKey(), entry.getValue());
}
},
(p1, p2) -> {
p1._1.putAll(p2._1);
p1._2.addAll(p2._2);
return p1;
});
}
with its usage:
Tuple2<Map<K, V>, List<K>> pair =
animalMap.entrySet().parallelStream().collect(customCollector());
You can tune it more if you want, for example by providing a predicate as parameter.
If you are a windows user, right click on Start and open Windows Powershell(Run as administartor). Then type
mongod
That's it. Your database will surely get connected!
System.out.println("...") is displayed on the Android Monitor in Android Studio
I think of two ways to test for the type of a value:
Method 1:
You can use the isNaN
javascript method, which determines if a value is NaN or not. But because in your case you are testing a numerical value converted to string, Javascript is trying to guess the type of the value and converts it to the number 5 which is not NaN
. That's why if you console.log
out the result, you will be surprised that the code:
if (isNaN(i)) {
console.log('This is not number');
}
will not return anything. For this reason a better alternative would be the method 2.
Method 2:
You may use javascript typeof method to test the type of a variable or value
if (typeof i != "number") {
console.log('This is not number');
}
Notice that i'm using double equal operator, because in this case the type of the value is a string but Javascript internally will convert to Number.
A more robust method to force the value to numerical type is to use Number.isNaN which is part of new Ecmascript 6 (Harmony) proposal, hence not widespread and fully supported by different vendors.
I know it's a YEARS old topic, but I got frustrated and built a role for myself to do exactly this for an arbitrary list of files. Extend as you see fit:
main.yml
- name: created destination directory
file:
path: /path/to/directory
state: directory
mode: '0750'
- include_tasks: move.yml
loop:
- file1
- file2
- file3
move.yml
- name: stat the file
stat:
path: {{ item }}
register: my_file
- name: hard link the file into directory
file:
src: /original/path/to/{{ item }}
dest: /path/to/directory/{{ item }}
state: hard
when: my_file.stat.exists
- name: Delete the original file
file:
path: /original/path/to/{{ item }}
state: absent
when: my_file.stat.exists
Note that hard linking is preferable to copying here, because it inherently preserves ownership and permissions (in addition to not consuming more disk space for a second copy of the file).
This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them.
new_index = max(0, min(new_index, len(mylist)-1))
This is working very fast,and efficient in SQL.
Suppose you have Table Sample with 4 column a,b,c,d where a,b,d are int and c column is Varchar(50)
.
CREATE TABLE [dbo].[Sample](
[a] [int] NULL,
[b] [int] NULL,
[c] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[D] [int] NULL
)
So you cant inset multiple records in this table using following query without repeating insert statement,
DECLARE @LIST VARCHAR(MAX)
SET @LIST='SELECT 1, 1, ''Charan Ghate'',11
SELECT 2,2, ''Mahesh More'',12
SELECT 3,3,''Mahesh Nikam'',13
SELECT 4,4, ''Jay Kadam'',14'
INSERT SAMPLE (a, b, c,d) EXEC(@LIST)
Also With C# using SqlBulkCopy bulkcopy = new SqlBulkCopy(con)
You can insert 10 rows at a time
DataTable dt = new DataTable();
dt.Columns.Add("a");
dt.Columns.Add("b");
dt.Columns.Add("c");
dt.Columns.Add("d");
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr["a"] = 1;
dr["b"] = 2;
dr["c"] = "Charan";
dr["d"] = 4;
dt.Rows.Add(dr);
}
SqlConnection con = new SqlConnection("Connection String");
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(con))
{
con.Open();
bulkcopy.DestinationTableName = "Sample";
bulkcopy.WriteToServer(dt);
con.Close();
}
Math.random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Now it depends on what you want to accomplish. When you want to have Numbers from 1 to 100 for example you just have to add
(int)(Math.random()*100)
So 100 is the range of values. When you want to change the start of the range to 20 to 120 you have to add +20 at the end.
So the formula is:
(int)(Math.random()*range) + min
And you can always calculate the range with max-min, thats why Google gives you that formula.
Sometimes you want to pass all your arguments, but preceded by a flag (e.g. --flag
)
$ bar --flag "$1" --flag "$2" --flag "$3"
You can do this in the following way:
$ bar $(printf -- ' --flag "%s"' "$@")
note: to avoid extra field splitting, you must quote %s
and $@
, and to avoid having a single string, you cannot quote the subshell of printf
.
It's simple: declare the widget variables (editText
, textView
, button
etc.) in class but initialize it in onCreate
after setContentView
.
The problem is when you try to access a widget of a layout first you have to declare the layout. Declaring the layout is setContentView
.
And when you initialize the widget variable via findViewById
you are accessing the id
of the widget in the main layout in the setContentView
.
I hope you get it!
For some reason, none of the above worked for me. This DID however:
,
Replace All
Somehow CTRL + SHIFT + J is registered as a linebreak.
Type 'line numbers' into the Quick Launch textbox (top right VS 2015), and it'll take you right where you need to be (tick Line Numbers checkbox).
Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.
I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.
This works:
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
char ch='a';
double val = nan(&ch);
if(isnan(val))
cout << "isnan" << endl;
return 0;
}
output: isnan
I have also got stuck into this and believe me disabling SELinux is not a good idea.
Please just use below and you are good,
sudo restorecon -R /var/www/mysite
Enjoy..
Use CONCAT_WS instead:
CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.
SELECT CONCAT_WS('-',`affiliate_name`,`model`,`ip`,`os_type`,`os_version`) AS device_name FROM devices
@Melodia
Sorry for this is not C# code but this is what you would want, besides translating this should be easy.
FORM1
Private Sub Form1_MouseEnter(sender As Object, e As EventArgs) Handles MyBase.MouseEnter
Me.Focus()
Me.Enabled = True
Form2.Enabled = False
End Sub
Private Sub Form1_MouseLeave(sender As Object, e As EventArgs) Handles MyBase.MouseLeave
Form2.Enabled = True
Form2.Focus()
End Sub
FORM2
Private Sub Form2_MouseEnter(sender As Object, e As EventArgs) Handles MyBase.MouseEnter
Me.Focus()
Me.Enabled = True
Form1.Enabled = False
End Sub
Private Sub Form2_MouseLeave(sender As Object, e As EventArgs) Handles MyBase.MouseLeave
Form1.Enabled = True
Form1.Focus()
End Sub
Hope this helps
THIS IS NOT AN ANSWER TO THE ORIGINAL QUESTION, IT'S AN ANSWER TO @Teddy's QUESTION IN @Dudi's ANSWER'S COMMENTS
Here's a way to list id's in the active presentation to the immediate window (Ctrl + G) in VBA editor:
Sub ListAllShapes()
Dim curSlide As Slide
Dim curShape As Shape
For Each curSlide In ActivePresentation.Slides
Debug.Print curSlide.SlideID
For Each curShape In curSlide.Shapes
If curShape.TextFrame.HasText Then
Debug.Print curShape.Id
End If
Next curShape
Next curSlide
End Sub
What you are possibly looking for is map()
. You can "convert" the objects in a stream to another by mapping this way:
...
.map(userMeal -> new UserMealExceed(...))
...
If you are using Python 3.6+
you can make use of the new so called f-strings
which stands for formatted strings and it can be used by adding the character f
at the beginning of a string to identify this as an f-string.
price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!
The main benefits of using f-strings is that they are more readable, can be faster, and offer better performance:
Source Pandas for Everyone: Python Data Analysis, By Daniel Y. Chen
No doubt that the new f-strings
are more readable, as you don't have to remap the strings, but is it faster though as stated in the aformentioned quote?
price = 123
name = "Jerry"
def new():
x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"
def old():
x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)
import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776 #new
> 5.861819514350163 #old
Running 10 Million test's it seems that the new f-strings
are actually faster in mapping.
ptf <- function (txtToPrint,outFile){system(paste(paste(paste("echo '",cat(txtToPrint),sep = "",collapse = NULL),"'>",sep = "",collapse = NULL),outFile))}
#Prints txtToPrint to outFile in cwd. #!/bin/bash echo txtToPrint > outFile
Just a note about difference beetween static and dynamic.
For quick reference, all the following methods will add a new key 'a' if it does not exist already or it will update the existing key value pair with the new value offered:
data['a']=1
data.update({'a':1})
data.update(dict(a=1))
data.update(a=1)
You can also mixing them up, for example, if key 'c' is in data but 'd' is not, the following method will updates 'c' and adds 'd'
data.update({'c':3,'d':4})
it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);
DECLARE @STARTDATE datetime;
DECLARE @EntDt datetime;
set @STARTDATE = '01/01/2009';
set @EntDt = '12/31/2009';
declare @dcnt int;
;with DateList as
(
select @STARTDATE DateValue
union all
select DateValue + 1 from DateList
where DateValue + 1 < convert(VARCHAR(15),@EntDt,101)
)
select count(*) as DayCnt from (
select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )
)a
option (maxrecursion 365);
As of Java 7, the NIO Api provides a better and more generic way of accessing the contents of Zip or Jar files. Actually, it is now a unified API which allows you to treat Zip files exactly like normal files.
In order to extract all of the files contained inside of a zip file in this API, you'd do this:
In Java 8:
private void extractAll(URI fromZip, Path toDirectory) throws IOException{
FileSystems.newFileSystem(fromZip, Collections.emptyMap())
.getRootDirectories()
.forEach(root -> {
// in a full implementation, you'd have to
// handle directories
Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
});
}
In java 7:
private void extractAll(URI fromZip, Path toDirectory) throws IOException{
FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());
for(Path root : zipFs.getRootDirectories()) {
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
// You can do anything you want with the path here
Files.copy(file, toDirectory);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
// In a full implementation, you'd need to create each
// sub-directory of the destination directory before
// copying files into it
return super.preVisitDirectory(dir, attrs);
}
});
}
}
The correct way to do this is:
typedef void (*callback_function)(void); // type for conciseness
callback_function disconnectFunc; // variable to store function pointer type
void D::setDisconnectFunc(callback_function pFunc)
{
disconnectFunc = pFunc; // store
}
void D::disconnected()
{
disconnectFunc(); // call
connected = false;
}
So after research the following is discovered:
For a div#bar
setting display:block; width: auto;
causes the equivalent of outerWidth:100%;
For a table#bar
you need to wrap it in a div with the rules stated below. So your structure becomes:
<div id="foo">
<div id="barWrap" style="border....">
<table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">
This way the table takes up the parent div 100%, and #barWrap
is used to add borders/margin/padding to the #bar
table. Note that you will need to set the background of the whole thing in #barWrap
and have #bar
's background be transparent or the same as #barWrap
.
For textarea#bar
and input#bar
you need to do the same thing as table#bar
, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap
's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.
If your list of values is to be hard-coded in the script, it's fairly simple to test using case
. Here's a short example, which you can adapt to your requirements:
for item in $list
do
case "$x" in
item1|item2)
echo "In the list"
;;
not_an_item)
echo "Error" >&2
exit 1
;;
esac
done
If the list is an array variable at runtime, one of the other answers is probably a better fit.
You can fix this issue without opening the storyboard as a source. This warning is triggered by UILabels if numberOfLines !=1 and deployment target is < 8.0
HOW TO FIND IT?
Based on Bootstrap doc:
As of v3.1.0, .pull-right is deprecated on dropdown menus. use .dropdown-menu-right
eg:
<ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dLabel">
Your current combination of a POST with an HTTP 204 response is fine.
Using a POST as a universal replacement for a GET is not supported by the RFC, as each has its own specific purpose and semantics.
The purpose of a GET is to retrieve a resource. Therefore, while allowed, an HTTP 204 wouldn't be the best choice since content IS expected in the response. An HTTP 404 Not Found or an HTTP 410 Gone would be better choices if the server was unable to provide the requested resource.
The RFC also specifically calls out an HTTP 204 as an appropriate response for PUT, POST and DELETE, but omits it for GET.
See the RFC for the semantics of GET.
There are other response codes that could also be returned, indicating no content, that would be more appropriate than an HTTP 204.
For example, for a conditional GET you could receive an HTTP 304 Not Modified response which would contain no body content.
this may help for auto adjusting the image height having image 100% width
image: { width: "100%", resizeMode: "center" "contain", height: undefined, aspectRatio: 1, }
I've been using svg filters to achieve similar effects for sprites
<svg id="gray_calendar" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 48 48 48">
<filter id="greyscale">
<feColorMatrix type="saturate" values="0"/>
</filter>
<image width="48" height="10224" xlink:href="tango48i.png" filter="url(#greyscale)"/>
</svg>
<feGaussianBlur stdDeviation="10"/>
example.<image ...>
tag to apply it to any image or even use multiple images.using as will return null if not a valid cast which allows you to do other things besides wrapping the cast in a try/catch. I hate classic cast. I always use as cast if i'm not sure. Plus, exceptions are expensive. Null checks are not.
public static ArtworkData[] GetDataRecords(int UsersID)
{
ArtworkData[] Labels;
Labels = new ArtworkData[3];
return Labels;
}
This should work.
You only use the brackets when creating an array or accessing an array. Also, Array[]
is returning an array of array. You need to return the typed array ArtworkData[]
.
For what it's worth, for Gecko-based browsers you can't condition this thing off of :visited
due to the resulting privacy leaks. See http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/
svn info -r HEAD
This will give you the latest revision number at the head of your repository.
There are some nice blog posts about integrating subversion numbers into your build script:
there is also the logic grid which is more maintainable as the state machine gets bigger
You can use the storage_path();
function to get storage folder path.
storage_path(); // Return path like: laravel_app\storage
Suppose you want to save your logfile mylog.log
inside Log folder of storage folder. You have to write something like
storage_path() . '/LogFolder/mylog.log'
The magic variables %
n contains the arguments used to invoke the file: %0
is the path to the bat-file itself, %1
is the first argument after, %2
is the second and so on.
Since the arguments are often file paths, there is some additional syntax to extract parts of the path. ~d
is drive, ~p
is the path (without drive), ~n
is the file name. They can be combined so ~dp
is drive+path.
%~dp0
is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.
You can also get other kinds of meta info about the file: ~t
is the timestamp, ~z
is the size.
Look here for a reference for all command line commands. The tilde-magic codes are described under for.
I had downloaded it from http://gradle.org/gradle-download/. I use Homebrew
, but I missed installing gradle
using it.
To save some MBs by downloading it over again using Homebrew, I symlinked the gradle
binary from the downloaded (and extracted) zip archive in the /usr/local/bin/
. This is the same place where Homebrew symlinks all other binaries.
cd /usr/local/bin/
ln -s ~/Downloads/gradle-2.12/bin/gradle
Now check whether it works or not:
gradle -v
You can always use the plot()
function like so:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
plt.figure()
for y in ys:
plt.plot(x, y, 'o')
plt.show()
a="abc"
b="def"
# Equality Comparison
if [ "$a" == "$b" ]; then
echo "Strings match"
else
echo "Strings don't match"
fi
# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
echo "$b is lexicographically smaller than $a"
else
echo "Strings are equal"
fi
Notes:
if
and [
and ]
are important>
and <
are redirection operators so escape it with \>
and \<
respectively for strings.You can update your provisioning certificates in XCode at:
Organizer -> Devices -> LIBRARY -> Provisioning Profiles
There is a refresh button :) So if you have created the certificate manually in iTunes connect, then you need to press this button or download the certificate manually.
I have wondered about this in the past and came to the conclusion that it was not actually a valid test case for my code. I don't think your application code can actually tell the difference between somebody declining notifications the first time or later disabling it from the iPhone notification settings. It is true that the user experience is different but that is hidden inside the call to registerForRemoteNotificationTypes.
Calling unregisterForRemoteNotifications does not completely remove the application from the notifications settings - though it does remove the contents of the settings for that application. So this still will not cause the dialog to be presented a second time to the user the next time the app runs (at least not on v3.1.3 that I am currently testing with). But as I say above you probably should not be worrying about that.
I suggest visit Add digest auth in jmx-console and read oficial documentation for Configure admin consoles, you can add more security to your JBoss AS console and at these link explains where are the role and user/pass files that you need to change this information for your server and how you can change them. Also I recommend you quit all consoles that you don't use because they can affect to application server's performance. Also there are others links about securing jmx-console that could help you, search in jboss as community site for them (I can't put them here for my actual reputation,sorry). Never you should has the password in plain text over conf/props/ files.
Sorry for my bad English and I hope my answer be useful for you.
In Java 8, if you want to have a list
of non-repeating N
random integers in range (a, b)
, where b
is exclusive, you can use something like this:
Random random = new Random();
List<Integer> randomNumbers = random.ints(a, b).distinct().limit(N).boxed().collect(Collectors.toList());
This is totally covered by the other answers, but I'll make it explicit. An object may have class attributes and static and dynamic instance attributes.
class foo:
classy = 1
@property
def dyno(self):
return 1
def __init__(self):
self.stasis = 2
def fx(self):
return 3
stasis
is static, dyno
is dynamic (cf. property decorator) and classy
is a class attribute. If we simply do __dict__
or vars
we will only get the static one.
o = foo()
print(o.__dict__) #{'stasis': 2}
print(vars(o)) #{'stasis': 2}
So if we want the others __dict__
will get everything (and more).
This includes magic methods and attributes and normal bound methods. So lets avoid those:
d = {k: getattr(o, k, '') for k in o.__dir__() if k[:2] != '__' and type(getattr(o, k, '')).__name__ != 'method'}
print(d) #{'stasis': 2, 'classy': 1, 'dyno': 1}
The type
called with a property decorated method (a dynamic attribute) will give you the type of the returned value, not method
. To prove this let's json stringify it:
import json
print(json.dumps(d)) #{"stasis": 2, "classy": 1, "dyno": 1}
Had it been a method it would have crashed.
TL;DR. try calling extravar = lambda o: {k: getattr(o, k, '') for k in o.__dir__() if k[:2] != '__' and type(getattr(o, k, '')).__name__ != 'method'}
for all three, but not methods nor magic.
You are modifying the collection in this line:
colStates[key] = 0;
By doing so, you are essentially deleting and reinserting something at that point (as far as IEnumerable is concerned anyways.
If you edit a member of the value you are storing, that would be OK, but you are editing the value itself and IEnumberable doesn't like that.
The solution I've used is to eliminate the foreach loop and just use a for loop. A simple for loop won't check for changes that you know won't effect the collection.
Here's how you could do it:
List<string> keys = new List<string>(colStates.Keys);
for(int i = 0; i < keys.Count; i++)
{
string key = keys[i];
double Percent = colStates[key] / TotalCount;
if (Percent < 0.05)
{
OtherCount += colStates[key];
colStates[key] = 0;
}
}
From msdn
When you created the project, you made the wrong choice of application type. When asked whether your project was a console application or a windows application or a DLL or a static library, you made the wrong chose windows application (wrong choice).
Go back, start over again, go to File -> New -> Project -> Win32 Console Application -> name your app -> click next -> click application settings.
For the application type, make sure Console Application is selected (this step is the vital step).
The main for a windows application is called WinMain, for a DLL is called DllMain, for a .NET application is called Main(cli::array ^), and a static library doesn't have a main. Only in a console app is main called main
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
@JsonProperty("name")
public String mName;
@JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
I had the same program, I hope this could help.
I your using Windows 7, open Command Prompt-> run as Administrator. register your <...>.dll.
Why run as Administrator, you can register your <...>.dll using the run at the Windows Start, but still your dll only run as user even your account is administrator.
Now you can add your <...>.dll at the Project->Add Reference->Browse
Thanks
Look here: http://www.w3schools.com/tags/tag_p.asp
The p element automatically creates some space before and after itself. The space is automatically applied by the browser, or you can specify it in a style sheet.
you could remove the extra space by using css
p {
margin: 0px;
padding: 0px;
}
or use the element <span>
which has no default margins and is an inline element.
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(function() {
//here you have the control over the body of the iframe document
var iBody = $("#iView").contents().find("body");
//here you have the control over any element (#myContent)
var myContent = iBody.find("#myContent");
});
</script>
</head>
<body>
<iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>
See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).
BEGIN RSA PRIVATE KEY
is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY
is PKCS#8 and indicates that the key type is included in the key data itself. From the link:
The unencrypted PKCS#8 encoded data starts and ends with the tags:
-----BEGIN PRIVATE KEY----- BASE64 ENCODED DATA -----END PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
PrivateKeyInfo ::= SEQUENCE { version Version, algorithm AlgorithmIdentifier, PrivateKey BIT STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL }
So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.
As opposed to BEGIN RSA PRIVATE KEY
, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY
is PKCS#1
:
RSA Private Key file (PKCS#1)
The RSA private key PEM file is specific for RSA keys.
It starts and ends with the tags:
-----BEGIN RSA PRIVATE KEY----- BASE64 ENCODED DATA -----END RSA PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
RSAPrivateKey ::= SEQUENCE { version Version, modulus INTEGER, -- n publicExponent INTEGER, -- e privateExponent INTEGER, -- d prime1 INTEGER, -- p prime2 INTEGER, -- q exponent1 INTEGER, -- d mod (p-1) exponent2 INTEGER, -- d mod (q-1) coefficient INTEGER, -- (inverse of q) mod p otherPrimeInfos OtherPrimeInfos OPTIONAL }
Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:
"
git push --recurse-submodules
" learned to optionally look into the histories of submodules bound to the superproject and push them out.
Probably done after this patch and the --on-demand
option:
recurse-submodules=<check|on-demand>::
Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.
- If
check
is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
Otherwise the push will be aborted and exit with non-zero status.- If
on-demand
is used, all submodules that changed in the revisions to be pushed will be pushed.
If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.
So you could push everything in one go with (from the parent repo) a:
git push --recurse-submodules=on-demand
This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.
With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.
See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe
).
(Merged by Junio C Hamano -- gitster
-- in commit 5d35d72, 21 Dec 2015)
push
: addrecurseSubmodules
config optionThe
--recurse-submodules
command line parameter has existed for some time but it has no config file equivalent.Following the style of the corresponding parameter for
git fetch
, let's inventpush.recurseSubmodules
to provide a default for this parameter.
This also requires the addition of--recurse-submodules=no
to allow the configuration to be overridden on the command line when required.The most straightforward way to implement this appears to be to make
push
use code insubmodule-config
in a similar way tofetch
.
The git config
doc now include:
push.recurseSubmodules
:Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.
- If the value is '
check
', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.- If the value is '
on-demand
' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -- If the value is '
no
' then default behavior of ignoring submodules when pushing is retained.You may override this configuration at time of push by specifying '
--recurse-submodules=check|on-demand|no
'.
So:
git config push.recurseSubmodules on-demand
git push
Git 2.12 (Q1 2017)
git push --dry-run --recurse-submodules=on-demand
will actually work.
See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 12cf113, 16 Dec 2016)
push run with --dry-run
doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.Teach
push
to respect the--dry-run
option when configured to recursively push submodules 'on-demand'.
This is done by passing the--dry-run
flag to the child process which performs a push for a submodules when performing a dry-run.
And still in Git 2.12, you now havea "--recurse-submodules=only
" option to push submodules out without pushing the top-level superproject.
See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 792e22e, 31 Jan 2017)
If a sudo apt-get update
did not do it for you, it might be that some packages have failed to updated to repository-related errors.
For me all of those happened to reside in (Software Updates --> Other Software). You could remove them with "Remove", the cache will be refreshed successfully. Otherwise
sudo apt-get clean
apt-get autoremove
is something to try.
//call Facebook onclick on your customized button on click by the following
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
}
@Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
}
@Override
public void onError(FacebookException exception) {
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
setContentView(R.layout.activity_main);
Button mycustomizeedbutton=(Button)findViewById(R.id.mycustomizeedbutton);
mycustomizeedbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
}
});
}
var
stlst: TStringList;
begin
Label1.Caption := 'Hello,'+sLineBreak+'world!';
Label2.Caption := 'Hello,'#13#10'world!';
Label3.Caption := 'Hello,' + chr(13) + chr(10) + 'world!';
stlst := TStringList.Create;
stlst.Add('Hello,');
stlst.Add('world!');
Label4.Caption := stlst.Text;
Label5.WordWrap := True; //Multi-line Caption
Label5.Caption := 'Hello,'^M^J'world!';
Label6.Caption := AdjustLineBreaks('Hello,'#10'world!');
{http://delphi.about.com/library/rtl/blrtlAdjustLineBreaks.htm}
end;
Because the vertical-align
is set at baseline as default.
Use vertical-align:top
instead:
.small{
display: inline-block;
width: 40%;
height: 30%;
border: 1px black solid;
background: aliceblue;
vertical-align:top;
}
http://jsfiddle.net/Lighty_46/RHM5L/9/
Or as @f00644 said you could apply float
to the child elements as well.
One more, using urlretrieve
:
import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
(for Python 3+ use import urllib.request
and urllib.request.urlretrieve
)
Yet another one, with a "progressbar"
import urllib2
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
There is no replaceAt
function in JavaScript. You can use the following code to replace any character in any string at specified position:
function rep() {
var str = 'Hello World';
str = setCharAt(str,4,'a');
alert(str);
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substring(0,index) + chr + str.substring(index+1);
}
_x000D_
<button onclick="rep();">click</button>
_x000D_