Function overloading is same name function but different arguments. Function over riding means same name function and same as arguments
Well, you can at least tell Json.NET to include the type name: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_TypeNameHandling.htm . Newtonsoft.Json.JsonSerializer jser = new Newtonsoft.Json.JsonSerializer();
jser.TypeNameHandling = TypeNameHandling.Objects;
The type will be included at the beginning in the "$type" property of the object.
This is not exactly what you are looking for, but it was good enough for me when facing a similiar problem.
Have a look at the mainpage
command.
Also, have a look this answer to another thread: How to include custom files in Doxygen. It states that there are three extensions which doxygen classes as additional documentation files: .dox
, .txt
and .doc
. Files with these extensions do not appear in the file index but can be used to include additional information into your final documentation - very useful for documentation that is necessary but that is not really appropriate to include with your source code (for example, an FAQ)
So I would recommend having a mainpage.dox
(or similarly named) file in your project directory to introduce you SDK. Note that inside this file you need to put one or more C/C++ style comment blocks.
If you take a look at the constructors called from the LinkedHashSet
class you will see that internally it's a LinkedHashMap
that is used for backing purpose.
HTML css works fine if body tag does nothing you can write as well
<body scroll="no" style="overflow: hidden">
In this case overriding should be on the body tag, it is easier to control but sometimes gives headaches.
Here's an aparently free tool http://www.extradata.com/products/jarc/
With EF Core in .NET Core you can use the keyword ThenInclude
:
return DatabaseContext.Applications
.Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);
Include childs from childrens collection :
return DatabaseContext.Applications
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);
Use the bash built-in variable SECONDS
. Each time you reference the variable it will return the elapsed time since the script invocation.
Example:
echo "Start $SECONDS"
sleep 10
echo "Middle $SECONDS"
sleep 10
echo "End $SECONDS"
Output:
Start 0
Middle 10
End 20
The API's will provide full access to LIVE data, and developers can thus provide applications and develop against the API without paying licencing fees. Consumers will pay for any data received from the apps provided by third party developers, and so BB will grow their audience and revenue in that way.
NOTE: Bloomberg is offering this programming interface (BLPAPI) under a free-use license. This license does not include nor provide access to any Bloomberg data or content.
HTML controls the semantic meaning of the elements. CSS controls the layout/style of the page. Use CSS when you are controlling your layout.
In short, never use size=""
It looks like API level 11 has support for what you need. See WebViewClient.shouldInterceptRequest()
.
Sure. I suppose that you have already installed TensorFlow for GPU.
You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.
import keras
import tensorflow as tf
config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} )
sess = tf.Session(config=config)
keras.backend.set_session(sess)
Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.
For Debian users, I have this problem after modifying my locale to change machine's language. This is what I did:
Modify .bashrc:
export LANG=fr_FR.UTF-8
export LC_ALL=fr_FR.UTF-8
Uncomment line fr_FR.UTF-8
in file etc/locale.gen
-> sudo locale-gen
to generate the missing package
sudo update-locale
sudo dpkg-reconfigure locales
to configure my locale to fr_FR.UTF-8
Add extra lines to the etc/default/locale
file:
LANGUAGE=en_US.UTF-8
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
LC_TYPE=en_US.UTF-8
Reboot my computer and everything works fine
Following the rest of the clear theme of this question, the meaning and use of aggregates continues to change with every standard. There are several key changes on the horizon.
In C++17, this type is still an aggregate:
struct X {
X() = delete;
};
And hence, X{}
still compiles because that is aggregate initialization - not a constructor invocation. See also: When is a private constructor not a private constructor?
In C++20, the restriction will change from requiring:
no user-provided,
explicit
, or inherited constructors
to
no user-declared or inherited constructors
This has been adopted into the C++20 working draft. Neither the X
here nor the C
in the linked question will be aggregates in C++20.
This also makes for a yo-yo effect with the following example:
class A { protected: A() { }; };
struct B : A { B() = default; };
auto x = B{};
In C++11/14, B
was not an aggregate due to the base class, so B{}
performs value-initialization which calls B::B()
which calls A::A()
, at a point where it is accessible. This was well-formed.
In C++17, B
became an aggregate because base classes were allowed, which made B{}
aggregate-initialization. This requires copy-list-initializing an A
from {}
, but from outside the context of B
, where it is not accessible. In C++17, this is ill-formed (auto x = B();
would be fine though).
In C++20 now, because of the above rule change, B
once again ceases to be an aggregate (not because of the base class, but because of the user-declared default constructor - even though it's defaulted). So we're back to going through B
's constructor, and this snippet becomes well-formed.
A common issue that comes up is wanting to use emplace()
-style constructors with aggregates:
struct X { int a, b; };
std::vector<X> xs;
xs.emplace_back(1, 2); // error
This does not work, because emplace
will try to effectively perform the initialization X(1, 2)
, which is not valid. The typical solution is to add a constructor to X
, but with this proposal (currently working its way through Core), aggregates will effectively have synthesized constructors which do the right thing - and behave like regular constructors. The above code will compile as-is in C++20.
In C++17, this does not compile:
template <typename T>
struct Point {
T x, y;
};
Point p{1, 2}; // error
Users would have to write their own deduction guide for all aggregate templates:
template <typename T> Point(T, T) -> Point<T>;
But as this is in some sense "the obvious thing" to do, and is basically just boilerplate, the language will do this for you. This example will compile in C++20 (without the need for the user-provided deduction guide).
I'm working with minSDK=14 and was curious what set of these variations would work. I ended up with:
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
in addition to other formatting stuff. I didn't need scrollHoriontally, focusable, or focusableInTouchMode.
This set did require a call to
setSelected(true)
What I find interesting is that singleLine has allegedly been deprecated, with a recommendation to replace it with maxLines = 1. Except - when I do that, that change alone stops the text from scrolling. One would hope that when singleLine eventually bites the dust, that all its current behavior will be triggered by maxLines...
you have to update your node.js and angular/cli.If you update these two things then your project has angular.json file instead of angular-cli.json file.Then add css file into angular.json file.If you add css file into angular-cli.json file instead of angular.json file,then errors are occured.
SELECT username, numb from(
Select username, count(username) as numb from customers GROUP BY username ) as my_table
WHERE numb > 3
INSERT INTO exampleTbl VALUES('he doesn''t work for me')
If you're adding a record through ASP.NET, you can use the SqlParameter object to pass in values so you don't have to worry about the apostrophe's that users enter in.
import pandas as pd
df = pd.DataFrame({'a' : [0,0,1], 'b' : [0,0,-1]})
temp = df.abs().sum(axis=1) == 0
df = df.drop(temp)
Result:
>>> df
a b
2 1 -1
The solution above not working for the latest version on PostgreSQL. I found this way to convert epoch time being stored in number and int column type is on PostgreSQL 13:
SELECT TIMESTAMP 'epoch' + (<table>.field::int) * INTERVAL '1 second' as started_on from <table>;
For more detail explanation, you can see here https://www.yodiw.com/convert-epoch-time-to-timestamp-in-postgresql/#more-214
nav = ( NavigationView ) findViewById( R.id.navigation );
if( nav != null ){
LinearLayout mParent = ( LinearLayout ) nav.getHeaderView( 0 );
if( mParent != null ){
// Set your values to the image and text view by declaring and setting as you need to here.
SharedPreferences prefs = getSharedPreferences("user_data", MODE_PRIVATE);
String photoUrl = prefs.getString("photo_url", null);
String user_name = prefs.getString("name", "User");
if(photoUrl!=null) {
Log.e("Photo Url: ", photoUrl);
TextView userName = mParent.findViewById(R.id.user_name);
userName.setText(user_name);
ImageView user_imageView = mParent.findViewById(R.id.avatar);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_user_24dp);
requestOptions.error(R.drawable.ic_user_24dp);
Glide.with(this).load(photoUrl)
.apply(requestOptions).thumbnail(0.5f).into(user_imageView);
}
}
}
Hope this helps.
For Safari versions <5.1 the css3 property background-size
doesn't work. In such cases you need webkit
.
So you need to use -webkit-background-size
attribute to specify the background-size.
Hence use -webkit-background-size:cover
.
Reference-Safari versions using webkit
Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.
As detailed by this answer on this page, a status code of 0 means the request failed for some reason, and a javascript library interpreted the fail as a status code of 0.
1) Use this chrome extension, Requestly to redirect your url from the https
version of your url to the http
version, as this will cause a mixed content security error, and ultimately generate a status code of 0. The advantage of this approach is that you don't have to change your app at all, and you can simply "rewrite" your url using this extension.
2) Change the code of your app to optionally make your endpoint redirect to the http
version of your url instead of the https
version (or vice versa). If you do this, the request will fail with status code 0.
You can also reset page number counter:
\setcounter{page}{1}
However, with this technique you get wrong page numbers in Acrobat in the top left page numbers field:
\maketitle: 1
\tableofcontents: 2
\setcounter{page}{1}
\section{Introduction}: 1
...
You can always use the
echo "Column1`tColumn2`tColumn3..." >> results.csv
You will need to put "`t" between the columns to separates the variables into their own column. Here is the way I wrote my script:
echo "Host`tState" >> results.csv
$names = Get-Content "hostlist.txt"
foreach ($name in $names) {
$count = 0
$count2 = 13490
if ( Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue ) {
echo "$name`tUp" >> results.csv
}
else {
echo "$name`tDown" >> results.csv
}
$count++
Write-Progress -Activity "Gathering Information" -status "Pinging Hosts..." -percentComplete ($count / $count2 *100)
}
This is the easiest way to me. The output I get is :
Host|State
----------
H1 |Up
H2 |UP
H3 |Down
You can play around with the look, but that's the basic idea. The $count is just a progress bar if you want to spice up the look
The most common representations are probably these two:
Of these two the adjacency matrix is the simplest, as long as you don't mind having a (possibly huge) n * n
array, where n
is the number of vertices. Depending on the base type of the array, you can even store edge weights for use in e.g. shortest path discovery algorithms.
I thought I would add some server side php code to this answer for any beginners that read this post and are struggling to figure out how to receive the file on the server side and save the file to the filesystem.
I realize that this answer does not directly answer the OP's question, but since Brandon's answer is sufficient for the iOS device side of uploading and he mentions that some knowledge of php is necessary, I thought I would fill in the php gap with this answer.
Here is a class I put together with some sample usage code. Note that the files are stored in directories based on which user is uploading them. This may or may not be applicable to your use, but I thought I'd leave it in place just in case.
<?php
class upload
{
protected $user;
protected $isImage;
protected $isMovie;
protected $file;
protected $uploadFilename;
protected $uploadDirectory;
protected $fileSize;
protected $fileTmpName;
protected $fileType;
protected $fileExtension;
protected $saveFilePath;
protected $allowedExtensions;
function __construct($file, $userPointer)
{
// set the file we're uploading
$this->file = $file;
// if this is tied to a user, link the user account here
$this->user = $userPointer;
// set default bool values to false since we don't know what file type is being uploaded yet
$this->isImage = FALSE;
$this->isMovie = FALSE;
// setup file properties
if (isset($this->file) && !empty($this->file))
{
$this->uploadFilename = $this->file['file']['name'];
$this->fileSize = $this->file['file']['size'];
$this->fileTmpName = $this->file['file']['tmp_name'];
$this->fileType = $this->file['file']['type'];
}
else
{
throw new Exception('Received empty data. No file found to upload.');
}
// get the file extension of the file we're trying to upload
$tmp = explode('.', $this->uploadFilename);
$this->fileExtension = strtolower(end($tmp));
}
public function image($postParams)
{
// set default error alert (or whatever you want to return if error)
$retVal = array('alert' => '115');
// set our bool
$this->isImage = TRUE;
// set our type limits
$this->allowedExtensions = array("png");
// setup destination directory path (without filename yet)
$this->uploadDirectory = DIR_IMG_UPLOADS.$this->user->uid."/photos/";
// if user is not subscribed they are allowed only one image, clear their folder here
if ($this->user->isSubscribed() == FALSE)
{
$this->clearFolder($this->uploadDirectory);
}
// try to upload the file
$success = $this->startUpload();
if ($success === TRUE)
{
// return the image name (NOTE: this wipes the error alert set above)
$retVal = array(
'imageName' => $this->uploadFilename,
);
}
return $retVal;
}
public function movie($data)
{
// update php settings to handle larger uploads
set_time_limit(300);
// you may need to increase allowed filesize as well if your server is not set with a high enough limit
// set default return value (error code for upload failed)
$retVal = array('alert' => '92');
// set our bool
$this->isMovie = TRUE;
// set our allowed movie types
$this->allowedExtensions = array("mov", "mp4", "mpv", "3gp");
// setup destination path
$this->uploadDirectory = DIR_IMG_UPLOADS.$this->user->uid."/movies/";
// only upload the movie if the user is a subscriber
if ($this->user->isSubscribed())
{
// try to upload the file
$success = $this->startUpload();
if ($success === TRUE)
{
// file uploaded so set the new retval
$retVal = array('movieName' => $this->uploadFilename);
}
}
else
{
// return an error code so user knows this is a limited access feature
$retVal = array('alert' => '13');
}
return $retVal;
}
//-------------------------------------------------------------------------------
// Upload Process Methods
//-------------------------------------------------------------------------------
private function startUpload()
{
// see if there are any errors
$this->checkForUploadErrors();
// validate the type received is correct
$this->checkFileExtension();
// check the filesize
$this->checkFileSize();
// create the directory for the user if it does not exist
$this->createUserDirectoryIfNotExists();
// generate a local file name
$this->createLocalFileName();
// verify that the file is an uploaded file
$this->verifyIsUploadedFile();
// save the image to the appropriate folder
$success = $this->saveFileToDisk();
// return TRUE/FALSE
return $success;
}
private function checkForUploadErrors()
{
if ($this->file['file']['error'] != 0)
{
throw new Exception($this->file['file']['error']);
}
}
private function checkFileExtension()
{
if ($this->isImage)
{
// check if we are in fact uploading a png image, if not return error
if (!(in_array($this->fileExtension, $this->allowedExtensions)) || $this->fileType != 'image/png' || exif_imagetype($this->fileTmpName) != IMAGETYPE_PNG)
{
throw new Exception('Unsupported image type. The image must be of type png.');
}
}
else if ($this->isMovie)
{
// check if we are in fact uploading an accepted movie type
if (!(in_array($this->fileExtension, $this->allowedExtensions)) || $this->fileType != 'video/mov')
{
throw new Exception('Unsupported movie type. Accepted movie types are .mov, .mp4, .mpv, or .3gp');
}
}
}
private function checkFileSize()
{
if ($this->isImage)
{
if($this->fileSize > TenMB)
{
throw new Exception('The image filesize must be under 10MB.');
}
}
else if ($this->isMovie)
{
if($this->fileSize > TwentyFiveMB)
{
throw new Exception('The movie filesize must be under 25MB.');
}
}
}
private function createUserDirectoryIfNotExists()
{
if (!file_exists($this->uploadDirectory))
{
mkdir($this->uploadDirectory, 0755, true);
}
else
{
if ($this->isMovie)
{
// clear any prior uploads from the directory (only one movie file per user)
$this->clearFolder($this->uploadDirectory);
}
}
}
private function createLocalFileName()
{
$now = time();
// try to create a unique filename for this users file
while(file_exists($this->uploadFilename = $now.'-'.$this->uid.'.'.$this->fileExtension))
{
$now++;
}
// create our full file save path
$this->saveFilePath = $this->uploadDirectory.$this->uploadFilename;
}
private function clearFolder($path)
{
if(is_file($path))
{
// if there's already a file with this name clear it first
return @unlink($path);
}
elseif(is_dir($path))
{
// if it's a directory, clear it's contents
$scan = glob(rtrim($path,'/').'/*');
foreach($scan as $index=>$npath)
{
$this->clearFolder($npath);
@rmdir($npath);
}
}
}
private function verifyIsUploadedFile()
{
if (! is_uploaded_file($this->file['file']['tmp_name']))
{
throw new Exception('The file failed to upload.');
}
}
private function saveFileToDisk()
{
if (move_uploaded_file($this->file['file']['tmp_name'], $this->saveFilePath))
{
return TRUE;
}
throw new Exception('File failed to upload. Please retry.');
}
}
?>
Here's some sample code demonstrating how you might use the upload class...
// get a reference to your user object if applicable
$myUser = $this->someMethodThatFetchesUserWithId($myUserId);
// get reference to file to upload
$myFile = isset($_FILES) ? $_FILES : NULL;
// use try catch to return an error for any exceptions thrown in the upload script
try
{
// create and setup upload class
$upload = new upload($myFile, $myUser);
// trigger file upload
$data = $upload->image(); // if uploading an image
$data = $upload->movie(); // if uploading movie
// return any status messages as json string
echo json_encode($data);
}
catch (Exception $exception)
{
$retData = array(
'status' => 'FALSE',
'payload' => array(
'errorMsg' => $exception->getMessage()
),
);
echo json_encode($retData);
}
As stated multiple times, inversion is achieved by the -v
option to grep
. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep
help text:
grep --help | grep invert
-v, --invert-match select non-matching lines
>>> from datetime import date
>>> date.today().month
2
>>> date.today().year
2020
>>> date.today().day
13
You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility. This is still true in SQL Server 2014 - you cannot restore a 2014 backup on anything other than another 2014 box (or something newer).
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts
) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.
The compatibility mode setting just controls what T-SQL features are available to you - which can help to prevent accidentally using new features not available in other servers. But it does NOT change the internal file format for the .mdf
files - this is NOT a solution for that particular problem - there is no solution for restoring a backup from a newer version of SQL Server on an older instance.
pow
is built into the language(not part of the math library). The problem is that you haven't imported math.
Try this:
import math
math.sqrt(4)
string result = myList.FirstOrDefault(x => x == myString)
if(result != null)
{
//found
}
Actaully there's a hacky solution for this problem. Let's say you want to select the biggest tree of each forest in a region.
SELECT (array_agg(tree.id ORDER BY tree_size.size)))[1]
FROM tree JOIN forest ON (tree.forest = forest.id)
GROUP BY forest.id
When you group trees by forests there will be an unsorted list of trees and you need to find the biggest one. First thing you should do is to sort the rows by their sizes and select the first one of your list. It may seems inefficient but if you have millions of rows it will be quite faster than the solutions that includes JOIN
's and WHERE
conditions.
BTW, note that ORDER_BY
for array_agg
is introduced in Postgresql 9.0
right click somewhere on the file or in project explorer and choose 'run as'->'java application'
a.button:hover{
background: #383; }
works for me but in my case
#buttonClick:hover {
background-color:green; }
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
I needed to do this recently and after trying a few different permutations (using onfocus, onclick of textbox etc), I finally settled on this...
<input id="autocomplete" name="autocomplete" type="text"
value="Choose Document">
<p>
<button type="submit" value="Submit" name="submit" id="submit" >
Submit
</button>
</p>
<script type="text/javascript">
$("#autocomplete").autocomplete(
{
source: '@Url.Content("~/Document/DocumentTypeAutoComplete/")' //<--ddl source
, minLength: 0 // <-- This is necessary to get the search going on blank input
, delay: 0
, select: function (event, ui)
{
if (ui.item) {
$("#autocomplete").val(ui.item.value);//<-- Place selection in the textbox
$("docForm").submit();
loadDocTypeCreatePartial(ui.item);
$("#submit").focus(); //This stops the drop down list from reopening
// after an item in the select box is chosen
// You can place the focus anywhere you'd like,
// I just chose my *submit* button
}
}
}).focus(function () {
// following line will autoselect textbox text
// making it easier for the user to overwrite whats in the
// textbox
$(this).select();
//The below line triggers the search function on an empty string
$(this).data("autocomplete").search('');
});
</script>
This opens the autocomplete ddl list on focus (Even if you have default text in your input box like I do above).
It also auto-selects the text in the text box to prevent the user from having to clear out the text.
Once an item is selected from the auto-complete list, it puts that item into the auto-complete input box and moves the focus to another control (thus preventing the auto-complete from reopening).
I plan on replacing it by adding dynamic Ajax calls to the very nice Chosen select lists with the Melting Ice upgrade when I get a chance.
Specifying CV_THRESH_OTSU
causes the threshold value to be ignored. From the documentation:
Also, the special value THRESH_OTSU may be combined with one of the above values. In this case, the function determines the optimal threshold value using the Otsu’s algorithm and uses it instead of the specified thresh . The function returns the computed threshold value. Currently, the Otsu’s method is implemented only for 8-bit images.
This code reads frames from the camera and performs the binary threshold at the value 20.
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int main(int argc, const char * argv[]) {
VideoCapture cap;
if(argc > 1)
cap.open(string(argv[1]));
else
cap.open(0);
Mat frame;
namedWindow("video", 1);
for(;;) {
cap >> frame;
if(!frame.data)
break;
cvtColor(frame, frame, CV_BGR2GRAY);
threshold(frame, frame, 20, 255, THRESH_BINARY);
imshow("video", frame);
if(waitKey(30) >= 0)
break;
}
return 0;
}
Use
var arrayNames = (from DataColumn x in dt.Columns
select x.ColumnName).ToArray();
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage originalImage = ImageIO.read(scrFile);
//int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
It's now called rounded-circle
as explained here in the BS4 docs
<img src="img/gallery2.JPG" class="rounded-circle">
Compiler It converts the source code into the object code.
Linker It combines the multiple object files into a single executable program file.
Loader It loads the executable file into main memory.
9 years too late to the party, but a different approach to your problem (that nobody has mentioned?):
The statement-body works fine with Func<>
but won't work with Expression<Func<>>
. IQueryable.Select
wants an Expression<>
, because they can be translated for Entity Framework - Func<>
can not.
So you either use the AsEnumerable
and start working with the data in memory (not recommended, if not really neccessary) or you keep working with the IQueryable<>
which is recommended.
There is something called linq query
which makes some things easier:
IQueryable<Obj> result = from o in objects
let someLocalVar = o.someVar
select new Obj
{
Var1 = someLocalVar,
Var2 = o.var2
};
with let
you can define a variable and use it in the select
(or where
,...) - and you keep working with the IQueryable
until you really need to execute and get the objects.
Afterwards you can Obj[] myArray = result.ToArray()
You need to add:
#include <string>
In your header file.
I would like to re-structure the statement that you mentioned which is:
This means that the state as consumed by your target component can have a wildly different structure from the state as it is stored on your store
You can say that the state consumed by your target component has a small portion of the state that is stored on the redux store. In other words, the state consumed by your component would be the sub-set of the state of the redux store.
As far as understanding the connect() method is concerned, it's fairly simple! connect() method has the power to add new props to your component and even override existing props. It is through this connect method that we can access the state of the redux store as well which is thrown to us by the Provider. A combination of which works in your favor and you get to add the state of your redux store to the props of your component.
Above is some theory and I would suggest you look at this video once to understand the syntax better.
Just construct a new Date
object without any arguments; this will assign the current date and time to the new object.
import java.util.Date;
Date d = new Date();
In the words of the Javadocs for the zero-argument constructor:
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
Make sure you're using java.util.Date
and not java.sql.Date
-- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)
Your where
clause will return all rows where tester
does not match username
AND where tester
is not null.
If you want to include NULLs, try:
where tester <> 'username' or tester is null
If you are looking for strings that do not contain the word "username" as a substring, then like
can be used:
where tester not like '%username%'
It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:
Use raw_input
in Python 2.x, and input
in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)
For example:
user_input = raw_input("Some input please: ")
More details can be found here.
So, for example, you might have a script that looks like this
# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)
# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3
# Now do something with the above
print(user_input)
If you saved this in foo.py
, you could just call the script from the command line, it would print out tok tiktok
, then ask you for input. You could enter bar baz
(followed by the enter key) and it would print bar baz
. Here's what that would look like:
$ python foo.py
tok tiktok
Some input please: bar baz
bar baz
Here, $
represents the command-line prompt (so you don't actually type that), and I hit Enter
after typing bar baz
when it asked for input.
Suppose you have a script named foo.py
and want to call it with arguments bar
and baz
from the command line like
$ foo.py bar baz
(Again, $
represents the command-line prompt.) Then, you can do that with the following in your script:
import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]
Here, the variable arg1
will contain the string 'bar'
, and arg2
will contain 'baz'
. The object sys.argv
is just a list containing everything from the command line. Note that sys.argv[0]
is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:]
.
This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.
Here's the difference:
INSERT
creates a new row. I'm guessing that you really want to create a new row.UPDATE
changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.So this will probably do what you want:
$sql = "INSERT INTO `access_users`
(`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)
VALUES (:firstname, :surname, :email, :telephone);
";
Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.
MySQL also supports an alternative syntax for INSERT:
$sql = "INSERT INTO `access_users`
SET `contact_first_name` = :firstname,
`contact_surname` = :surname,
`contact_email` = :email,
`telephone` = :telephone
";
This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.
Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:
<div class="wrapWithBackgroundImage">
<a href="#" class="invisibleLink"></a>
</div>
.wrapWithBackgroundImage {
background-image: url(...);
}
.invisibleLink {
display: block;
left: 55px; top: 55px;
position: absolute;
height: 55px width: 55px;
}
Haskell is a general purpose programming language. It can be used for anything you use any other language to do. You aren't limited by anything but your own imagination. As for what it's suited for? Well, pretty much everything. There are few tasks in which a functional language does not excel.
And yes, I'm the Rayne from Dreamincode. :)
I would also like to mention that, in case you haven't read the Wikipedia page, functional programming is a paradigm like Object Oriented programming is a paradigm. Just in case you didn't know. Haskell is also functional in the sense that it works; it works quite well at that.
Just because a language isn't an Object Oriented language doesn't mean the language is limited by anything. Haskell is a general-purpose programming language, and is just as general purpose as Java.
SET date = DATE_ADD( fieldname, INTERVAL 2 DAY )
NOTE: Path for adb has changed since Android Studio 1.0.xx
For bash shell, use:
echo 'export PATH=$PATH:'$HOME'/Library/Android/sdk/platform-tools' >> ~/.bash_profile
For tcsh shell, use:
echo 'setenv PATH $PATH\:'$HOME'/Library/Android/sdk/platform-tools' >> ~/.tcshrc
From my experience and Maven best practices there are two kinds of "parent poms"
"company" parent pom - this pom contains your company specific information and configuration that inherit every pom and doesn't need to be copied. These informations are:
Preparing this parent pom need to be done with caution, because all your company poms will inherit from it, so this pom have to be mature and stable (releasing a version of parent pom should not affect to release all your company projects!)
The intention is to be scalable to a large scale build so should be scalable to a large number of projects and artifacts.
Mutliprojects have structure of trees - so you aren't arrown down to one level of parent pom. Try to find a suitable project struture for your needs - a classic exmample is how to disrtibute mutimodule projects
distibution/
documentation/
myproject/
myproject-core/
myproject-api/
myproject-app/
pom.xml
pom.xml
A few bonus questions:
- Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).
This configuration has to be wisely splitted into a "company" parent pom and project parent pom(s). Things related to all you project go to "company" parent and this related to current project go to project one's.
- How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?
Company parent pom have to be released first. For multiprojects standard rules applies. CI server need to know all to build the project correctly.
Please change your javascript function as like below....
$(function () {
$("#projectKey").change(function () {
alert($('option:selected').text());
});
});
You do not need to use $(this)
in alert.
From lambda answer, I have made something closer to the requirements.
boolean imageCreated = false;
Bitmap bmp = null;
Marker currentLocationMarker;
private void doSomeCustomizationForMarker(LatLng currentLocation) {
if (!imageCreated) {
imageCreated = true;
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
bmp = Bitmap.createBitmap(400, 400, conf);
Canvas canvas1 = new Canvas(bmp);
Paint color = new Paint();
color.setTextSize(30);
color.setColor(Color.WHITE);
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inMutable = true;
Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),
R.drawable.messi,opt);
Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 320, 320, true);
canvas1.drawBitmap(resized, 40, 40, color);
canvas1.drawText("Le Messi", 30, 40, color);
currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation)
.icon(BitmapDescriptorFactory.fromBitmap(bmp))
// Specifies the anchor to be at a particular point in the marker image.
.anchor(0.5f, 1));
} else {
currentLocationMarker.setPosition(currentLocation);
}
}
Well those Data Annotations should do the trick, maybe is something related with the PostgreSQL Provider.
From EF Core documentation:
Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during
SaveChanges
.
You could also try with this Fluent Api configuration:
modelBuilder.Entity<Foo>()
.Property(f => f.Id)
.ValueGeneratedOnAdd();
But as I said earlier, I think this is something related with the DB provider. Try to add a new row to your DB and check later if was generated a value to the Id
column.
I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound
This means that nothing is bound to the jndi name greetJndi
, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.
Is there any specific directory structure to deploy in JBoss?
The internal structure of the ejb-jar
is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):
. +-- greetBean.java +-- greetHome.java +-- greetRemote.java +-- META-INF +-- ejb-jar.xml +-- jboss.xml
But as already mentioned, this tutorial is full of mistakes:
<enterprise-beans>]
<-- HERE) in the ejb-jar.xml
(!)PUBLIC
in the ejb-jar.xml
and jboss.xml
(!!)jboss.xml
is incorrect, it should contain a session
element instead of entity
(!!!)Here is a "fixed" version of the ejb-jar.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<home>greetHome</home>
<remote>greetRemote</remote>
<ejb-class>greetBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
And of the jboss.xml
:
<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<jndi-name>greetJndi</jndi-name>
</session>
</enterprise-beans>
</jboss>
After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:
21:48:06,512 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/} 21:48:06,534 INFO [EjbDeployer] installing bean: ejb/#greetBean,uid19981448 21:48:06,534 INFO [EjbDeployer] with dependencies: 21:48:06,534 INFO [EjbDeployer] and supplies: 21:48:06,534 INFO [EjbDeployer] jndi:greetJndi 21:48:06,624 INFO [EjbModule] Deploying greetBean 21:48:06,661 WARN [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/ 21:48:06,805 INFO [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'
That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
My usecase is:
I am on later versions of Selenium 3, and the login popup is not detected with driver.switchTo().alert();
- results in NoAlertPresentException
.
Just providing username:password
in the URL is not propagated from step 1 to 2 above.
My workaround:
import org.apache.http.client.utils.URIBuilder;
driver.get(...webapp_location...);
wait.until(ExpectedConditions.urlContains(...sso_server...));
URIBuilder uri = null;
try {
uri = new URIBuilder(driver.getCurrentUrl());
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
uri.setUserInfo(username, password);
driver.navigate().to(uri.toString());
Finaly I found another answer for this problem. and this is working for me. Just add below datas to the your webconfig file.
<configuration>
<system.webServer>
<security>
<requestFiltering>
<verbs allowUnlisted="true">
<add verb="OPTIONS" allowed="false" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Form more information, you can visit this web site: http://www.iis.net/learn/manage/configuring-security/use-request-filtering
if you want to test your web site, is it working or not... You can use "HttpRequester" mozilla firefox plugin. for this plugin: https://addons.mozilla.org/En-us/firefox/addon/httprequester/
If you cannot use TRUNCATE
(e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:
ALTER TABLE mytable AUTO_INCREMENT = 1
iOS7 onwards, we have below default methods :
- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates
Calling above method is faster than trying to render the contents of the current view into a bitmap image yourself.
If you want to apply a graphical effect, such as blur, to a snapshot, use the drawViewHierarchyInRect:afterScreenUpdates:
method instead.
A pure PowerShell alternative that works with PowerShell 3 and .NET 4.5 (if you can use it):
function ZipFiles( $zipfilename, $sourcedir )
{
Add-Type -Assembly System.IO.Compression.FileSystem
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
$zipfilename, $compressionLevel, $false)
}
Just pass in the full path to the zip archive you would like to create and the full path to the directory containing the files you would like to zip.
import json
myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}]}
myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}
Three ways in android studio for adding a external library.
if you want to add libarary project dependency in your project :
A. In file menu click new and choose import module choose your library project path and click ok, library project automatically add in your android studio project .
B. Now open your main module(like app) gradle file and add project dependency in dependency section dependencies {
compile project(':library project name')
if you want to add jar file : A. add jar file in libs folder. B. And Add dependency
compile fileTree(dir: 'libs', include: '*.jar') // add all jar file from libs folder, if you want to add particular jar from libs add below dependency.
compile files('libs/abc.jar')
Add Dependency from url (recommended). like
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
export PATH=/usr/local/bin:$PATH
brew update
brew install vim && brew install macvim
brew link macvim
You now have the latest versions of vim and macvim managed by brew. Run brew update && brew upgrade
every once in a while to upgrade them.
This includes the installation of the CLI mvim
and the mac application (which both point to the same thing).
I use this setup and it works like a charm. Brew even takes care of installing vim with the preferable options.
PLplot is a cross-platform software package for creating scientific plots. They aren't very pretty (eye catching), but they look good enough. Have a look at some examples (both source code and pictures).
The PLplot core library can be used to create standard x-y plots, semi-log plots, log-log plots, contour plots, 3D surface plots, mesh plots, bar charts and pie charts. It runs on Windows (2000, XP and Vista), Linux, Mac OS X, and other Unices.
I needeed to solve very similar problem, which is configuring Jackson Mapper to "Do not serialize null values for Christ's sake!!!".
I didn't want to leave fancy mvc:annotation-driven tag, so I found, how to configure Jackson's ObjectMapper without removing mvc:annotation-driven and adding not really fancy ContentNegotiatingViewResolver.
The beautiful thing is that you don't have to write any Java code yourself!
And here is the XML configuration (don't be confused with different namespaces of Jackson classes, I simply used new Jakson 2.x library ... the same should also work with Jackson 1.x libraries):
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
This jQuery plugin gives you a pre-made way of selection/caret manipulation.
Using wget
wget -O /tmp/myfile 'http://www.google.com/logo.jpg'
or curl:
curl -o /tmp/myfile 'http://www.google.com/logo.jpg'
I think what you have missed here is this:
https://maven.apache.org/settings.html#Servers
The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.
This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.
Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml
like this:
<settings ...>
.
.
.
<servers>
<server>
<id>internal-repository-group</id>
<username>YOUR-USERNAME-HERE</username>
<password>YOUR-PASSWORD-HERE</password>
</server>
</servers>
</settings>
EDIT:
You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.
The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.
Following is a sample pom of a project using "internal-repository-group"
<repositories>
<repository>
<id>internal-repository-group</id>
<name>repo-name</name>
<url>http://project.com/yourrepourl/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
Once you're logged in as postgres
, you should be able to write:
psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';'
to print out just the value of that field, which means that you can capture it to (for example) save in a Bash variable:
testuser_defaults="$(psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';')"
To handle the logging in as postgres
, I recommend using sudo
. You can give a specific user the permission to run
sudo -u postgres /path/to/this/script.sh
so that they can run just the one script as postgres
.
Not sure about flexbox but you can do using the position property.
set parent div
position: relative
and child element which might be an <p>
or <h1>
etc.. set position: absolute
and bottom: 0
.
Example:
index.html
<div class="parent">
<p>Child</p>
</div>
style.css
.parent {
background: gray;
width: 10%;
height: 100px;
position: relative;
}
p {
position: absolute;
bottom: 0;
}
<html>
<body>
<p>Enter some text in the fields below, and then press the "Submit form" button to submit the form.</p>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit form">
</form>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
</script>
</body>
</html>
I had a similar problem for the preview Web API. Did not port that part to the new MVC 4 Web API yet, but maybe this helps:
REST file upload with HttpRequestMessage or Stream?
Please let me know, can sit down tomorrow and try to implement it again.
If you think the executable is locked by a process, try Process Explorer from SysInternals. In the File/handle, enter Fibonacci.exe and you should see who holds the file.
If it is not enough, you can use Process Monitor (from SysInternals, again) to follow the activity of all processes on your system on Fibonacci.exe. With a little bit of analysis (call stacks), you'll may find out why the access to the file is denied and what make it disappear.
You will have to provide the entire user dn
in SECURITY_PRINCIPAL
like this
env.put(Context.SECURITY_PRINCIPAL, "cn=username,ou=testOu,o=test");
To show all privileges:
select name from system_privilege_map;
This might be not so obvious, but sometime is required to test the executable to appropriately call it without an external shell process:
function tkl_is_file_os_exec()
{
[[ ! -x "$1" ]] && return 255
local exec_header_bytes
case "$OSTYPE" in
cygwin* | msys* | mingw*)
# CAUTION:
# The bash version 3.2+ might require a file path together with the extension,
# otherwise will throw the error: `bash: ...: No such file or directory`.
# So we make a guess to avoid the error.
#
{
read -r -n 4 exec_header_bytes 2> /dev/null < "$1" ||
{
[[ -x "${1%.exe}.exe" ]] && read -r -n 4 exec_header_bytes 2> /dev/null < "${1%.exe}.exe"
} ||
{
[[ -x "${1%.com}.com" ]] && read -r -n 4 exec_header_bytes 2> /dev/null < "${1%.com}.com"
}
} &&
if [[ "${exec_header_bytes:0:3}" == $'MZ\x90' ]]; then
# $'MZ\x90\00' for bash version 3.2.42+
# $'MZ\x90\03' for bash version 4.0+
[[ "${exec_header_bytes:3:1}" == $'\x00' || "${exec_header_bytes:3:1}" == $'\x03' ]] && return 0
fi
;;
*)
read -r -n 4 exec_header_bytes < "$1"
[[ "$exec_header_bytes" == $'\x7fELF' ]] && return 0
;;
esac
return 1
}
# executes script in the shell process in case of a shell script, otherwise executes as usual
function tkl_exec_inproc()
{
if tkl_is_file_os_exec "$1"; then
"$@"
else
. "$@"
fi
return $?
}
myscript.sh:
#!/bin/bash
echo 123
return 123
In Cygwin:
> tkl_exec_inproc /cygdrive/c/Windows/system32/cmd.exe /c 'echo 123'
123
> tkl_exec_inproc /cygdrive/c/Windows/system32/chcp.com 65001
Active code page: 65001
> tkl_exec_inproc ./myscript.sh
123
> echo $?
123
In Linux:
> tkl_exec_inproc /bin/bash -c 'echo 123'
123
> tkl_exec_inproc ./myscript.sh
123
> echo $?
123
You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:
$("#change_password").click(function() {
var target = $(this).attr("rel");
if($("#" + target).attr("disabled")) {
$("#" + target).attr("disabled", false);
} else {
$("#" + target).attr("disabled", true);
}
});
The "rel" attribute stores the id of the target input field.
I would say that if you know a bit of spanish to look at this page, where is properly explained.
However, a fast definition would be that div
is for dividing sections and span
is for applying some kind of style to an element within another block element like div
.
>>> s = bytes("s","utf-8")
>>> print(s)
b's'
>>> s = s.decode("utf-8")
>>> print(s)
s
Well if useful for you in case removing annoying 'b' character.If anyone got better idea please suggest me or feel free to edit me anytime in here.I'm just newbie
That worked for me in python3:
import urllib.request
htmlfile = urllib.request.urlopen("http://google.com")
htmltext = htmlfile.read()
print(htmltext)
You can delete all unwanted characters from a string using its translate()
method with None
for the table
argument followed by a string containing the character(s) you want removed for its deletechars
argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string
module's translate()
function instead because the ability to pass None
as the table
argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate()
function will also work in 2.6+, so using it might be preferable.
I think you mean to put the rolling of the random a,b,c, etc within the loop:
a = None # initialise
while not (a in winning_numbers):
# keep rolling an a until you get one not in winning_numbers
a = random.randint(1,30)
winning_numbers.append(a)
Otherwise, a
will be generated just once, and if it is in winning_numbers
already, it won't be added. Since the generation of a
is outside the while
(in your code), if a
is already in winning_numbers
then too bad, it won't be re-rolled, and you'll have one less winning number.
That could be what causes your error in if guess[i] == winning_numbers[i]
. (Your winning_numbers
isn't always of length 5).
If you have headers in the markdown files, you can directly link them in the file.
Markdown Header -
## The Header
this will generate an implicit id #the-header
(replace internal spaces with hyphens and make lowercase).
To navigate to this id, you can create the link like this:
[Link to Header](#the-header)
This is equivalent to:
<a href="#the-header">Link to Header</a>
Please note the reference's name is a lower-case #header
.
Though they operate the same way, however, the mouseenter
event only triggers when the mouse pointer enters the selected element. The mouseover
event is triggered if a mouse pointer enters any child elements as well.
Correct answer is simply:
SELECT a.group_id
FROM a
LEFT JOIN b ON a.group_id=b.group_id and b.user_id = 4
where b.user_id is null
and a.keyword like '%keyword%'
Here we are checking user_id = 4
(your user id from the session). Since we have it in the join criteria, it will return null values for any row in table b that does not match the criteria - ie, any group that that user_id is NOT in.
From there, all we need to do is filter for the null values, and we have all the groups that your user is not in.
Let say you have 2 columns named first_name and last_name in your users table and you want to retrieve full name. you can achieve with the following code :
class User extends Eloquent {
public function getFullNameAttribute()
{
return $this->first_name.' '.$this->last_name;
}
}
now you can get full name as:
$user = User::find(1);
$user->full_name;
It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.
I think you have an issue with your server certificate, is not a valid certificate (I think this is what "handshake_failure" means in this case):
Import your server certificate into your trustcacerts keystore on client's JRE. This is easily done with keytool:
keytool
-import
-alias <provide_an_alias>
-file <certificate_file>
-keystore <your_path_to_jre>/lib/security/cacerts
UPDATED
I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/
Also, I've changed two ^=
to *=
. See http://api.jquery.com/category/selectors/
And note the :checked
selector. See http://api.jquery.com/checked-selector/
function createcodes() {
//run through each row
$('.authors-list tr').each(function (i, row) {
// reference all the stuff you need first
var $row = $(row),
$family = $row.find('input[name*="family"]'),
$grade = $row.find('input[name*="grade"]'),
$checkedBoxes = $row.find('input:checked');
$checkedBoxes.each(function (i, checkbox) {
// assuming you layout the elements this way,
// we'll take advantage of .next()
var $checkbox = $(checkbox),
$line = $checkbox.next(),
$size = $line.next();
$line.val(
$family.val() + ' ' + $size.val() + ', ' + $grade.val()
);
});
});
}
The following code should work. It takes every filename in the current directory, if the filename contains the pattern CHEESE_CHEESE_
then it is renamed. If not nothing is done to the filename.
import os
for fileName in os.listdir("."):
os.rename(fileName, fileName.replace("CHEESE_CHEESE_", "CHEESE_"))
Print only selected element on codepen
HTML:
<div class="print">
<p>Print 1</p>
<a href="#" class="js-print-link">Click Me To Print</a>
</div>
<div class="print">
<p>Print 2</p>
<a href="#" class="js-print-link">Click Me To Print</a>
</div>
JQuery:
$('.js-print-link').on('click', function() {
var printBlock = $(this).parents('.print').siblings('.print');
printBlock.hide();
window.print();
printBlock.show();
});
You could definitely append data into an existing table. (But it is actually not an append at the HDFS level). It's just that whenever you do a LOAD or INSERT operation on an existing Hive table without OVERWRITE
clause the new data will be put without replacing the old data. A new file will be created for this newly inserted data inside the directory corresponding to that table. For example :
I have a file named demo.txt which has 2 lines :
ABC
XYZ
Create a table and load this file into it
hive> create table demo(foo string);
hive> load data inpath '/demo.txt' into table demo;
Now,if I do a SELECT on this table it'll give me :
hive> select * from demo;
OK
ABC
XYZ
Suppose, I have one more file named demo2.txt which has :
PQR
And I do a LOAD again on this table without using overwrite,
hive> load data inpath '/demo2.txt' into table demo;
Now, if I do a SELECT now, it'll give me,
hive> select * from demo;
OK
ABC
XYZ
PQR
HTH
Took a while to figure this one out. Seems most of us missed the obvious error…the last “-” is not escaped.
Adding the . and | as I’ve seen other suggest may work for you, but the regex was supposed to be:
if ( ! preg_match("/^[a-z0-9:_\/\-\.|]+$/i", $str))
Python’s wonderful standard library to the rescue…
import codecs
reader = codecs.getreader("utf-8")
obj = json.load(reader(response))
Works with both py2 and py3.
I extends the SimpleJpaRepository:
public class ExtendedRepositoryImpl<T extends EntityBean> extends SimpleJpaRepository<T, Long>
implements ExtendedRepository<T> {
private final JpaEntityInformation<T, ?> entityInformation;
private final EntityManager em;
public ExtendedRepositoryImpl(final JpaEntityInformation<T, ?> entityInformation,
final EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityInformation = entityInformation;
this.em = entityManager;
}
}
and adds this class to @EnableJpaRepositoryries repositoryBaseClass.
If you have a class file at build/com/foo/Hello.class
, you can check what java version it is compiled at using the command:
javap -v build/com/foo/Hello.class | grep "major"
Example usage:
$ javap -v build/classes/java/main/org/aguibert/liberty/Book.class | grep major
major version: 57
According to the table in the OP, major version 57 means the class file was compiled to JDK 13 bytecode level
Is there a way to remove all previous click events that have been assigned to a button?
$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});
In jsp you can do it like this:
<%
boolean checkboxDisabled = true; //do your logic here
String checkboxState = checkboxDisabled ? "disabled" : "";
%>
<input type="checkbox" <%=checkboxState%>>
You can try to change your Styles, Themes, or using android:indeterminateTint="@color/yourColor" anywhere you want, but there's just one way o doing that will work on any Android SKD version:
If you progress bar is not indeterminate, please use:
progressBar.getProgressDrawable().setColorFilter(ContextCompat.getColor(context, R.color.yourColor), PorterDuff.Mode.SRC_IN );
If you progress bar is indeterminate, please use:
progressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), R.color.yourColor), PorterDuff.Mode.SRC_IN );
It's sad that Android is such a mess!
Just for completeness here's the solution involving my StreamEx library:
String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
EntryStream.of(names)
.filterKeyValue((idx, str) -> str.length() <= idx+1)
.values().toList();
Here we create an EntryStream<Integer, String>
which extends Stream<Entry<Integer, String>>
and adds some specific operations like filterKeyValue
or values
. Also toList()
shortcut is used.
I think you maybe need a service to store file upload and get that file. Check more detail from here
1) Create a Storage Sevice
@Service
public class StorageService {
Logger log = LoggerFactory.getLogger(this.getClass().getName());
private final Path rootLocation = Paths.get("upload-dir");
public void store(MultipartFile file) {
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (Exception e) {
throw new RuntimeException("FAIL!");
}
}
public Resource loadFile(String filename) {
try {
Path file = rootLocation.resolve(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("FAIL!");
}
} catch (MalformedURLException e) {
throw new RuntimeException("FAIL!");
}
}
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
public void init() {
try {
Files.createDirectory(rootLocation);
} catch (IOException e) {
throw new RuntimeException("Could not initialize storage!");
}
}
}
2) Create Rest Controller to upload and get file
@Controller
public class UploadController {
@Autowired
StorageService storageService;
List<String> files = new ArrayList<String>();
@PostMapping("/post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
String message = "";
try {
storageService.store(file);
files.add(file.getOriginalFilename());
message = "You successfully uploaded " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.OK).body(message);
} catch (Exception e) {
message = "FAIL to upload " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
}
}
@GetMapping("/getallfiles")
public ResponseEntity<List<String>> getListFiles(Model model) {
List<String> fileNames = files
.stream().map(fileName -> MvcUriComponentsBuilder
.fromMethodName(UploadController.class, "getFile", fileName).build().toString())
.collect(Collectors.toList());
return ResponseEntity.ok().body(fileNames);
}
@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
Resource file = storageService.loadFile(filename);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
}
A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.
A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.
"A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered."
Not so. The purpose of a destructor is to allow the item that registered the listeners to unregister them. Once an object has no other references to it, it will be garbage collected.
For instance, in AngularJS, when a controller is destroyed, it can listen for a destroy event and respond to it. This isn't the same as having a destructor automatically called, but it's close, and gives us the opportunity to remove listeners that were set when the controller was initialized.
// Set event listeners, hanging onto the returned listener removal functions
function initialize() {
$scope.listenerCleanup = [];
$scope.listenerCleanup.push( $scope.$on( EVENTS.DESTROY, instance.onDestroy) );
$scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.SUCCESS, instance.onCreateUserResponse ) );
$scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.FAILURE, instance.onCreateUserResponse ) );
}
// Remove event listeners when the controller is destroyed
function onDestroy(){
$scope.listenerCleanup.forEach( remove => remove() );
}
def dupe(str1):
s=set(str1)
return "".join(s)
str1='geeksforgeeks'
a=dupe(str1)
print(a)
works well if order is not important.
Your code was compiled with Java Version 1.8 while it is being executed with Java Version 1.7 or below.
In your case it seems that two different Java installations are used, the newer to compile and the older to execute your code.
Try recompiling your code with Java 1.7 or upgrade your Java Plugin.
If you are doing form validation such as
type="submit" onsubmit="return validateForm(this)"
validateForm = function(form) {
if ($('input#company').val() === "" || $('input#company').val() === "Company") {
$('input#company').val("Company").css('color','red'); finalReturn = false;
$('input#company').on('mouseover',(function() {
$('input#company').val("").css('color','black');
$('input#company').off('mouseover');
finalReturn = true;
}));
}
return finalReturn;
}
Double check you are returning true. This seems simple but I had
var finalReturn = false;
When the form was correct it was not being corrected by validateForm and so not being submitted as finalReturn was still initialized to false instead of true. By the way, above code works nicely with address, city, state and so on.
While indenting your code in the function (which is ok), you did also indent the lines of the raw message string. But leading white space implies folding (concatenation) of the header lines, as described in sections 2.2.3 and 3.2.3 of RFC 2822 - Internet Message Format:
Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding".
In the function form of your sendmail
call, all lines are starting with white space and so are "unfolded" (concatenated) and you are trying to send
From: [email protected] To: [email protected] Subject: Hello! This message was sent with Python's smtplib.
Other than our mind suggests, smtplib
will not understand the To:
and Subject:
headers any longer, because these names are only recognized at the beginning of a line. Instead smtplib
will assume a very long sender email address:
[email protected] To: [email protected] Subject: Hello! This message was sent with Python's smtplib.
This won't work and so comes your Exception.
The solution is simple: Just preserve the message
string as it was before. This can be done by a function (as Zeeshan suggested) or right away in the source code:
import smtplib
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
"""this is some test documentation in the function"""
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
Now the unfolding does not occur and you send
From: [email protected]
To: [email protected]
Subject: Hello!
This message was sent with Python's smtplib.
which is what works and what was done by your old code.
Note that I was also preserving the empty line between headers and body to accommodate section 3.5 of the RFC (which is required) and put the include outside the function according to the Python style guide PEP-0008 (which is optional).
I use to throw an exception in the base class.
protected abstractMethod() {
throw new Error("abstractMethod not implemented");
}
Then you have to implement in the sub-class. The cons is that there is no build error, but run-time. The pros is that you can call this method from the super class, assuming that it will work :)
HTH!
Milton
Often, I like changing current directories while editing - so I have to specify paths less.
cd %:h
find /dir -type f -follow -print
-type f
means it will display real files (not symlinks)
-follow
means it will follow your directory symlinks
-print
will cause it to display the filenames.
If you want a ls type display, you can do the following
find /dir -type f -follow -print|xargs ls -l
Using float does not work.
DECLARE @t1 datetime, @t2 datetime
SELECT @t1 = '19000101 23:55:00', @t2 = '20001102 23:55:00'
SELECT CAST(@t1 as float) - floor(CAST(@t1 as float)), CAST(@t2 as float) - floor(CAST(@t2 as float))
You'll see that the values are not the same (SQL Server 2005). I wanted to use this method to check for times around midnight (the full method has more detail) in which I was comparing the current time for being between 23:55:00 and 00:05:00.
I realize this is an old question, but I found that none of these were really what I was looking for exactly. It seems to be caused by trying to close the modal before it's finished showing.
My solution was based on @schoonie23's answer but I had to change a few things.
First, I declared a global variable at the top of my script:
<script>
var closeModal = false;
...Other Code...
Then in my modal code:
$('#myModal').on('show.bs.modal', function (event) {
...Some Code...
if (someReasonToHideModal) {
closeModal = true;
return;
}
...Other Code...
Then this: (Note the name 'shown.bs.modal' indicating that the modal has shown completely as opposed to 'show' that triggers when the show event is called. (I originally tried just 'shown' but it did not work.)
$('#myModal').on('shown.bs.modal', function (event) {
if (closeEditModal) {
$('#myModal').modal('hide');
closeModal = false;
}
});
Hope this saves someone the extra research some day. I spent a bit looking for a solution before I came up with this.
You could just use the bound ng-model
(answers[item.questID]
) value itself in your ng-change method to detect if it has been checked or not.
Example:-
<input type="checkbox" ng-model="answers[item.questID]"
ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->
and
$scope.stateChanged = function (qId) {
if($scope.answers[qId]){ //If it is checked
alert('test');
}
}
Seekbar called onProgressChanged method when we initialize first time. We can skip by using below code We need to check boolean it return false when initialize automatically
volumeManager.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(b){
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
This should do the trick:
...
select: function(event, ui){
ui.tab.attr('class');
} ,
...
For more info about the ui.tab see http://jqueryui.com/demos/tabs/#Events
I tried @ScottK's approach, first as a side feature of my functional UDF, then as a standalone _Help suffix version when I ran into trouble (see below). In hindsight, the latter approach is better anyway--more obvious to a user attentive enough to see a tool tip, and it doesn't clutter up the functional code.
I figured if an inattentive user just typed the function name and closed the parentheses while he thought it over, help would appear and he would be on his way. But dumping a bunch of text into a single cell that I cannot format didn't seem like a good idea. Instead, When the function is entered in a cell with no arguments i.e.
= interpolateLinear()
or
= interpolateLinear_Help()
a msgBox opens with the help text. A msgBox is limited to ~1000 characters, maybe it's 1024. But that's enough (barely 8^/) for my overly tricked out interpolation function. If it's not, you can always open a user form and go to town.
The first time the message box opened, it looked like success. But there are a couple of problems. First of course, the user has to know to enter the function with no arguments (+1 for the _Help suffix UDF).
The big problem is, the msgBox reopens several times in succession, spontaneously while working in unrelated parts of the workbook. Needless to say, it's very annoying. Sometimes it goes on until I get a circular reference warning. Go figure. If a UDF could change the cell formula, I would have done that to shut it up.
I don't know why Excel feels the need recalculate the formula over and over; neither the _Help standalone, nor the full up version (in help mode) has precedents or dependents. There's not an application.volatile statement anywhere. Of course the function returns a value to the calling cell. Maybe that triggers the recalc? But that's what UDFs do. I don't think you can not return a value.
Since you can't modify a worksheet formula from a UDF, I tried to return a specific string --a value --to the calling cell (the only one you can change the value of from a UDF), figuring I would inspect the cell value using application.caller on the next cycle, spot my string, and know not to re-display the help message. Seemed like a good idea at the time--didn't work. Maybe I did something stupid in my sleep-deprived state. I still like the idea. I'll update this when (if) I fix the problem. My quick fix was to add a line on the help box: "Seek help only in an emergency. Delete the offending formula to end the misery.
In the meantime, I tried the Application.MacroOptions approach. Pretty easy, and it looks professional. Just one problem to work out. I'll post a separate answer on that approach later.
Here is a kind of snippet for you:
app.factory('Session', function($http) {
var Session = {
data: {},
saveSession: function() { /* save session data to db */ },
updateSession: function() {
/* load data from db */
$http.get('session.json').then(function(r) { return Session.data = r.data;});
}
};
Session.updateSession();
return Session;
});
Here is Plunker example how you can use that: http://plnkr.co/edit/Fg3uF4ukl5p88Z0AeQqU?p=preview
GETDATE()
didn't work for me using mySQL 8
ERROR 1305 (42000): FUNCTION mydatabase.GETDATE does not exist
but this does:
DELETE FROM table_name WHERE date_column < CURRENT_DATE - 30;
As of June 14th 2013 (HTML5), there is a significant difference
Browser : Chrome 27.X.X
References: document.location, window.location (MDN)
type: Object
The object when called by itself document.location
return its origin
+ pathname
properties concatenated.
To retrieve just the URL as a string, the read-only document.URL
property can be used.
ancestorOrigins: DOMStringList
assign: function () { [native code] }
hash: ""
host: "stackoverflow.com"
hostname: "stackoverflow.com"
href: "http://stackoverflow.com/questions/2652816/what-is-the-difference-between-document-location-href-and-document-location?rq=1"
origin: "http://stackoverflow.com"
pathname: "/questions/2652816/what-is-the-difference-between-document-location-href-and-document-location"
port: ""
protocol: "http:"
reload: function () { [native code] }
replace: function () { [native code] }
search: "?rq=1"
toString: function toString() { [native code] }
valueOf: function valueOf() { [native code] }
type: string
http://stackoverflow.com/questions/2652816/what-is-the-difference-between-document-location-href-and-document-location?rq=1
Assign after the EXEC
token:
DECLARE @returnValue INT
EXEC @returnValue = SP_One
in addition to what Kirk said I want to tell you that just "playing around" won't help you to learn asp.net, and there is a lot of free and very good tutorials .
take a look on the asp.net official site tutorials and on 4GuysFromRolla site
The solutions turned out to be very simple.
Open text edit
Write the command, save as .bat.
Double click the file created and the command automatically starts running in command-prompt.
I encountered the same error once. It was really funny. I had created a backup of the .java file with different filename but the same class name. And kept on trying to build it till I checked all the files in my folder.
And by the way for you fellow googlers for selecting multiple folders in the search input you separate your directories with a comma. Works both for exclude and include
Example: ./src/public/,src/components/
How about putting the checkbox
into the label
, making the label automatically "click sensitive" for the check box, and giving the checkbox a onchange
event?
<label ..... ><input type="checkbox" onchange="toggleCheckbox(this)" .....>
function toggleCheckbox(element)
{
element.checked = !element.checked;
}
This will additionally catch users using a keyboard to toggle the check box, something onclick
would not.
You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.
Ternary:
$something = isset($_GET['something']) ? $_GET['something'] : "failed";
If-else:
if (isset($_GET['something'])) {
$something = $_GET['something'];
} else {
$something = "failed";
}
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
Is the Postman Interceptor enabled? Toggling it will route all requests and responses through the Chrome browser.
Interceptor - https://www.getpostman.com/docs/capture Cookies documentation - http://blog.getpostman.com/index.php/2014/11/28/using-the-interceptor-to-read-and-write-cookies/
string constr = @"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(constr);
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd = new SqlCommand(" UPDATE Account SET name = Aleesha, CID = 24 Where name =Areeba and CID =11 )";
cmd.ExecuteNonQuery();
Couldn't find a working answer here; but on linux you can run "umount.nfs4 /volume -f" and it definitely unmounts it.
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
You can fake it like this:
-- with column headings
select column1, column2 from some_table;
-- without column headings
select column1 as '', column2 as '' from some_table;
Immutable :
When you do some operation on a object, it creates a new object hence state is not modifiable as in case of string.
Mutable
When you perform some operation on a object, object itself modified no new obect created as in case of StringBuilder
Call
perror("execl");
in case of error.
Sample:
if(read(fd, buf, 1)==-1) {
perror("read");
}
The manpages of errno(3)
and perror(3)
are interesting, too...
To expand on the accepted answer, I just wanted to provide another reason why real
? user
+ sys
.
Keep in mind that real
represents actual elapsed time, while user
and sys
values represent CPU execution time. As a result, on a multicore system, the user
and/or sys
time (as well as their sum) can actually exceed the real time. For example, on a Java app I'm running for class I get this set of values:
real 1m47.363s
user 2m41.318s
sys 0m4.013s
Something like this - for each line read into string variable a
:
>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456
Now you can do what is necessary with x
and y
as assigned, which are integers.
You were right to look at using a set, we just need to dig in a little deeper to get your method to work.
First, the example code:
test_1 = {"foo": "bar", "FOO": "BAR"}
test_2 = {"foo": "bar", "f00": "b@r"}
We can see right now that both dictionaries contain a similar key/value pair:
{"foo": "bar", ...}
Each dictionary also contains a completely different key value pair. But how do we detect the difference? Dictionaries don't support that. Instead, you'll want to use a set.
Here is how to turn each dictionary into a set we can use:
set_1 = set(test_1.items())
set_2 = set(test_2.items())
This returns a set containing a series of tuples. Each tuple represents one key/value pair from your dictionary.
Now, to find the difference between set_1 and set_2:
print set_1 - set_2
>>> {('FOO', 'BAR')}
Want a dictionary back? Easy, just:
dict(set_1 - set_2)
>>> {'FOO': 'BAR'}
The box model is something every web-developer should know about. working with percents for sizes and pixels for padding/margin just doesn't work. There always is a resolution at which it doesn't look good (e.g. giving a width of 90% and a padding/margin of 10px in a div with a width of under 100px).
Check this out (using micro.pravi's code): http://jsbin.com/umeduh/2
<div id="container">
<div class="left">
<div class="content">
left
</div>
</div>
<div class="right">
<div class="content">
right
<textarea>Check me out!</textarea>
</div>
</div>
</div>
The <div class="content">
are there so you can use padding and margin without screwing up the floats.
this is the most important part of the CSS:
textarea {
display: block;
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
Change the code where you load the partial view to:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable
After integrating Spring 4 with Hibernate 5 in my project and experiencing this problem, I found that I could prevent the error from appearing by changing the way of getting the session from sessionFactory.openSession()
to sessionFactory.getCurrentSession()
.
the proper way to work out this bug may be keep using the same session for the binding transaction.opensession will always create a new session which doesnt like the former one holding a transaction configed.using getCurrentSession and adding additional property <property name="current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</property>
works fine for me.
You have different choices. One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder. and you can give orders to this page in this way:
Old page: http://something.com/profile.php?id=a&abc=1
New page: http://something.com/profile/?id=a&abc=1
If you are not satisfied leave a comment for complicated methods.
adb shell
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
adb push <appname>.apk /system/app
adb reboot
The key checks for FAST REFRESH includes the following:
1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.
No 3 is easy to miss and worth highlighting here
I want to return odd numbers of an array
If i read that correctly, you want something like this?
List<Integer> getOddNumbers(int[] integers) {
List<Integer> oddNumbers = new ArrayList<Integer>();
for (int i : integers)
if (i % 2 != 0)
oddNumbers.add(i);
return oddNumbers;
}
Mixin for Less
.appearance (@value: none) {
-webkit-appearance: @value;
-moz-appearance: @value;
-ms-appearance: @value;
-o-appearance: @value;
appearance: @value;
}
Not sure if this can be an answer but as I see what others have said for someone it may look like you need two separate abstractions for both of these concepts so that one of them (Future
) is just a read-only view of the other (Promise
) ... but actually this is not needed.
For example take a look at how promises are defined in javascript:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
The focus is on the composability using the then
method like:
asyncOp1()
.then(function(op1Result){
// do something
return asyncOp2();
})
.then(function(op2Result){
// do something more
return asyncOp3();
})
.then(function(op3Result){
// do something even more
return syncOp4(op3Result);
})
...
.then(function(result){
console.log(result);
})
.catch(function(error){
console.log(error);
})
which makes asynchronous computation to look like synchronous:
try {
op1Result = syncOp1();
// do something
op1Result = syncOp2();
// do something more
op3Result = syncOp3();
// do something even more
syncOp4(op3Result);
...
console.log(result);
} catch(error) {
console.log(error);
}
which is pretty cool. (Not as cool as async-await but async-await just removes the boilerplate ....then(function(result) {.... from it).
And actually their abstraction is pretty good as the promise constructor
new Promise( function(resolve, reject) { /* do it */ } );
allows you to provide two callbacks which can be used to either complete the Promise
successfully or with an error. So that only the code that constructs the Promise
can complete it and the code that receives an already constructed Promise
object has the read-only view.
With inheritance the above can be achieved if resolve and reject are protected methods.
changing the project to use java 1.7: For this to work follow those steps :
Not working?
Still not working?
in your project's directory: edit .settings/org.eclipse.jdt.core.prefs > make sure your target level is applied
Good Luck!
Did you read clang
documentation ? You're probably looking for -emit-llvm
.
In the spring boot reference,it said:
When a class doesn’t include a package declaration it is considered to be in the “default package”. The use of the “default package” is generally discouraged, and should be avoided. It can cause particular problems for Spring Boot applications that use @ComponentScan, @EntityScan or @SpringBootApplication annotations, since every class from every jar, will be read.
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
In your cases. You must add scanBasePackages
in the @SpringBootApplication
annotation.just like@SpringBootApplication(scanBasePackages={"domain","contorller"..})
Reload the current page:
F5
or
CTRL + R
Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R
In the case you are asking about, this
represents the HTML DOM element.
So it would be the <a>
element that was clicked on.
change your query to like.
$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");
However, MySQL is deprecated. You should instead use MySQLi or PDO
Try doing it the other way around.
$('<link rel="stylesheet" href="css/style2.css" type="text/css" />').appendTo('head');
I would do it something along these lines:
class Foo{
...
};
int main(){
Foo* arrayOfFoo[100]; //[1]
arrayOfFoo[0] = new Foo; //[2]
}
[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.
[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.
The JDK path might change when you update JAVA. For Mac you should go to the following path to check the JAVA version installed.
/Library/Java/JavaVirtualMachines/
Next, say JDK version that you find is jdk1.8.0_151.jdk
, the path to home directory within it is the JDK home path.
In my case it was :
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
You can configure it by going to File -> Project Structure -> SDKs
.
Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm
Update on March 8, 2018 with Visual Studio Code 1.20.1 (mac)
It has been simplified quite a lot lately.
Very easy and straight forward now.
From the search box just search for "editor.action.transformTo", You will see the screen like:
Click the "plus" sign at the left of each item, it will prompt dialog for your to [press] you desired key-bindings, after it showing that on the screen, just hit [Enter] to save.
If you see there source code they check if process.env.NODE_ENV === 'development'
returns true
, and they automatically removes host URL and only return path.
For example, if you set like below
PUBLIC_URL=http://example.com/static/
They will remove http://example.com
and only return /static
.
However since you only set root URL like http://example.com
, they will just return an empty string since there no subpath in your URL string.
This only happens if you call react-scripts start
, and if you call react-scripts build
then isEnvDevelopment
will be false
, so it will just return http://example.com
as what you set in the .env
file.
Here is the source code of getPublicUrlOrPath.js.
/**
* Returns a URL or a path with slash at the end
* In production can be URL, abolute path, relative path
* In development always will be an absolute path
* In development can use `path` module functions for operations
*
* @param {boolean} isEnvDevelopment
* @param {(string|undefined)} homepage a valid url or pathname
* @param {(string|undefined)} envPublicUrl a valid url or pathname
* @returns {string}
*/
function getPublicUrlOrPath(isEnvDevelopment, homepage, envPublicUrl) {
const stubDomain = 'https://create-react-app.dev';
if (envPublicUrl) {
// ensure last slash exists
envPublicUrl = envPublicUrl.endsWith('/')
? envPublicUrl
: envPublicUrl + '/';
// validate if `envPublicUrl` is a URL or path like
// `stubDomain` is ignored if `envPublicUrl` contains a domain
const validPublicUrl = new URL(envPublicUrl, stubDomain);
return isEnvDevelopment
? envPublicUrl.startsWith('.')
? '/'
: validPublicUrl.pathname
: // Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
envPublicUrl;
}
if (homepage) {
// strip last slash if exists
homepage = homepage.endsWith('/') ? homepage : homepage + '/';
// validate if `homepage` is a URL or path like and use just pathname
const validHomepagePathname = new URL(homepage, stubDomain).pathname;
return isEnvDevelopment
? homepage.startsWith('.')
? '/'
: validHomepagePathname
: // Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
homepage.startsWith('.')
? homepage
: validHomepagePathname;
}
return '/';
}
This will do what you want. Fixed sides with 50px-width, and the content fills the remaining area.
<div style="width:100%;">
<div style="width: 50px; float: left;">Left Side</div>
<div style="width: 50px; float: right;">Right Side</div>
<div style="margin-left: 50px; margin-right: 50px;">Content Goes Here</div>
</div>
sudo apt install php-xml
will work but the thing is it will download the plugin for the latest PHP version.
If your PHP version is not the latest, then you can add version in it:
# PHP 7.1
sudo apt install php7.1-xml
# PHP 7.2:
sudo apt install php7.2-xml
# PHP 7.3
sudo apt install php7.3-xml
# PHP 7.4
sudo apt install php7.4-xml
# PHP 8
sudo apt install php-xml
Intent serviceIntent = new Intent(this,YourActivity.class);
startService(serviceIntent);
add service in manifist
<service android:enabled="true" android:name="YourActivity.class" />
for running service on oreo and greater devices use for ground service and show notification to user
or use geofencing service for location update in background reference http://stackoverflow.com/questions/tagged/google-play-services
I do it like Bradley Braithwaite suggests in his blog:
app
.factory('searchService', ['$q', '$http', function($q, $http) {
var service = {};
service.search = function search(query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http
.get('http://localhost/v1?=q' + query)
.success(function(data) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(data);
})
.error(function(reason) {
// The promise is rejected if there is an error with the HTTP call.
deferred.reject(reason);
});
// The promise is returned to the caller
return deferred.promise;
};
return service;
}])
.controller('SearchController', ['$scope', 'searchService', function($scope, searchService) {
// The search service returns a promise API
searchService
.search($scope.query)
.then(function(data) {
// This is set when the promise is resolved.
$scope.results = data;
})
.catch(function(reason) {
// This is set in the event of an error.
$scope.error = 'There has been an error: ' + reason;
});
}])
Key Points:
The resolve function links to the .then function in our controller i.e. all is well, so we can keep our promise and resolve it.
The reject function links to the .catch function in our controller i.e. something went wrong, so we can’t keep our promise and need to reject it.
It is quite stable and safe and if you have other conditions to reject the promise you can always filter your data in the success function and call deferred.reject(anotherReason)
with the reason of the rejection.
As Ryan Vice suggested in the comments, this may not be seen as useful unless you fiddle a bit with the response, so to speak.
Because success
and error
are deprecated since 1.4 maybe it is better to use the regular promise methods then
and catch
and transform the response within those methods and return the promise of that transformed response.
I am showing the same example with both approaches and a third in-between approach:
success
and error
approach (success
and error
return a promise of an HTTP response, so we need the help of $q
to return a promise of data):
function search(query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http.get('http://localhost/v1?=q' + query)
.success(function(data,status) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(data);
})
.error(function(reason,status) {
// The promise is rejected if there is an error with the HTTP call.
if(reason.error){
deferred.reject({text:reason.error, status:status});
}else{
//if we don't get any answers the proxy/api will probably be down
deferred.reject({text:'whatever', status:500});
}
});
// The promise is returned to the caller
return deferred.promise;
};
then
and catch
approach (this is a bit more difficult to test, because of the throw):
function search(query) {
var promise=$http.get('http://localhost/v1?=q' + query)
.then(function (response) {
// The promise is resolved once the HTTP call is successful.
return response.data;
},function(reason) {
// The promise is rejected if there is an error with the HTTP call.
if(reason.statusText){
throw reason;
}else{
//if we don't get any answers the proxy/api will probably be down
throw {statusText:'Call error', status:500};
}
});
return promise;
}
There is a halfway solution though (this way you can avoid the throw
and anyway you'll probably need to use $q
to mock the promise behavior in your tests):
function search(query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http.get('http://localhost/v1?=q' + query)
.then(function (response) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(response.data);
},function(reason) {
// The promise is rejected if there is an error with the HTTP call.
if(reason.statusText){
deferred.reject(reason);
}else{
//if we don't get any answers the proxy/api will probably be down
deferred.reject({statusText:'Call error', status:500});
}
});
// The promise is returned to the caller
return deferred.promise;
}
Any kind of comments or corrections are welcome.
All given answers are wrong. It is impossible to globalise a variable inside a function in a separate file.
I just had the same problem with an SBT project in IntelliJ 2016.2 after removing a globally installed IntelliJ and re-installing in my own home folder (Linux). No files or folders were shown in Project View anymore.
The Project Structure view wouldn't even open, and renaming the .idea
folder to .idea.bak
and re-importing the project didn't make any difference.
However, what fixed it for me was to reboot Linux. Afterwards it worked again, even with the original .idea
folder. Seems this "fix" is not only restricted to the Windows world.
"matt b" has it right, but to be specific, the "install" goal copies your built target to the local repository on your file system; useful for small changes across projects not currently meant for the full group.
The "deploy" goal uploads it to your shared repository for when your work is finished, and then can be shared by other people who require it for their project.
In your case, it seems that "install" is used to make the management of the deployment easier since CI's local repo is the shared repo. If CI was on another box, it would have to use the "deploy" goal.
it work in my case, oldSensor and newSnsor - oldView and newView:
private void replaceSensors(View oldSensor, View newSensor) {
ViewGroup parent = (ViewGroup) oldSensor.getParent();
if (parent == null) {
return;
}
int indexOldSensor = parent.indexOfChild(oldSensor);
int indexNewSensor = parent.indexOfChild(newSensor);
parent.removeView(oldSensor);
parent.addView(oldSensor, indexNewSensor);
parent.removeView(newSensor);
parent.addView(newSensor, indexOldSensor);
}
My conclusion is HTML doesn't allows NESTED SCRIPT tags. If you are using javascript for injecting HTML code that include script tags inside is not going to work because the javascript goes in a script tag too. You can test it with the next code and you will be that it's not going to work. The use case is you are calling a service with AJAX or similar, you are getting HTML and you want to inject it in the HTML DOM straight forward. If the injected HTML code has inside SCRIPT tags is not going to work.
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"></head><body></body><script>document.getElementsByTagName("body")[0].innerHTML = "<script>console.log('hi there')</script>\n<div>hello world</div>\n"</script></html>
Upgrading protobuf-gradle-plugin to version 0.8.10 solved my problem. Replace your existing protobuf with
classpath 'gradle.plugin.com.google.protobuf:protobuf-gradle-plugin:0.8.10'
Pretty late, but you can also do this by annotating a @BeforeStep method:
@BeforeStep
public void beforeStep(final StepExecution stepExecution) {
JobParameters parameters = stepExecution.getJobExecution().getJobParameters();
//use your parameters
}
The above answers are good, but in my case, 1st approach that converts the function to be a static didn't work. I was trying to convert exiting code to move into thread function but that code had lots to references to non-static class members already. The second solution of encapsulating into C++ object works, but has 3-level wrappers to run a thread.
I had an alternate solution that uses existing C++ construct - 'friend' function, and it worked perfect for my case. An example of how I used 'friend' (will use the above same example for names showing how it can be converted into a compact form using friend)
class MyThreadClass
{
public:
MyThreadClass() {/* empty */}
virtual ~MyThreadClass() {/* empty */}
bool Init()
{
return (pthread_create(&_thread, NULL, &ThreadEntryFunc, this) == 0);
}
/** Will not return until the internal thread has exited. */
void WaitForThreadToExit()
{
(void) pthread_join(_thread, NULL);
}
private:
//our friend function that runs the thread task
friend void* ThreadEntryFunc(void *);
pthread_t _thread;
};
//friend is defined outside of class and without any qualifiers
void* ThreadEntryFunc(void *obj_param) {
MyThreadClass *thr = ((MyThreadClass *)obj_param);
//access all the members using thr->
return NULL;
}
Ofcourse, we can use boost::thread and avoid all these, but I was trying to modify the C++ code to not use boost (the code was linking against boost just for this purpose)
The case sensitivity is defined in the columns / tables / database collation settings. You can do the query under a specific collation in the following way:
SELECT *
FROM trees
WHERE trees.`title` LIKE '%elm%' COLLATE utf8_general_ci
for instance.
(Replace utf8_general_ci
with whatever collation you find useful). The _ci
stands for case insensitive.
I suggest this one:
if [ "$a" = "$b" ]
Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the '=' sign.
Also, be careful of your script header. It's not the same thing whether you use
#!/bin/bash
or
#!/bin/sh
Dont define varibale in header file , do declaration in header file(good practice ) .. in your case it is working because multiple weak symbols .. Read about weak and strong symbol ....link :http://csapp.cs.cmu.edu/public/ch7-preview.pdf
This type of code create problem while porting.
When I had to do some matrix arithmetic I defined a new class to help. Within such a class you can define magic methods like __add__
, or, in your use-case, __matmul__
, allowing you to define x = a @ b
or a @= b
rather than matrixMult(a,b)
. __matmul__
was added in Python 3.5 per PEP 465.
I have included some code which implements this below (I excluded the prohibitively long __init__
method, which essentially creates a two-dimensional list self.mat
and a tuple self.order
according to what is passed to it)
class Matrix:
def __matmul__(self, multiplier):
if self.order[1] != multiplier.order[0]:
raise ValueError("The multiplier was non-conformable under multiplication.")
return [[sum(a*b for a,b in zip(srow,mcol)) for mcol in zip(*multiplier.mat)] for srow in self.mat]
def __imatmul__(self, multiplier):
self.mat = self @ multiplier
return self.mat
def __rmatmul__(self, multiplicand):
if multiplicand.order[1] != self.order[0]:
raise ValueError("The multiplier was non-conformable under multiplication.")
return [[sum(a*b for a,b in zip(mrow,scol)) for scol in zip(*self.mat)] for mrow in multiplicand.mat]
Note:
__rmatmul__
is used if b @ a
is called and b
does not implement __matmul__
(e.g. if I wanted to implement premultiplying by a 2D list)__imatmul__
is required for a @= b
to work correctly;Different ways to create a Rounded button are as follows
FlatButton Button with Shape RoundedRectangleBorder
FlatButton(
minWidth: 260,
height: 60,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.red)),
color: Colors.white,
textColor: Colors.red,
padding: EdgeInsets.all(8.0),
onPressed: () {},
child: Text(
"Add to Cart".toUpperCase(),
style: TextStyle(
fontSize: 14.0,
),
),
),
RaisedButton Button with Shape RoundedRectangleBorder
RaisedButton(
padding:
EdgeInsets.only(left: 100, right: 100, top: 20, bottom: 20),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(28.0),
side: BorderSide(color: Colors.red)),
onPressed: () {},
color: Colors.red,
textColor: Colors.white,
child: Text("Buy now".toUpperCase(),
style: TextStyle(fontSize: 14)),
),
RaisedButton Button with Shape StadiumBorder()
RaisedButton(
padding:
EdgeInsets.only(left: 100, right: 100, top: 20, bottom: 20),
shape: StadiumBorder(),
onPressed: () {},
child: Text("Button"),
)
RaisedButton Button with ClipRRect
ClipRRect(
borderRadius: BorderRadius.circular(40),
child: RaisedButton(
padding: EdgeInsets.only(
left: 100, right: 100, top: 20, bottom: 20),
onPressed: () {},
child: Text("Button"),
),
)
RaisedButton Button with ClipOval
ClipOval(
child: RaisedButton(
onPressed: () {},
child: Text("Button"),
),
),
RaisedButton Button with ButtonTheme
ButtonTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: RaisedButton(
onPressed: () {},
child: Text("Button"),
),
)
practical demonstration of a round button can be found in below dartpad link
I found a way that works just fine.
var Update = context.UpdateTables.Find(id);
Update.Title = title;
// Mark as Changed
context.Entry(Update).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
Under compiler.xml file you will find :
<bytecodeTargetLevel>
<module name="your_project_name_main" target="1.8" />
<module name="your_project_name_test" target="1.8" />
</bytecodeTargetLevel>
and you can change the target value from your old to the new for me i needed to change it from 1.5 to 1.8
I think your first line would actually work but I think you need four quotation marks for a string containing a single one (in VB at least):
s = s.Replace("""", "")
for C# you'd have to escape the quotation mark using a backslash:
s = s.Replace("\"", "");
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>
An alternative and perhaps more transparent way of evaluating an empty environment variable is to use...
if [ "x$ENV_VARIABLE" != "x" ] ; then
echo 'ENV_VARIABLE contains something'
fi
IE6 Internet Explorer 6
Percent only works for the width of an element, but height:100%;
does not work without the correct code.
CSS
html, body { height:100%; }
Then using a percentage works properly, and dynamically updates on window resize.
<img src="image.jpg" style="height:80%;">
You do not need a width attribute, the width scales proportionately as the browser window size is changed.
And this little gem, is in case the image is scaled up, it will not look (overly) blocky (it interpolates).
img { -ms-interpolation-mode: bicubic; }
Props go to this source: Ultimate IE6 Cheatsheet: How To Fix 25+ Internet Explorer 6 Bugs
You can't... Maybe if you posted a picture of the desired effect there's another way to achieve it.
For example, you can wrap the entire table in a DIV and set the padding to the div.
Another option is use the Hibernate email validator, using the annotation @Email
or using the validator class programatically, like:
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
class Validator {
// code
private boolean isValidEmail(String email) {
EmailValidator emailValidator = new EmailValidator();
return emailValidator.isValid(email, null);
}
}
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent
and background-image: none
) without explicitly specifying any value such as transparent
or none
, you can do so by writing:
background: initial;
Ways to hide Navigation Bar in Swift:
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.navigationController?.navigationBar.isHidden = true
self.navigationController?.isNavigationBarHidden = true
First, you don't need to do all that. In particular, the strcpy
is redundant - you don't need to copy a string just to printf
it. Your message
can be defined with that string in place.
Second, you've not allowed enough space for that "Hello, World!" string (message
needs to be at least 14 characters, allowing the extra one for the null terminator).
On the why, though, it's history. In assembler, there are no strings, only bytes, words etc. Pascal had strings, but there were problems with static typing because of that - string[20]
was a different type that string[40]
. There were languages even in the early days that avoided this issue, but that caused indirection and dynamic allocation overheads which were much more of an efficiency problem back then.
C simply chose to avoid the overheads and stay very low level. Strings are character arrays. Arrays are very closely related to pointers that point to their first item. When array types "decay" to pointer types, the buffer-size information is lost from the static type, so you don't get the old Pascal string issues.
In C++, there's the std::string
class which avoids a lot of these issues - and has the dynamic allocation overheads, but these days we usually don't care about that. And in any case, std::string
is a library class - there's C-style character-array handling underneath.
Since you've already stashed your changes, all you need is this one-liner:
git stash branch <branchname> [<stash>]
From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):
Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.
This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.