Yet still another way to get this symptom: I was rsync'ing from a remote machine over ssh to a Linux box with an NTFS-3G (FUSE) filesystem. Originally the filesystem was mounted at boot time and thus owned by root, and I was getting this error message when I did an rsync push from the remote machine. Then, as the user to which the rsync is pushed, I did:
$ sudo umount /shared
$ mount /shared
and the error messages went away.
I found a pretty simple way to do this. Use a button to open it using an on click
listener to start the function openc()
, like this:
String fileloc;
private void openc()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try
{
f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
fileloc = Uri.fromFile(f)+"";
Log.d("texts", "openc: "+fileloc);
startActivityForResult(takePictureIntent, 3);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK) {
Log.d("texts", "onActivityResult: "+fileloc);
// fileloc is the uri of the file so do whatever with it
}
}
You can do whatever you want with the uri
location string. For instance, I send it to an image cropper to crop the image.
You can also put the fieldset inside a table, like so:
<table>
<tr>
<td>
<fieldset>
.......
</fieldset>
</td>
</tr>
</table>
Before proceeding:
Install a proper mergetool. On Linux, I strongly suggest you to use meld:
sudo apt-get install meld
Configure your mergetool:
git config --global merge.tool meld
Then, iterate in the following way:
git cherry-pick ....
git mergetool
git cherry-pick --continue
Using WifiManager
you can do:
WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}
The method getNeworkId returns -1 only when it's not connected to a network;
There should be a way to make a .NET EXE/DLL AnyCPU, and any unmanaged DLLs it depends on compiled both with x86 and x64, both bundled perhaps with different filenames and then the .NET module dynamically loading the correct one based on its runtime processor architecture. That would make AnyCPU powerful. If the C++ DLL only supports x86 or x64 then AnyCPU is of course pointless. But the bundling both idea I have yet to see implemented as the configuration manager does not even provide a means to build the same project twice with a different configuration/platform for multiple bundling allowing AnyCPU or even other concepts like any configuration to be possible.
You Could try the other format for the case statement
CASE WHEN Product.type_id = 10
THEN
(
Select Statement
)
ELSE
(
Other select statement
)
END
FROM Product
WHERE Product.product_id = $pid
See http://msdn.microsoft.com/en-us/library/ms181765.aspx for more information.
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
The biggest advantage of NoSQL over RDBMS is Scalability.
NoSQL databases can easily scale-out to many nodes, but for RDBMS it is very hard.
Scalability not only gives you more storage space but also much higher performance since many hosts work at the same time.
Export the .ipa by checking the "with manifest plist checkbox" and provide the links requested.
Upload the .ipa file and .plist file to the same location of the server (which you provided when exporting .ipa/ which mentioned in the .plist file).
Create the Download Link as given below. url should link to your .plist file location.
itms-services://?action=download-manifest&url=https://yourdomainname.com/app.plist
Copy this link and paste it in safari browser in your iphone. It will ask to install :D
Create a html button using this full url
If using integers as targets, makes sure they aren't symmetrical at 0.
I.e., don't use classes -1, 0, 1. Use instead 0, 1, 2.
In angularjs you can create the UI part, service, Directives and all the part of angularjs which represent the UI. It is nice technology to work on.
As any one who new into this technology and want to authenticate the "User" then i suggest to do it with the power of c# web api. for that you can use the OAuth specification which will help you to built a strong security mechanism to authenticate the user. once you build the WebApi with OAuth you need to call that api for token:
var _login = function (loginData) {_x000D_
_x000D_
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
_x000D_
var deferred = $q.defer();_x000D_
_x000D_
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
_x000D_
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
_x000D_
_authentication.isAuth = true;_x000D_
_authentication.userName = loginData.userName;_x000D_
_x000D_
deferred.resolve(response);_x000D_
_x000D_
}).error(function (err, status) {_x000D_
_logOut();_x000D_
deferred.reject(err);_x000D_
});_x000D_
_x000D_
return deferred.promise;_x000D_
_x000D_
};_x000D_
_x000D_
and once you get the token then you request the resources from angularjs with the help of Token and access the resource which kept secure in web Api with OAuth specification.
Please have a look into the below article for more help:-
In Clean Code, Robert C. Martin devoted four pages to the subject. Here's the gist:
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification -- and then shouldn't be used anyway.
You have to use GROUP BY
so you will have multiple records returned,
SELECT COUNT(*) TotalCount,
b.category_id,
b.category_name
FROM table1 a
INNER JOIN table2 b
ON a.category_id = b.category_id
WHERE a.colour <> 'red'
GROUP BY b.category_id, b.category_name
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
Go to "Window -> Preferences -> General -> C/C++ -> Code analysis" and disable "Syntax and Semantics Errors -> Abstract class cannot be instantiated"
I didn't need anything robust like storing the string in attributes. I just needed to turn something like MyEnum.BillEveryWeek
into "bill every week" or MyEnum.UseLegacySystem
into "use legacy system"--basically split the enum by its camel-casing into individiual lower-case words.
public static string UnCamelCase(this Enum input, string delimiter = " ", bool preserveCasing = false)
{
var characters = input.ToString().Select((x, i) =>
{
if (i > 0 && char.IsUpper(x))
{
return delimiter + x.ToString(CultureInfo.InvariantCulture);
}
return x.ToString(CultureInfo.InvariantCulture);
});
var result = preserveCasing
? string.Concat(characters)
: string.Concat(characters).ToLower();
var lastComma = result.LastIndexOf(", ", StringComparison.Ordinal);
if (lastComma > -1)
{
result = result.Remove(lastComma, 2).Insert(lastComma, " and ");
}
return result;
}
MyEnum.UseLegacySystem.UnCamelCase()
outputs "use legacy system"
If you have multiple flags set, it will turn that into plain english (comma-delimited except an "and" in place of the last comma).
var myCustomerBehaviour = MyEnum.BillEveryWeek | MyEnum.UseLegacySystem | MyEnum.ChargeTaxes;
Console.WriteLine(myCustomerBehaviour.UnCamelCase());
//outputs "bill every week, use legacy system and charge taxes"
Amazings WPF Controls includes the Jetpack theme for WPF.
Thought I would chip in here with when I have found ON
to be more useful than USING
. It is when OUTER
joins are introduced into queries.
ON
benefits from allowing the results set of the table that a query is OUTER
joining onto to be restricted while maintaining the OUTER
join. Attempting to restrict the results set through specifying a WHERE
clause will, effectively, change the OUTER
join into an INNER
join.
Granted this may be a relative corner case. Worth putting out there though.....
For example:
CREATE TABLE country (
countryId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
country varchar(50) not null,
UNIQUE KEY countryUIdx1 (country)
) ENGINE=InnoDB;
insert into country(country) values ("France");
insert into country(country) values ("China");
insert into country(country) values ("USA");
insert into country(country) values ("Italy");
insert into country(country) values ("UK");
insert into country(country) values ("Monaco");
CREATE TABLE city (
cityId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
countryId int(10) unsigned not null,
city varchar(50) not null,
hasAirport boolean not null default true,
UNIQUE KEY cityUIdx1 (countryId,city),
CONSTRAINT city_country_fk1 FOREIGN KEY (countryId) REFERENCES country (countryId)
) ENGINE=InnoDB;
insert into city (countryId,city,hasAirport) values (1,"Paris",true);
insert into city (countryId,city,hasAirport) values (2,"Bejing",true);
insert into city (countryId,city,hasAirport) values (3,"New York",true);
insert into city (countryId,city,hasAirport) values (4,"Napoli",true);
insert into city (countryId,city,hasAirport) values (5,"Manchester",true);
insert into city (countryId,city,hasAirport) values (5,"Birmingham",false);
insert into city (countryId,city,hasAirport) values (3,"Cincinatti",false);
insert into city (countryId,city,hasAirport) values (6,"Monaco",false);
-- Gah. Left outer join is now effectively an inner join
-- because of the where predicate
select *
from country left join city using (countryId)
where hasAirport
;
-- Hooray! I can see Monaco again thanks to
-- moving my predicate into the ON
select *
from country co left join city ci on (co.countryId=ci.countryId and ci.hasAirport)
;
I also faced that problem and there are two ways to solve this in laravel.
first one is you can set the default value as null. I will show you an example:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('gender');
$table->string('slug');
$table->string('pic')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
as the above example, you can set nullable()
for that feature. then when you are inserting data MySQL set the default value as null.
second one is in your model set your input field in protected $fillable
field. as example:
protected $fillable = [
'name', 'email', 'password', 'slug', 'gender','pic'
];
I think the second one is fine than the first one and also you can set nullable feature as well as fillable in the same time without a problem.
Repartition: Shuffle the data into a NEW number of partitions.
Eg. Initial data frame is partitioned in 200 partitions.
df.repartition(500)
: Data will be shuffled from 200 partitions to new 500 partitions.
Coalesce: Shuffle the data into existing number of partitions.
df.coalesce(5)
: Data will be shuffled from remaining 195 partitions to 5 existing partitions.
This should do it:
expect($('[ng-show=saving].icon-spin').isDisplayed()).toBe(true);
Remember protractor's $
isn't jQuery and :visible
is not yet a part of available CSS selectors + pseudo-selectors
More info at https://stackoverflow.com/a/13388700/511069
If you want to capture click on everything then do
$("*").click(function(){
//code here
}
I use this for selector: http://api.jquery.com/all-selector/
This is used for handling clicks: http://api.jquery.com/click/
And then use http://api.jquery.com/event.preventDefault/
To stop normal clicking actions.
Another way you can do in Jquery.
<video id="videoclip" controls="controls" poster="" title="Video title">
<source id="mp4video" src="video/bigbunny.mp4" type="video/mp4" />
</video>
<div class="list-item">
<ul>
<li class="item" data-video = "video/bigbunny.mp4"><a href="javascript:void(0)">Big Bunny.</a></li>
</ul>
</div>
$(".list-item").find(".item").on("click", function() {
let videoData = $(this).data("video");
let videoSource = $("#videoclip").find("#mp4video");
videoSource.attr("src", videoData);
let autoplayVideo = $("#videoclip").get(0);
autoplayVideo.load();
autoplayVideo.play();
});
In recent version, The following works fine:
$('.selector').datetimepicker({
maxDate: new Date()
});
maxDate
accepts a Date object as parameter.
The following found in documentation:
Multiple types supported:
Date: A date object containing the minimum date.
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.
String: A string in the format defined by the dateFormat option, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.
$.fn.attr(attributeName) returns the attribute value as string, or undefined
when the attribute is not present.
Since ""
, and undefined
are both falsy (evaluates to false when coerced to boolean) values in JavaScript, in this case I would write the check as below:
if (wlocation) { ... }
I want to understand the lock each transaction isolation takes on the table
For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT
statement to read data. C reads and updates data. All these process work on the same table T.
WHERE aField > 10 AND aField < 20
, A inserts data where aField
value is between 10 and 20, then B reads the data again and get a different result.I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also
Using JDBC, you define it using Connection#setTransactionIsolation
.
Using Hibernate:
<property name="hibernate.connection.isolation">2</property>
Where
Hibernate configuration is taken from here (sorry, it's in Spanish).
By the way, you can set the isolation level on RDBMS as well:
SET ISOLATION TO DIRTY READ
sentence.)and on and on...
The way to keep SELECT dbo.fCalculateEstimateDate(647)
call working is:
ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100) AS
Declare @Result varchar(100)
SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
Return @Result
Begin
End
CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100) AS
Begin
<Function Body>
End
BigDecimal obj = new BigDecimal("100");
if(obj.intValue()>0)
System.out.println("yes");
I found @cocco's answer interesting, but had the following issues with it:
TypeScript:
/**
* Describes manner by which a quantity of bytes will be formatted.
*/
enum ByteFormat {
/**
* Use Base 10 (1 kB = 1000 bytes). Recommended for sizes of files on disk, disk sizes, bandwidth.
*/
SI = 0,
/**
* Use Base 2 (1 KiB = 1024 bytes). Recommended for RAM size, size of files on disk.
*/
IEC = 1
}
/**
* Returns a human-readable representation of a quantity of bytes in the most reasonable unit of magnitude.
* @example
* formatBytes(0) // returns "0 bytes"
* formatBytes(1) // returns "1 byte"
* formatBytes(1024, ByteFormat.IEC) // returns "1 KiB"
* formatBytes(1024, ByteFormat.SI) // returns "1.02 kB"
* @param size The size in bytes.
* @param format Format using SI (Base 10) or IEC (Base 2). Defaults to SI.
* @returns A string describing the bytes in the most reasonable unit of magnitude.
*/
function formatBytes(
value: number,
format: ByteFormat = ByteFormat.SI
) {
const [multiple, k, suffix] = (format === ByteFormat.SI
? [1000, 'k', 'B']
: [1024, 'K', 'iB']) as [number, string, string]
// tslint:disable-next-line: no-bitwise
const exp = (Math.log(value) / Math.log(multiple)) | 0
// or, if you'd prefer not to use bitwise expressions or disabling tslint rules, remove the line above and use the following:
// const exp = value === 0 ? 0 : Math.floor(Math.log(value) / Math.log(multiple))
const size = Number((value / Math.pow(multiple, exp)).toFixed(2))
return (
size +
' ' +
(exp
? (k + 'MGTPEZY')[exp - 1] + suffix
: 'byte' + (size !== 1 ? 's' : ''))
)
}
// example
[0, 1, 1024, Math.pow(1024, 2), Math.floor(Math.pow(1024, 2) * 2.34), Math.pow(1024, 3), Math.floor(Math.pow(1024, 3) * 892.2)].forEach(size => {
console.log('Bytes: ' + size)
console.log('SI size: ' + formatBytes(size))
console.log('IEC size: ' + formatBytes(size, 1) + '\n')
});
import sys
f = open(sys.argv[1] , 'r')
for line in f.readlines()[::-1]:
print line
Let's assume you want to overwrite the same file:
import json
with open('data.json', 'r') as data_file:
data = json.load(data_file)
for element in data:
element.pop('hours', None)
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
dict.pop(<key>, not_found=None)
is probably what you where looking for, if I understood your requirements. Because it will remove the hours
key if present and will not fail if not present.
However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?
Now, if you really want to use del
instead of pop
, here is how you could make your code work:
import json
with open('data.json') as data_file:
data = json.load(data_file)
for element in data:
if 'hours' in element:
del element['hours']
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.
I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.
with
is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with
block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.
Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.
I hope it's clear enough...
SECOND EDIT
This time, it seems clear that you need to do this:
with open('dest_file.json', 'w') as dest_file:
with open('source_file.json', 'r') as source_file:
for line in source_file:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
dest_file.write(json.dumps(element))
For ng serve you need to be inside that directory
ashish@ashish-Inspiron-3521:~/Angular$ ng new FireStore
create FireStore/README.md (1025 bytes)
create FireStore/.angular-cli.json (1245 bytes)
create FireStore/.editorconfig (245 bytes)
create FireStore/.gitignore (544 bytes)
create FireStore/src/assets/.gitkeep (0 bytes)
create FireStore/src/environments/environment.prod.ts (51 bytes)
create FireStore/src/environments/environment.ts (387 bytes)
create FireStore/src/favicon.ico (5430 bytes)
create FireStore/src/index.html (296 bytes)
create FireStore/src/main.ts (370 bytes)
create FireStore/src/polyfills.ts (3114 bytes)
create FireStore/src/styles.css (80 bytes)
ashish@ashish-Inspiron-3521:~/Angular$ ng serve
You seem to not be depending on "@angular/core". This is an error.
How I solved this using cmd
ashish@ashish-Inspiron-3521:~/Angular$ cd FireStore/
Now Do cmd
ashish@ashish-Inspiron-3521:~/Angular/FireStore$ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
elements is an array of DOM objects. You should do something like this
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('hover');
}
ie: enumerate the elements collection, and for each element inside the collection call the remove method
One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):
My solution will be to run the code (On timer event) from another hidden form that opens with the database.
Does anyone see any reason why not to do this?
mystring.Select(Convert.ToByte).ToArray()
Just use the *args
parameter, which allows you to pass as many arguments as you want after your a,b,c
. You would have to add some logic to map args
->c,d,e,f
but its a "way" of overloading.
def myfunc(a,b, *args, **kwargs):
for ar in args:
print ar
myfunc(a,b,c,d,e,f)
And it will print values of c,d,e,f
Similarly you could use the kwargs
argument and then you could name your parameters.
def myfunc(a,b, *args, **kwargs):
c = kwargs.get('c', None)
d = kwargs.get('d', None)
#etc
myfunc(a,b, c='nick', d='dog', ...)
And then kwargs
would have a dictionary of all the parameters that are key valued after a,b
If you wan't to animate your background using only core jQuery functionality, try this:
jQuery(".usercontent").mouseover(function() {
jQuery(".usercontent").animate({backgroundColor:'red'}, 'fast', 'linear', function() {
jQuery(this).animate({
backgroundColor: 'white'
}, 'normal', 'linear', function() {
jQuery(this).css({'background':'none', backgroundColor : ''});
});
});
Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405
When importing a database in your SQL instance you would find yourself with Cannot use the special principal 'sa'. Microsoft SQL Server, Error: 15405 popping out when setting the sa user as the DBO of the database. To fix this, Open SQL Management Studio and Click New Query. Type:
USE mydatabase
exec sp_changedbowner 'sa', 'true'
Close the new query and after viewing the security of the sa, you will find that that sa is the DBO of the database. (14444)
Source: http://www.noelpulis.com/fix-cannot-use-the-special-principal-sa-microsoft-sql-server-error-15405/
This worked for me for on Windows10
curl -d "{"""owner""":"""sasdasdasdasd"""}" -H "Content-Type: application/json" -X PUT http://localhost:8080/api/changeowner/CAR4
Simple HTML trick to get this :
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row" >_x000D_
_x000D_
<div class="col-md-6">_x000D_
<div class="row">_x000D_
<div class="col-md-4" >_x000D_
<label for="hours">Hours</label>_x000D_
<select class="form-control" required>_x000D_
<option> </option>_x000D_
<option value="1"> 1 </option>_x000D_
<option value="2"> 2 </option>_x000D_
<option value="3"> 3 </option>_x000D_
<option value="4"> 4 </option>_x000D_
<option value="5"> 5 </option>_x000D_
<option value="6"> 6 </option>_x000D_
<option value="7"> 7 </option>_x000D_
<option value="8"> 8 </option>_x000D_
<option value="9"> 9 </option>_x000D_
<option value="10"> 10 </option>_x000D_
<option value="11"> 11 </option>_x000D_
<option value="12"> 12 </option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="col-md-4" >_x000D_
<label for="minutes">Minutes</label>_x000D_
<select class="form-control" required="">_x000D_
<option selected disabled> </option>_x000D_
<option value="00"> 00 </option>_x000D_
<option value="10"> 10 </option>_x000D_
<option value="20"> 20 </option>_x000D_
<option value="30"> 30 </option>_x000D_
<option value="40"> 40 </option>_x000D_
<option value="50"> 50 </option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="col-md-4" >_x000D_
<label for="hours">Select Meridiem</label>_x000D_
<select class="form-control" required="" >_x000D_
<option selected="" value="AM"> AM </option>_x000D_
<option value="PM"> PM </option>_x000D_
</select>_x000D_
</div>_x000D_
</div></div>_x000D_
</div>
_x000D_
Laravel Eloquent provides destroy()
function in which returns boolean
value. So if a record exists on the database and deleted you'll get true
otherwise false
.
Here's an example using Laravel Tinker shell.
In this case, your code should look like this:
public function destroy($id)
{
$res = User::destroy($id);
if ($res) {
return response()->json([
'status' => '1',
'msg' => 'success'
]);
} else {
return response()->json([
'status' => '0',
'msg' => 'fail'
]);
}
}
More info about Laravel Eloquent Deleting Models
If you haven't yet installed jquery (because you're just a beginner or something), use this bit of code:
<a href="#" onclick="thisfunction()">link</a>
<script type="text/javascript">
function thisfunction(){
var x = new XMLHttpRequest();
x.open("GET","function.php",true);
x.send();
return false;
}
</script>
I would suggest this for matching Chrome's style, extended from Jarish's example. Notice the cursor property which previous answers have omitted.
cursor: text;
border: 1px solid #ccc;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 200px;
overflow: auto;
padding: 2px;
resize: both;
-moz-box-shadow: inset 0px 1px 2px #ccc;
-webkit-box-shadow: inset 0px 1px 2px #ccc;
box-shadow: inset 0px 1px 2px #ccc;
Use controller.controller_name
In the Rails Guides, it says:
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values
So let's say you have a CSS class active
, that should be inserted in any link whose page is currently open (maybe so that you can style differently) . If you have a static_pages
controller with an about
action, you can then highlight the link like so in your view:
<li>
<a class='button <% if controller.controller_name == "static_pages" && controller.action_name == "about" %>active<%end%>' href="/about">
About Us
</a>
</li>
You should not mix-up arrays and generics. They don't go well together. There are differences in how arrays and generic types enforce the type check. We say that arrays are reified, but generics are not. As a result of this, you see these differences working with arrays and generics.
What that means? You must be knowing by now that the following assignment is valid:
Object[] arr = new String[10];
Basically, an Object[]
is a super type of String[]
, because Object
is a super type of String
. This is not true with generics. So, the following declaration is not valid, and won't compile:
List<Object> list = new ArrayList<String>(); // Will not compile.
Reason being, generics are invariant.
Generics were introduced in Java to enforce stronger type check at compile time. As such, generic types don't have any type information at runtime due to type erasure. So, a List<String>
has a static type of List<String>
but a dynamic type of List
.
However, arrays carry with them the runtime type information of the component type. At runtime, arrays use Array Store check to check whether you are inserting elements compatible with actual array type. So, the following code:
Object[] arr = new String[10];
arr[0] = new Integer(10);
will compile fine, but will fail at runtime, as a result of ArrayStoreCheck. With generics, this is not possible, as the compiler will try to prevent the runtime exception by providing compile time check, by avoiding creation of reference like this, as shown above.
Creation of array whose component type is either a type parameter, a concrete parameterized type or a bounded wildcard parameterized type, is type-unsafe.
Consider the code as below:
public <T> T[] getArray(int size) {
T[] arr = new T[size]; // Suppose this was allowed for the time being.
return arr;
}
Since the type of T
is not known at runtime, the array created is actually an Object[]
. So the above method at runtime will look like:
public Object[] getArray(int size) {
Object[] arr = new Object[size];
return arr;
}
Now, suppose you call this method as:
Integer[] arr = getArray(10);
Here's the problem. You have just assigned an Object[]
to a reference of Integer[]
. The above code will compile fine, but will fail at runtime.
That is why generic array creation is forbidden.
new Object[10]
to E[]
works?Now your last doubt, why the below code works:
E[] elements = (E[]) new Object[10];
The above code have the same implications as explained above. If you notice, the compiler would be giving you an Unchecked Cast Warning there, as you are typecasting to an array of unknown component type. That means, the cast may fail at runtime. For e.g, if you have that code in the above method:
public <T> T[] getArray(int size) {
T[] arr = (T[])new Object[size];
return arr;
}
and you call invoke it like this:
String[] arr = getArray(10);
this will fail at runtime with a ClassCastException. So, no this way will not work always.
List<String>[]
?The issue is the same. Due to type erasure, a List<String>[]
is nothing but a List[]
. So, had the creation of such arrays allowed, let's see what could happen:
List<String>[] strlistarr = new List<String>[10]; // Won't compile. but just consider it
Object[] objarr = strlistarr; // this will be fine
objarr[0] = new ArrayList<Integer>(); // This should fail but succeeds.
Now the ArrayStoreCheck in the above case will succeed at runtime although that should have thrown an ArrayStoreException. That's because both List<String>[]
and List<Integer>[]
are compiled to List[]
at runtime.
Yes. The reason being, a List<?>
is a reifiable type. And that makes sense, as there is no type associated at all. So there is nothing to loose as a result of type erasure. So, it is perfectly type-safe to create an array of such type.
List<?>[] listArr = new List<?>[10];
listArr[0] = new ArrayList<String>(); // Fine.
listArr[1] = new ArrayList<Integer>(); // Fine
Both the above case is fine, because List<?>
is super type of all the instantiation of the generic type List<E>
. So, it won't issue an ArrayStoreException at runtime. The case is same with raw types array. As raw types are also reifiable types, you can create an array List[]
.
So, it goes like, you can only create an array of reifiable types, but not non-reifiable types. Note that, in all the above cases, declaration of array is fine, it's the creation of array with new
operator, which gives issues. But, there is no point in declaring an array of those reference types, as they can't point to anything but null
(Ignoring the unbounded types).
E[]
?Yes, you can create the array using Array#newInstance()
method:
public <E> E[] getArray(Class<E> clazz, int size) {
@SuppressWarnings("unchecked")
E[] arr = (E[]) Array.newInstance(clazz, size);
return arr;
}
Typecast is needed because that method returns an Object
. But you can be sure that it's a safe cast. So, you can even use @SuppressWarnings on that variable.
You need to modify the method GetData()
and add your "experimental" code there, and return t1
.
String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> namesList = Arrays.asList(names);
or
String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> temp = Arrays.asList(names);
Above Statement adds the wrapper on the input array. So the methods like add & remove will not be applicable on list reference object 'namesList'.
If you try to add an element in the existing array/list then you will get "Exception in thread "main" java.lang.UnsupportedOperationException".
The above operation is readonly or viewonly.
We can not perform add or remove operation in list object.
But
String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.ArrayList<String> list1 = new ArrayList<>(Arrays.asList(names));
or
String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> listObject = Arrays.asList(names);
java.util.ArrayList<String> list1 = new ArrayList<>(listObject);
In above statement you have created a concrete instance of an ArrayList class and passed a list as a parameter.
In this case method add & remove will work properly as both methods are from ArrayList class so here we won't get any UnSupportedOperationException.
Changes made in Arraylist object (method add or remove an element in/from an arraylist) will get not reflect in to original java.util.List object.
String names[] = new String[] {
"Avinash",
"Amol",
"John",
"Peter"
};
java.util.List < String > listObject = Arrays.asList(names);
java.util.ArrayList < String > list1 = new ArrayList < > (listObject);
for (String string: list1) {
System.out.print(" " + string);
}
list1.add("Alex"); //Added without any exception
list1.remove("Avinash"); //Added without any exception will not make any changes in original list in this case temp object.
for (String string: list1) {
System.out.print(" " + string);
}
String existingNames[] = new String[] {
"Avinash",
"Amol",
"John",
"Peter"
};
java.util.List < String > namesList = Arrays.asList(names);
namesList.add("Bob"); // UnsupportedOperationException occur
namesList.remove("Avinash"); //UnsupportedOperationException
Always keep in mind that 'size' is variable if not explicitly specified so if you declare
int i = 10;
On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).
In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across
typedef short INT16;
typedef int INT32;
typedef long INT64;
Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.
On a windows based system, you may see entries in stdin.h header file as
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.
I've created a little Powershell function to emulate MSDOS pause
. This handles whether running Powershell ISE or non ISE. (ReadKey
does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox
. This can sometimes be confusing, because the MessageBox
does not always come to the forefront. Anyway, here it goes:
Usage:
pause "Press any key to continue"
Function definition:
Function pause ($message)
{
# Check if running Powershell ISE
if ($psISE)
{
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("$message")
}
else
{
Write-Host "$message" -ForegroundColor Yellow
$x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
}
The error is here:
hasLetter("a",words[]);
You are passing the first item of words
, instead of the array.
Instead, pass the array to the function:
hasLetter("a",words);
Problem solved!
Here's a breakdown of what the problem was:
I'm guessing in your browser (chrome throws a different error), words[] == words[0]
, so when you call hasLetter("a",words[]);
, you are actually calling hasLetter("a",words[0]);
. So, in essence, you are passing the first item of words to your function, not the array as a whole.
Of course, because words
is just an empty array, words[0]
is undefined
. Therefore, your function call is actually:
hasLetter("a", undefined);
which means that, when you try to access d[ascii]
, you are actually trying to access undefined[0]
, hence the error.
I had sometimes the same Exception.
When i create a FXML-File with the Wizard in Eclipse, i write example.fxml in the name field. Eclipse creates a file, like example.fxml.fxml. With this mistake, the FXMLLoader can't find the right FXML-File. So, my tip, check the name of the FXML-Filename in your start-Method and the real Name of File.
Hopes i could help. Good luck.
Even simpler:
=indirect(address(row(), column() - 1))
OFFSET returns a reference relative to the current reference, so if indirect returns the correct reference, you don't need it.
There are a few possible ways to do this:
PYTHONPATH
to a colon-separated list of directories to search for imported modules.sys.path.append('/path/to/search')
to add the names of directories you want Python to search for imported modules. sys.path
is just the list of directories Python searches every time it gets asked to import a module, and you can alter it as needed (although I wouldn't recommend removing any of the standard directories!). Any directories you put in the environment variable PYTHONPATH
will be inserted into sys.path
when Python starts up.site.addsitedir
to add a directory to sys.path
. The difference between this and just plain appending is that when you use addsitedir
, it also looks for .pth
files within that directory and uses them to possibly add additional directories to sys.path
based on the contents of the files. See the documentation for more detail.Which one of these you want to use depends on your situation. Remember that when you distribute your project to other users, they typically install it in such a manner that the Python code files will be automatically detected by Python's importer (i.e. packages are usually installed in the site-packages
directory), so if you mess with sys.path
in your code, that may be unnecessary and might even have adverse effects when that code runs on another computer. For development, I would venture a guess that setting PYTHONPATH
is usually the best way to go.
However, when you're using something that just runs on your own computer (or when you have nonstandard setups, e.g. sometimes in web app frameworks), it's not entirely uncommon to do something like
import sys
from os.path import dirname
sys.path.append(dirname(__file__))
you should you use following code
$configValue = Mage::getStoreConfig(
'sectionName/groupName/fieldName',
Mage::app()->getStore()
);
Mage::app()->getStore()
this will add store code in fetch values so that you can get correct configuration values for current store this will avoid incorrect store's values because magento is also use for multiple store/views so must add store code to fetch anything in magento.
if we have more then one store or multiple views configured then this will insure that we are getting values for current store
//MARK:- Use this class for different type of Roles
import UIKit
class HelperExtensionViewController: UIViewController {
}
//MARK:- Extension
extension UIImageView
{
func setImageCornerRadius()
{
self.layer.cornerRadius = self.frame.size.height/2
self.clipsToBounds = true
}
func setImageCornerRadiusInPoints(getValue:CGFloat)
{
self.layer.cornerRadius = getValue
self.clipsToBounds = true
}
}
extension UIButton
{
func setButtonCornerRadiusOnly()
{
self.layer.cornerRadius = self.frame.size.height/2
self.clipsToBounds = true
}
func setBtnCornerRadiusInPoints(getValue:CGFloat)
{
self.layer.cornerRadius = getValue
self.clipsToBounds = true
}
}
extension UITextField
{
func setTextFieldCornerRadiusWithBorder()
{
self.layer.cornerRadius = self.frame.size.height/2
self.layer.borderColor = UIColor.darkGray.cgColor
self.backgroundColor = UIColor.clear
self.layer.borderWidth = 0.5
self.clipsToBounds = true
}
func setLeftPaddingPoints(_ amount:CGFloat){
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.leftView = paddingView
self.leftViewMode = .always
}
func setRightPaddingPoints(_ amount:CGFloat) {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.rightView = paddingView
self.rightViewMode = .always
}
}
extension UIView
{
func setCornerRadius()
{
self.layer.cornerRadius = self.frame.size.height/2
self.clipsToBounds = true
}
// OUTPUT 1
func setViewCornerRadiusWithBorder()
{
self.layer.cornerRadius = self.frame.size.height/2
self.layer.borderColor = UIColor.init(red: 95.0/255.0, green: 229.0/255.0, blue: 206.0/255.0, alpha: 1.0).cgColor
self.backgroundColor = UIColor.clear
self.layer.borderWidth = 1.0
self.clipsToBounds = true
}
func layoutSubviews(myView:UIView)
{
let shadowPath = UIBezierPath(rect: myView.bounds)
myView.layer.masksToBounds = false
myView.layer.shadowColor = UIColor.lightGray.cgColor
myView.layer.shadowOffset = CGSize(width: -1.0, height: 2.0)
myView.layer.shadowOpacity = 0.5
myView.layer.shadowPath = shadowPath.cgPath
}
func layoutSubviews2(myView:UIView)
{
let shadowPath = UIBezierPath(rect: myView.bounds)
myView.clipsToBounds = true
myView.layer.masksToBounds = false
myView.layer.shadowColor = UIColor.black.cgColor
myView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
myView.layer.shadowOpacity = 0.2
myView.layer.shadowPath = shadowPath.cgPath
}
func setViewCornerRadiusInPoints(getValue:CGFloat)
{
self.layer.cornerRadius = getValue
self.clipsToBounds = true
}
func dropShadow(scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.shadowRadius = 1
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
// OUTPUT 2
func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowOffset = offSet
layer.shadowRadius = radius
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
func setGradientBackground(myview:UIView) {
let colorTop = UIColor(red: 100.0/255.0, green: 227.0/255.0, blue: 237.0/255.0, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 141.0/255.0, green: 109.0/255.0, blue: 164.0/255.0, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.locations = [1.0, 1.0]
gradientLayer.frame = myview.bounds
myview.layer.insertSublayer(gradientLayer, at:0)
}
}
You should also use <label for="checkbox1">Checkbox 1</label>
because then people can click on the label text as well as the checkbox itself. Its also easier to style and at least in IE it will be highlighted when you tab through the page's controls.
<%= Html.CheckBox("cbNewColors", true) %><label for="cbNewColors">New colors</label>
This is not just a 'oh I could do it' thing. Its a significant user experience enhancement. Even if not all users know they can click on the label many will.
Yes you can negate the test as SiegeX has already pointed out.
However you shouldn't use regular expressions for this - it can fail if your path contains special characters. Try this instead:
[[ ":$PATH:" != *":$1:"* ]]
Though this isn't a DIRECT answer to your question, I just encountered a similar problem, and thought I'd mentioned it:
I had an instance where it was instantiating a new (no doubt very inefficent) record for data.frame (a result of recursive searching) and it was giving me the same error.
I had this:
return(
data.frame(
user_id = gift$email,
sourced_from_agent_id = gift$source,
method_used = method,
given_to = gift$account,
recurring_subscription_id = NULL,
notes = notes,
stringsAsFactors = FALSE
)
)
turns out... it was the = NULL. When I switched to = NA, it worked fine. Just in case anyone else with a similar problem hits THIS post as I did.
Even better, you can encapsule this to clear any type of controls you want in one method, like this:
public static void EstadoControles<T>(object control, bool estado, bool limpiar = false) where T : Control
{
foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Enabled = estado;
foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.Enabled = estado;
if (!limpiar) return;
{
foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Text = string.Empty;
foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.EditValue = @"-1";
}
}
They are both going to have the same effect.
However, as pointed out in the comments: $(window).scrollTop()
is supported by more web browsers than $('html').scrollTop()
.
The initial issue is solved by changing lat
and lon
to double.
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
I just wanted to share my experience
For me,
$('#selectorId').val()
returned null.
I had to use
$('#selectorId option:selected').val()
I use
Object.entries(GoalProgressMeasurement).filter(e => !isNaN(e[0]as any)).map(e => ({ name: e[1], id: e[0] }));
A simple 1 line that does the job.
It does the job in 3 simple steps
- Loads the combination of keys & values using Object.entries
.
- Filters out the non numbers (since typescript generates the values for reverse lookup).
- Then we map it to the array object we like.
Yes. You just have to use the RAISE_APPLICATION_ERROR
function. If you also want to name your exception, you'll need to use the EXCEPTION_INIT
pragma in order to associate the error number to the named exception. Something like
SQL> ed
Wrote file afiedt.buf
1 declare
2 ex_custom EXCEPTION;
3 PRAGMA EXCEPTION_INIT( ex_custom, -20001 );
4 begin
5 raise_application_error( -20001, 'This is a custom error' );
6 exception
7 when ex_custom
8 then
9 dbms_output.put_line( sqlerrm );
10* end;
SQL> /
ORA-20001: This is a custom error
PL/SQL procedure successfully completed.
I got tired of seeing this page with its by-now stale references to defunct Codehaus pages so I asked on the Maven Users mailing list and got some more up-to-date answers.
I would say that the best (and most authoritative) answer contained in my link above is the one contributed by Hervé BOUTEMY:
here is the core reference: http://maven.apache.org/ref/3-LATEST/maven-model-builder/
it does not explain everyting that can be found in POM or in settings, since there are so much info available but it points to POM and settings descriptors and explains everything that is not POM or settings
return n
from your main entry function will terminate your process and report to the parent process (the one that executed your process) the result of your process. 0 means SUCCESS. Other codes usually indicates a failure and its meaning.
I am a little late to the party but I thought I'd share a way of doing it, if you have identical types of conditions, i.e. checking if all, any or at given amount of A_1=A_2 and B_1=B_2, this can be done in the following way:
cond_list_1=["1","2","3"]
cond_list_2=["3","2","1"]
nr_conds=1
if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])>=nr_conds:
print("At least " + str(nr_conds) + " conditions are fullfilled")
if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])==len(cond_list_1):
print("All conditions are fullfilled")
This means you can just change in the two initial lists, at least for me this makes it easier.
If you are able to use the bash shell, you can consider simply running the R code from within a bash script and piping the stdout and stderr streams to a file. Here is an example using a heredoc:
File: test.sh
#!/bin/bash
# this is a bash script
echo "Hello World, this is bash"
test1=$(echo "This is a test")
echo "Here is some R code:"
Rscript --slave --no-save --no-restore - "$test1" <<EOF
## R code
cat("\nHello World, this is R\n")
args <- commandArgs(TRUE)
bash_message<-args[1]
cat("\nThis is a message from bash:\n")
cat("\n",paste0(bash_message),"\n")
EOF
# end of script
Then when you run the script with both stderr and stdout piped to a log file:
$ chmod +x test.sh
$ ./test.sh
$ ./test.sh &>test.log
$ cat test.log
Hello World, this is bash
Here is some R code:
Hello World, this is R
This is a message from bash:
This is a test
Other things to look at for this would be to try simply pipping the stdout and stderr right from the R heredoc into a log file; I haven't tried this yet but it will probably work too.
The simple way of doing this would be (assuming your list is in 'l'):
>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]
Complete sample:
>>> l = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
...
>>> counter
{'and': 3, '': 1, 'merry': 1, 'rise.': 1, 'small;': 1, 'Moon': 1, 'cheerful': 1, 'bright': 1, 'Cats': 5, 'are': 3, 'have': 2, 'bright,': 1, 'for': 1, 'their': 1, 'rather': 1, 'when': 1, 'to': 3, 'airs': 1, 'black': 2, 'They': 1, 'practise': 1, 'caterwaul.': 1, 'pleasant': 1, 'hear': 1, 'they': 1, 'white,': 1, 'wait': 1, 'And': 2, 'like': 1, 'Jellicle': 6, 'eyes;': 1, 'the': 1, 'faces,': 1, 'graces': 1}
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]
With simple I mean working in nearly every version of python.
if you don't understand some of the functions used in this sample, you can always do this in the interpreter (after pasting the code above):
>>> help(counter.get)
>>> help(sorted)
Exceute the program by pressing SHIFT+F6, instead of clicking the RUN button on the window. This might be silly, bt the error main class not found is not occurring, the project is executing well...
it looks different from one situation to another. for me i did an installation and update a lot of things that the sdk manager said to then i had this problem. all i did was: from file -> Invalidate caches/Restart (a dialog will pop-up) choose Invalidate and restart.
after the restart is done. everything was fixed but i needed to create a new emulator and delete the old one. (android studio 1.3.1) (one professional must edit this to be more understandable) . . . Here everything was fine, but your machines also needs restart because some system files are changed, to sync them we have to restart the system.
Retrieve profile information for a signed-in user Use the GoogleSignInResult.getSignInAccount method to request profile information for the currently signed in user. You can call the getSignInAccount method after the sign-in intent succeeds.
GoogleSignInResult result =
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
I want to change the width and height of a div. data attributes did not change it. Instead I use:
var size = $("#theme_photo_size").val().split("x");
$("#imageupload_img").width(size[0]);
$("#imageupload_img").attr("data-width", size[0]);
$("#imageupload_img").height(size[1]);
$("#imageupload_img").attr("data-height", size[1]);
be careful:
$("#imageupload_img").data("height", size[1]); //did not work
did not set it
$("#imageupload_img").attr("data-height", size[1]); // yes it worked!
this has set it.
The following should work:
ABC: *\([a-zA-Z]+\) *(.+)
Explanation:
ABC: # match literal characters 'ABC:'
* # zero or more spaces
\([a-zA-Z]+\) # one or more letters inside of parentheses
* # zero or more spaces
(.+) # capture one or more of any character (except newlines)
To get your desired grouping based on the comments below, you can use the following:
(ABC:) *(\([a-zA-Z]+\).+)
String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.
System.out.println("line 1" + newLine + "line2");
If the string contain similar pattern like abccc
, you can use this:
str.replace(/abc(\s|$)/g, "")
One solution
DetailViewController *controller = [[DetailViewController alloc] initWithNibName:nil
bundle:[NSBundle mainBundle]];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
navController.modalPresentationStyle = UIModalPresentationCurrentContext;
[self.navigationController presentViewController:navController
animated:YES
completion:nil];
This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on Aspect-Oriented Programming and Transactions, as Spring's declarative transaction support uses AOP at its foundation.
But at a very high level, Spring creates proxies for classes that declare @Transactional on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with @Transactional, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.
Transactions in EJB work similarly, by the way.
As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the "this" reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in this forum post in which I use a BeanFactoryPostProcessor to inject an instance of the proxy into "self-referencing" classes at runtime. I save this reference to a member variable called "me". Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. "me.someMethod()".) The forum post explains in more detail. Note that the BeanFactoryPostProcessor code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available.
"The list are variables/paramaters that is pre-defined as comma separated lists". Do you mean that your query is actually
UPDATE tab1 SET budgpost_gr1=
CASE WHEN (budgpost in ('1001,1012,50055')) THEN 'BP_GR_A'
WHEN (budgpost in ('5,10,98,0')) THEN 'BP_GR_B'
WHEN (budgpost in ('11,876,7976,67465'))
ELSE 'Missing' END`
If so, you need a function to take a string and parse it into a list of numbers.
create type tab_num is table of number;
create or replace function f_str_to_nums (i_str in varchar2) return tab_num is
v_tab_num tab_num := tab_num();
v_start number := 1;
v_end number;
v_delim VARCHAR2(1) := ',';
v_cnt number(1) := 1;
begin
v_end := instr(i_str||v_delim,v_delim,1, v_start);
WHILE v_end > 0 LOOP
v_cnt := v_cnt + 1;
v_tab_num.extend;
v_tab_num(v_tab_num.count) :=
substr(i_str,v_start,v_end-v_start);
v_start := v_end + 1;
v_end := instr(i_str||v_delim,v_delim,v_start);
END LOOP;
RETURN v_tab_num;
end;
/
Then you can use the function like so:
select column_id,
case when column_id in
(select column_value from table(f_str_to_nums('1,2,3,4'))) then 'red'
else 'blue' end
from user_tab_columns
where table_name = 'EMP'
How to use index in select statement?
this way:
SELECT * FROM table1 USE INDEX (col1_index,col2_index)
WHERE col1=1 AND col2=2 AND col3=3;
SELECT * FROM table1 IGNORE INDEX (col3_index)
WHERE col1=1 AND col2=2 AND col3=3;
SELECT * FROM t1 USE INDEX (i1) IGNORE INDEX (i2) USE INDEX (i2);
And many more ways check this
Do I need to explicitly specify?
$().ready(docReady);
function docReady() {
$("#myTextbox").focusout(uCaseMe);
}
function uCaseMe() {
var val = $(this).val().toUpperCase();
// Reset the current value to the Upper Case Value
$(this).val(val);
}
This is a reusable approach. Any number of textboxes can be done this way w/o naming them. A page wide solution could be achieved by changing the selector in docReady.
My example uses lost focus, the question did not specify as they type. You could trigger on change if thats important in your scenario.
For iOS 7 that's what i made and worked for me
@implementation UILabel (VerticalAlign)
- (void)alignTop
{
CGSize boundingRectSize = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
NSDictionary *attributes = @{NSFontAttributeName : self.font};
CGRect labelSize = [self.text boundingRectWithSize:boundingRectSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attributes
context:nil];
int numberOfLines= ceil(labelSize.size.height / self.font.lineHeight);
CGRect newFrame = self.frame;
newFrame.size.height = numberOfLines * self.font.lineHeight;
self.frame = newFrame;
}
- (void)alignBottom
{
CGSize boundingRectSize = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
NSDictionary *attributes = @{NSFontAttributeName : self.font};
CGRect labelSize = [self.text boundingRectWithSize:boundingRectSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attributes
context:nil];
int numberOfLines= ceil(labelSize.size.height / self.font.lineHeight);
int numberOfNewLined = (self.frame.size.height/self.font.lineHeight) - numberOfLines;
NSMutableString *newLines = [NSMutableString string];
for(int i=0; i< numberOfNewLined; i++){
[newLines appendString:@"\n"];
}
[newLines appendString:self.text];
self.text = [newLines mutableCopy];
}
Maybe something changed since 2011 but this worked for me:
$ date +"%Y%m%d"
20150330
No need for the -d
to get the same appearing result.
I ran into this problem today and this was the trick I did, which worked for me:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DAOMANAGER");
EntityManagerem = emf.createEntityManager();
org.hibernate.Session session = ((EntityManagerImpl) em).getSession();
java.sql.Connection connectionObj = session.connection();
Though not the best way but does the job.
Actually, U+2018 is the Unicode representation of the special character ‘ . If you want, you can convert instances of that character to U+0027 with this code:
text = text.replace (u"\u2018", "'")
In addition, what are you using to write the file? f1.read()
should return a string that looks like this:
'I don\xe2\x80\x98t like this'
If it's returning this string, the file is being written incorrectly:
'I don\u2018t like this'
Check the API Docs
Methods addOption(data)
and setValue(value)
might be what you are looking for.
Update: Seeing the popularity of this answer, here is some additional info based on comments/requests...
setValue(value, silent)
Resets the selected items to the given value.
If "silent" is truthy (ie:true
,1
), no change event will be fired on the original input.
addOption(data)
Adds an available option, or array of options. If it already exists, nothing will happen.
Note: this does not refresh the options list dropdown (userefreshOptions()
for that).
In response to options being overwritten:
This can happen by re-initializing the select without using the options you initially provided. If you are not intending to recreate the element, simply store the selectize object to a variable:
// 1. Only set the below variables once (ideally)
var $select = $('select').selectize(options); // This initializes the selectize control
var selectize = $select[0].selectize; // This stores the selectize object to a variable (with name 'selectize')
// 2. Access the selectize object with methods later, for ex:
selectize.addOption(data);
selectize.setValue('something', false);
// Side note:
// You can set a variable to the previous options with
var old_options = selectize.settings;
// If you intend on calling $('select').selectize(old_options) or something
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
I researched this just recently and have yet to find a decent date picker that also includes a decent time picker. What I ended up using was eyecon's awesome DatePicker, with two simple dropdowns for time. I was tempted to use Timepickr.js though, looks like a really nice approach.
You can set the width in pixels via inline styling:
<input type="text" name="text" style="width: 195px;">
You can also set the width with a visible character length:
<input type="text" name="text" size="35">
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
Note: Commenting out bind_ip can make your system vulnerable to security flaws. Please see Security Checklist. It is a better idea to add more IP addresses than to open up your system to everything.
You need to edit your /etc/mongod.conf file's bind_ip variable to include the IP of the computer you're using, or eliminate it altogether.
I was able to connect using the following mongod.conf file. I commented out bind_ip and uncommented port.
# mongod.conf
# Where to store the data.
# Note: if you run MongoDB as a non-root user (recommended) you may
# need to create and set permissions for this directory manually.
# E.g., if the parent directory isn't mutable by the MongoDB user.
dbpath=/var/lib/mongodb
# Where to log
logpath=/var/log/mongodb/mongod.log
logappend=true
port = 27017
# Listen to local interface only. Comment out to listen on all
interfaces.
#bind_ip = 127.0.0.1
# Disables write-ahead journaling
# nojournal = true
# Enables periodic logging of CPU utilization and I/O wait
#cpu = true
# Turn on/off security. Off is currently the default
#noauth = true
#auth = true
# Verbose logging output.
#verbose = true
# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true
# Enable db quota management
#quota = true
# Set oplogging level where n is
# 0=off (default)
# 1=W
# 2=R
# 3=both
# 7=W+some reads
#diaglog = 0
# Ignore query hints
#nohints = true
# Enable the HTTP interface (Defaults to port 28017).
#httpinterface = true
# Turns off server-side scripting. This will result in greatly limited
# functionality
#noscripting = true
# Turns off table scans. Any query that would do a table scan fails.
#notablescan = true
# Disable data file preallocation.
#noprealloc = true
# Specify .ns file size for new databases.
# nssize = <size>
# Replication Options
# In replicated MongoDB databases, specify the replica set name here
#replSet=setname
# Maximum size in megabytes for replication operation log
#oplogSize=1024
# Path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile
Don't forget to restart the mongod service before trying to connect:
service mongod restart
From Robomongo, I used the following connection settings:
Connection Tab:
SSH Tab:
SSH Address: [VPS IP] : 22
SSH User Name: [Username for sudo enabled user]
SSH Auth Method: Password
User Password: Supersecret
Try this code. By using the parent>child selector "#productList li" it should find all li elements. Then, you can iterate through the result object using the each() method which will only alter li elements that have been found.
listItems = $("#productList li").each(function(){
var product = $(this);
var productid = product.children(".productId").val();
var productPrice = product.find(".productPrice").val();
var productMSRP = product.find(".productMSRP").val();
totalItemsHidden.val(parseInt(totalItemsHidden.val(), 10) + 1);
subtotalHidden.val(parseFloat(subtotalHidden.val()) + parseFloat(productMSRP));
savingsHidden.val(parseFloat(savingsHidden.val()) + parseFloat(productMSRP - productPrice));
totalHidden.val(parseFloat(totalHidden.val()) + parseFloat(productPrice));
});
Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto
or set a specific height to your div
. Live example: http://jsfiddle.net/tw16/xRcXL/3/
.Tab{
overflow:auto; /* add this */
border:solid 1px #faa62a;
border-bottom:none;
padding:7px 10px;
background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}
I am running Python 3.6 on MacOS Catalina. My issue was that I tried to install mysqlclient==1.4.2.post1
and it keeps throwing mysql_config not found error.
This is the steps I took to solve the issue.
brew unlink mysql
) - brew install mysql-connector-c
# Create options
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"
brew info openssl
- this will give you more information on what needs to be done about putting openssl in PATHecho 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"
I found a post suggesting a solution for that. It's about to run:
svn resolve --accept working <YourPath>
which will claim the local version files as OK.
You can run it for single file or entire project catalogues.
Another option is instanceof:
Object o =...
if (o instanceof Number) {
double d = ((Number)o).doubleValue(); //this cast is safe
}
In case you want to deeply iterate into a complex (nested) object for each key & value, you can do so using Object.keys():
const iterate = (obj) => {
Object.keys(obj).forEach(key => {
console.log(`key: ${key}, value: ${obj[key]}`)
if (typeof obj[key] === 'object') {
iterate(obj[key])
}
})
}
use value
instead of query
(must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):
select
xt.Id
, x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
XmlTest xt
cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)
Why not try MySQL GUI Tools? It's light, and does its job well.
You could use the encodeURIComponent
to safely URL encode parts of a query string:
var array = JSON.stringify([ 'foo', 'bar' ]);
var url = 'http://example.com/?data=' + encodeURIComponent(array);
or if you are sending this as an AJAX request:
var array = JSON.stringify([ 'foo', 'bar' ]);
$.ajax({
url: 'http://example.com/',
type: 'GET',
data: { data: array },
success: function(result) {
// process the results
}
});
There's an easy way to produce this error:
$joe = null;
$joe->anything();
Will render the error:
Fatal error: Call to a member function
anything()
on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23
It would be a lot better if PHP would just say,
Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define
anything()
in on line <##>.
Usually you have build your class so that $joe
is not defined in the constructor or
you can add some extra information to your exception in your class and then when you catch the exception you can control your custom information to identify your exception
this.Data["mykey"]="keyvalue"; //you can add any type of data if you want
and then you can get your value
string mystr = (string) err.Data["mykey"];
like that for more information: http://msdn.microsoft.com/en-us/library/system.exception.data.aspx
You could use LINQBridge (MIT Licensed) to add support for lambda expressions to C# 2.0:
With Studio's multi-targeting and LINQBridge, you'll be able to write local (LINQ to Objects) queries using the full power of the C# 3.0 compiler—and yet your programs will require only Framework 2.0.
Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!
<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">
<input type="submit" name="scheduled" value="Schedule Emails">
<input type="submit" name="single" value="Email Now">
</form>
twosubmits.php
<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}
if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.
Using this
setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));
But this always work in any size:
setSize(width + 14, height + 7);
If you don't want the border to border, and only want the white area, here:
setSize(width + 16, height + 39);
Also this only works on Windows 10, for MacOS users, use @ben's answer.
You can also get all fragments like this:
For v4 fragmets
List<Fragment> allFragments = getSupportFragmentManager().getFragments();
For app.fragment
List<Fragment> allFragments = getFragmentManager().getFragments();
As has been mentioned in other answers, there is no pure HTML5 way to do this.
If you are already using JQuery, then this should do what you need:
$(document).ready(function() {_x000D_
$('#ourForm').submit(function(e){_x000D_
var form = this;_x000D_
e.preventDefault();_x000D_
// Check Passwords are the same_x000D_
if( $('#pass1').val()==$('#pass2').val() ) {_x000D_
// Submit Form_x000D_
alert('Passwords Match, submitting form');_x000D_
form.submit();_x000D_
} else {_x000D_
// Complain bitterly_x000D_
alert('Password Mismatch');_x000D_
return false;_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="ourForm">_x000D_
<input type="password" name="password" id="pass1" placeholder="Password" required>_x000D_
<input type="password" name="password" id="pass2" placeholder="Repeat Password" required>_x000D_
<input type="submit" value="Go">_x000D_
</form>
_x000D_
Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$
and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready
$(document).ready(function() {
$('selectorForTextbox').bind('keyup', function(e) {
if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
$(this).addClass('invalid');
} else {
$(this).removeClass('invalid');
}
});
});
Here's a JSFiddle of this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.
The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.
A simple as that :
<a href="#" class="btn btn-success" role="button">link</a>
Just add "class="btn btn-success" & role=button
try this css:
/* Show in default resolution screen*/
#container2 {
width: 960px;
position: relative;
margin:0 auto;
line-height: 1.4em;
}
/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */
@media only screen and (max-width: 479px){
#container2 { width: 90%; }
}
Here the demo: http://jsfiddle.net/ongisnade/CG9WN/
For Syntactic Similarity There can be 3 easy ways of detecting similarity.
For Semantic Similarity One can use BERT Embedding and try a different word pooling strategies to get document embedding and then apply cosine similarity on document embedding.
An advanced methodology can use BERT SCORE to get similarity.
Research Paper Link: https://arxiv.org/abs/1904.09675
$('#serialize').click(function () {_x000D_
$('#out').text(_x000D_
$('form').serialize()_x000D_
);_x000D_
});_x000D_
_x000D_
$('#exclude').change(function () {_x000D_
if ($(this).is(':checked')) {_x000D_
$('[name=age]').attr('form', 'fake-form-id');_x000D_
} else {_x000D_
$('[name=age]').removeAttr('form'); _x000D_
}_x000D_
_x000D_
$('#serialize').click();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/">_x000D_
<input type="text" value="John" name="name">_x000D_
<input type="number" value="100" name="age">_x000D_
</form>_x000D_
_x000D_
<input type="button" value="serialize" id="serialize">_x000D_
<label for="exclude"> _x000D_
<input type="checkbox" value="exclude age" id="exclude">_x000D_
exlude age_x000D_
</label>_x000D_
_x000D_
<pre id="out"></pre>
_x000D_
Try passing columns of the DataFrame
directly to matplotlib, as in the examples below, instead of extracting them as numpy arrays.
df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
In [5]: df
Out[5]:
col1 col2 col3
0 -1.000075 -0.759910 100
1 0.510382 0.972615 200
2 1.872067 -0.731010 500
3 0.131612 1.075142 1000
4 1.497820 0.237024 1700
plt.scatter(df.col1, df.col2, s=df.col3)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=df.col3)
colors = np.where(df.col3 > 300, 'r', 'k')
plt.scatter(df.col1, df.col2, s=120, c=colors)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=120, c=colors)
However, the easiest way I've found to create a scatter plot with legend is to call plt.scatter
once for each point type.
cond = df.col3 > 300
subset_a = df[cond].dropna()
subset_b = df[~cond].dropna()
plt.scatter(subset_a.col1, subset_a.col2, s=120, c='b', label='col3 > 300')
plt.scatter(subset_b.col1, subset_b.col2, s=60, c='r', label='col3 <= 300')
plt.legend()
From what I can tell, matplotlib simply skips points with NA x/y coordinates or NA style settings (e.g., color/size). To find points skipped due to NA, try the isnull
method: df[df.col3.isnull()]
To split a list of points into many types, take a look at numpy select
, which is a vectorized if-then-else implementation and accepts an optional default value. For example:
df['subset'] = np.select([df.col3 < 150, df.col3 < 400, df.col3 < 600],
[0, 1, 2], -1)
for color, label in zip('bgrm', [0, 1, 2, -1]):
subset = df[df.subset == label]
plt.scatter(subset.col1, subset.col2, s=120, c=color, label=str(label))
plt.legend()
This is an old post but I'm chiming in because (as Narem briefly mentioned) a few of the printf-like features are available with the console.log
formatters. In the case of the question, you can benefit from the string, number or json formatters for your data.
Examples:
console.log("Quantity %s, Price: %d", data.quantity-row_122, data.price-row_122);
console.log("Quantity and Price Data %j", data);
I have solution without adapter. Transient map converted to xml-elements and vise versa:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "SchemaBasedProperties")
public class SchemaBasedProperties
{
@XmlTransient
Map<String, Map<String, String>> properties;
@XmlAnyElement(lax = true)
List<Object> xmlmap;
public Map<String, Map<String, String>> getProperties()
{
if (properties == null)
properties = new LinkedHashMap<String, Map<String, String>>(); // I want same order
return properties;
}
boolean beforeMarshal(Marshaller m)
{
try
{
if (properties != null && !properties.isEmpty())
{
if (xmlmap == null)
xmlmap = new ArrayList<Object>();
else
xmlmap.clear();
javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = db.newDocument();
org.w3c.dom.Element element;
Map<String, String> attrs;
for (Map.Entry<String, Map<String, String>> it: properties.entrySet())
{
element = doc.createElement(it.getKey());
attrs = it.getValue();
if (attrs != null)
for (Map.Entry<String, String> at: attrs.entrySet())
element.setAttribute(at.getKey(), at.getValue());
xmlmap.add(element);
}
}
else
xmlmap = null;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
void afterUnmarshal(Unmarshaller u, Object p)
{
org.w3c.dom.Node node;
org.w3c.dom.NamedNodeMap nodeMap;
String name;
Map<String, String> attrs;
getProperties().clear();
if (xmlmap != null)
for (Object xmlNode: xmlmap)
if (xmlNode instanceof org.w3c.dom.Node)
{
node = (org.w3c.dom.Node) xmlNode;
nodeMap = node.getAttributes();
name = node.getLocalName();
attrs = new HashMap<String, String>();
for (int i = 0, l = nodeMap.getLength(); i < l; i++)
{
node = nodeMap.item(i);
attrs.put(node.getNodeName(), node.getNodeValue());
}
getProperties().put(name, attrs);
}
xmlmap = null;
}
public static void main(String[] args)
throws Exception
{
SchemaBasedProperties props = new SchemaBasedProperties();
Map<String, String> attrs;
attrs = new HashMap<String, String>();
attrs.put("ResId", "A_LABEL");
props.getProperties().put("LABEL", attrs);
attrs = new HashMap<String, String>();
attrs.put("ResId", "A_TOOLTIP");
props.getProperties().put("TOOLTIP", attrs);
attrs = new HashMap<String, String>();
attrs.put("Value", "hide");
props.getProperties().put("DISPLAYHINT", attrs);
javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext.newInstance(SchemaBasedProperties.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(props, new java.io.File("test.xml"));
Unmarshaller unmarshaller = jc.createUnmarshaller();
props = (SchemaBasedProperties) unmarshaller.unmarshal(new java.io.File("test.xml"));
System.out.println(props.getProperties());
}
}
My output as espected:
<SchemaBasedProperties>
<LABEL ResId="A_LABEL"/>
<TOOLTIP ResId="A_TOOLTIP"/>
<DISPLAYHINT Value="hide"/>
</SchemaBasedProperties>
{LABEL={ResId=A_LABEL}, TOOLTIP={ResId=A_TOOLTIP}, DISPLAYHINT={Value=hide}}
You can use element name/value pair. I need attributes... Have fun!
If you are using Spring Security ver >= 4.2 you can use Spring Security's native support instead of including Apache's:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
The example above was copied from a Spring blog post in which you also can find information about how to configure CORS on a controller, specific controller methods, etc. Moreover, there is also XML configuration examples as well as Spring Boot integration.
div {
display: flex;
flex-direction: row-reverse;
}
I took hhafez code and added a memory test:
private static void test() {
Runtime runtime = Runtime.getRuntime();
long memory;
...
memory = runtime.freeMemory();
// for loop code
memory = memory-runtime.freeMemory();
I run this separately for each approach, the '+' operator, String.format and StringBuilder (calling toString()), so the memory used will not be affected by other approaches. I added more concatenations, making the string as "Blah" + i + "Blah"+ i +"Blah" + i + "Blah".
The result are as follow (average of 5 runs each):
Approach Time(ms) Memory allocated (long)
'+' operator 747 320,504
String.format 16484 373,312
StringBuilder 769 57,344
We can see that String '+' and StringBuilder are practically identical time-wise, but StringBuilder is much more efficient in memory use. This is very important when we have many log calls (or any other statements involving strings) in a time interval short enough so the Garbage Collector won't get to clean the many string instances resulting of the '+' operator.
And a note, BTW, don't forget to check the logging level before constructing the message.
Conclusions:
There is no method append()
on arrays. Instead as already suggested a List object can service the need for dynamically inserting elements eg.
List<String> where = new ArrayList<String>();
where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
Or if you are really keen to use an array:
String[] where = new String[]{
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
};
but then this is a fixed size and no elements can be added.
In Visual Studio, you can't just open a .cpp
file and expect it to run. You must create a project first, or open the .cpp in some existing project.
In your case, there is no project, so there is no project to build.
Go to File --> New --> Project --> Visual C++ --> Win32 Console Application
. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".
Then, You can add .cpp
files you created outside the Visual Studio by right clicking in the Solution explorer
on folder icon "Source" and Add->Existing Item.
Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.
Then you can press ctrl+F5 to compile without debugging and can see output on console window.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect
:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn
from the console by doing this:
indirect("imported_fn()");
Using eval
was my first thought, but it doesn't work. My hypothesis is that calling eval
from the console remains in the context of console, and we need to execute in the context of the module.
very fast way , this method works very quickly:
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
Actually it is possible:
Header('Location: '.$_SERVER['PHP_SELF']);
Exit(); //optional
And it will reload the same page.
How about a software solution:
Install SSH server on the application server. Then, use socket tunnel to create a link between your local port and the remote port on the application server. You can use ssh client tools to do so. Have your client application connect to your mapped local port instead. Then, you can break the socket tunnel at will to simulate the connection timeout.
You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:
JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
Simple line:
bodyDoc.LoadXml(new MemoryStream(Encoding.Unicode.GetBytes(body)));
Another interesting solution would be:
DESTINY=[Give the output that you intend]
# Don't forget to change from .ZIP to .zip.
# In my case the files were in .ZIP.
# The echo were for debug purpose.
find . -name "*.ZIP" | while read filename; do
ADDRESS=$filename
#echo "Address: $ADDRESS"
BASENAME=`basename $filename .ZIP`
#echo "Basename: $BASENAME"
unzip -d "$DESTINY$BASENAME" "$ADDRESS";
done;
Declaring a PRIMARY KEY
or UNIQUE
constraint causes SQL Server to automatically create an index.
An unique index can be created without matching a constraint, but a constraint (either primary key or unique) cannot exist without having a unique index.
From here, the creation of a constraint will:
and at the same time dropping the constraint will drop the associated index.
So, is there actual difference between a PRIMARY KEY
or UNIQUE INDEX
:
NULL
values are not allowed in PRIMARY KEY
, but allowed in UNIQUE
index; and like in set operators (UNION, EXCEPT, INTERSECT), here NULL = NULL
which means that you can have only one value as two NULL
s are find as duplicates of each other;PRIMARY KEY
may exists per table while 999 unique indexes can be createdPRIMARY KEY
constraint is created, it is created as clustered unless there is already a clustered index on the table or NONCLUSTERED
is used in its definition; when UNIQUE
index is created, it is created as NONCLUSTERED
unless it is not specific to be CLUSTERED
and such already does not exist;I think this sample explains the difference between the styles:
james@bodacious-wired:~$cat test.py
#!/usr/bin/env python
class MyClass:
element1 = "Hello"
def __init__(self):
self.element2 = "World"
obj = MyClass()
print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
File "./test.py", line 17, in <module>
print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'
element1 is bound to the class, element2 is bound to an instance of the class.
Seems like you use Angular 4.3 version, I also faced with same problem. Use Angular 4.0.1 and post with code by @trichetricheand and it will work. I am also not sure how to solve it on Angular 4.3 :S
In your case, try:
input.middle:focus {
outline-width: 0;
}
Or in general, to affect all basic form elements:
input:focus,
select:focus,
textarea:focus,
button:focus {
outline: none;
}
In the comments, Noah Whitmore suggested taking this even further to support elements that have the contenteditable
attribute set to true
(effectively making them a type of input element). The following should target those as well (in CSS3 capable browsers):
[contenteditable="true"]:focus {
outline: none;
}
Although I wouldn't recommend it, for completeness' sake, you could always disable the focus outline on everything with this:
*:focus {
outline: none;
}
Keep in mind that the focus outline is an accessibility and usability feature; it clues the user into what element is currently focused.
You can use following methods to get current date in milliseconds.
[[NSDate date] timeIntervalSince1970];
OR
double CurrentTime = CACurrentMediaTime();
your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.
Both should work.
/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2
/node/text()[1] - should return Text1
/node/text()[2] - should return text2
lines = bigstring.split('\n')
lines = [line for line in lines if line.strip()]
Iterables are nicer:
const matches = (text, pattern) => ({
[Symbol.iterator]: function * () {
const clone = new RegExp(pattern.source, pattern.flags);
let match = null;
do {
match = clone.exec(text);
if (match) {
yield match;
}
} while (match);
}
});
Usage in a loop:
for (const match of matches('abcdefabcdef', /ab/g)) {
console.log(match);
}
Or if you want an array:
[ ...matches('abcdefabcdef', /ab/g) ]
In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:
import pymongo
from random import randrange
docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]
coll = pymongo.MongoClient().test_db.grades
coll.insert_many(docs)
Using aggregate:
%timeit -n1 -r1 list(coll.aggregate([
{
'$project': {
'diff': {'$subtract': ['$Grade1', '$Grade2']},
'Grade1': 1,
'Grade2': 1
}
},
{
'$match': {'diff': {'$gt': 0}}
}
]))
1 loop, best of 1: 192 ms per loop
Using find and $where:
%timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))
1 loop, best of 1: 4.54 s per loop
Simply use $(":input")
Example disabling all inputs (textarea, input text, etc):
$(":input").prop("disabled", true);
_x000D_
<form>_x000D_
<textarea>Tetarea</textarea>_x000D_
<input type="text" value="Text">_x000D_
<label><input type="checkbox"> Checkbox</label>_x000D_
</form>_x000D_
_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
_x000D_
I know this was an old answer, but i would like to share my simple solution.
give style="margin-top:5px"
<div style="margin-top:5px">
div 1
</div>
<div style="margin-top:5px">
div2 elements
</div>
div3 elements
There is a lot of hate for this pattern in Java. However, an interface of static constants does sometimes have value. You need to basically fulfill the following conditions:
The concepts are part of the public interface of several classes.
Their values might change in future releases.
For example, suppose that you are writing an extension to a hypothetical query language. In this extension you are going to expand the language syntax with some new operations, which are supported by an index. E.g. You are going to have a R-Tree supporting geospatial queries.
So you write a public interface with the static constant:
public interface SyntaxExtensions {
// query type
String NEAR_TO_QUERY = "nearTo";
// params for query
String POINT = "coordinate";
String DISTANCE_KM = "distanceInKm";
}
Now later, a new developer thinks he needs to build a better index, so he comes and builds an R* implementation. By implementing this interface in his new tree he guarantees that the different indexes will have identical syntax in the query language. Moreover, if you later decided that "nearTo" was a confusing name, you could change it to "withinDistanceInKm", and know that the new syntax would be respected by all your index implementations.
PS: The inspiration for this example is drawn from the Neo4j spatial code.
Use BigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP)
when you want to round up to the 2 decimal points for cents. Be aware of rounding off error when you do calculations though. You need to be consistent when you will be doing the rounding of money value. Either do the rounding right at the end just once after all calculations are done, or apply rounding to each value before doing any calculations. Which one to use would depend on your business requirement, but generally, I think doing rounding right at the end seems to make a better sense to me.
Use a String
when you construct BigDecimal
for money value. If you use double
, it will have a trailing floating point values at the end. This is due to computer architecture regarding how double
/float
values are represented in binary format.
In theory, there's nothing preventing you from sending a request body in a GET
request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET
payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.
However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.
The simple option is to use POST
instead of GET
as recommended by other answers. Since POST
is not standardized by HTTP, you'll have to document how exactly that's supposed to work.
Another option, which I prefer, is to implement your application assuming the GET
payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override
, which is a popular convention for clients to emulate HTTP methods with POST
. So, if a client has a broken implementation, it can write the GET
request as a POST
, sending the X-HTTP-Method-Override: GET
method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.
This is simple way to Display Div using:-
$("#musicinfo").show(); //or
$("#musicinfo").css({'display':'block'}); //or
$("#musicinfo").toggle("slow"); //or
$("#musicinfo").fadeToggle(); //or
I agree. Once it is uploaded to somewhere the user's browser can access then it is pretty easy to get the size. As you need to wait for the image to load you'll want to hook into the onload
event for img
.
var width, height;
var img = document.createElement("img");
img.onload = function() {
// `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
// The natural size is the actual image size regardless of rendering.
// The 'normal' width/height are for the **rendered** size.
width = img.naturalWidth || img.width;
height = img.naturalHeight || img.height;
// Do something with the width and height
}
// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";
sometime you missed some file like I missed my one file rt.java
so better to check yours .........
C:\Program Files\Java\jdk1.8.0_112\jre\lib
I like the "evaluating your expression one additional time before execution" answer, and would like to clarify with another example.
var="\"par1 par2\""
echo $var # prints nicely "par1 par2"
function cntpars() {
echo " > Count: $#"
echo " > Pars : $*"
echo " > par1 : $1"
echo " > par2 : $2"
if [[ $# = 1 && $1 = "par1 par2" ]]; then
echo " > PASS"
else
echo " > FAIL"
return 1
fi
}
# Option 1: Will Pass
echo "eval \"cntpars \$var\""
eval "cntpars $var"
# Option 2: Will Fail, with curious results
echo "cntpars \$var"
cntpars $var
The Curious results in Option 2 are that we would have passed 2 parameters as follows:
"value
content"
How is that for counter intuitive? The additional eval
will fix that.
Adapted from https://stackoverflow.com/a/40646371/744133
could also happen when your local time is off (e.g. before certificate validation time), this was the case in my error...
Create a function like so:
CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE @result INT
EXEC master.dbo.xp_fileexist @path, @result OUTPUT
RETURN cast(@result as bit)
END;
GO
Edit your table and add a computed column (IsExists BIT). Set the expression to:
dbo.fn_FileExists(filepath)
Then just select:
SELECT * FROM dbo.MyTable where IsExists = 1
Update:
To use the function outside a computed column:
select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable
Update:
If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.
And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.
You can also use this direct command line to open the Advanced System Properties:
sysdm.cpl
Then go to the Advanced Tab -> Environment Variables
JObject implements IDictionary, so you can use it that way. For ex,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
So the final json will be
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
You can also use dynamic
keyword
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
The best use case I can think of is in caching AJAX responses. Here's a modified example from Rebecca Murphey's intro post on the topic:
var cache = {};
function getData( val ){
// return either the cached value or jqXHR object wrapped Promise
return $.when(
cache[ val ] ||
$.ajax('/foo/', {
data: { value: val },
dataType: 'json',
success: function( resp ){
cache[ val ] = resp;
}
})
);
}
getData('foo').then(function(resp){
// do something with the response, which may
// or may not have been retrieved using an
// XHR request.
});
Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when
/.then
doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then()
handler in both cases. jQuery.when()
handles a non-Promise/Deferred as a Completed one, immediately executing any .done()
or .then()
on the chain.
Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.
Another real world example using the $.when
helper:
$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {
$(tmpl) // create a jQuery object out of the template
.tmpl(data) // compile it
.appendTo("#target"); // insert it into the DOM
});
This code returns an object with all properties that have a different value and also values of both objects. Useful to logging the difference.
var allkeys = _.union(_.keys(obj1), _.keys(obj2));
var difference = _.reduce(allkeys, function (result, key) {
if ( !_.isEqual(obj1[key], obj2[key]) ) {
result[key] = {obj1: obj1[key], obj2: obj2[key]}
}
return result;
}, {});
readonly="readonly"
is xhtml syntax. In xhtml boolean attributes are written this way. In xhtml 'attribute minimization' (<input type="checkbox" checked>
) isn't allowed, so this is the valid way to include boolean attributes in xhtml. See this page for more.information.
If your document type is xhtml transitional or strict and you want to validate it, use readonly="readonly
otherwise readonly
is sufficient.
Implementing the TimeZone class to set the timezone to the Calendar takes care of the daylight savings.
java.util.TimeZone represents a time zone offset, and also figures out daylight savings.
sample code:
TimeZone est_timeZone = TimeZoneIDProvider.getTimeZoneID(TimeZoneID.US_EASTERN).getTimeZone();
Calendar enteredCalendar = Calendar.getInstance();
enteredCalendar.setTimeZone(est_timeZone);
If u want to use display=block it will make the content reader jump, so instead of using display you can set the left attribute to a negative value which does not exist in your html page to be displayed but actually it do.
I hope you must be understanding my point, if I am unable to make u understand u can message me back.
There is no standard naming of keys in JSON. According to the Objects section of the spec:
The JSON syntax does not impose any restrictions on the strings used as names,...
Which means camelCase or snake_case should work fine.
Imposing a JSON naming convention is very confusing. However, this can easily be figured out if you break it down into components.
Programming language for generating JSON
JSON itself has no standard naming of keys
Programming language for parsing JSON
snake_case will still make sense for those with Java entries because the existing JSON libraries for Java are using only methods to access the keys instead of using the standard dot.syntax. This means that it wouldn't hurt that much for Java to access the snake_cased keys in comparison to the other programming language which can do the dot.syntax.
Example for Java's org.json
package
JsonObject.getString("snake_cased_key")
Example for Java's com.google.gson
package
JsonElement.getAsString("snake_cased_key")
Choosing the right JSON naming convention for your JSON implementation depends on your technology stack. There are cases where one can use snake_case, camelCase, or any other naming convention.
Another thing to consider is the weight to be put on the JSON-generator vs the JSON-parser and/or the front-end JavaScript. In general, more weight should be put on the JSON-generator side rather than the JSON-parser side. This is because business logic usually resides on the JSON-generator side.
Also, if the JSON-parser side is unknown then you can declare what ever can work for you.
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).
I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:
sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF
Wrapping components with braces if no default exports:
import {MyNavbar} from './comp/my-navbar.jsx';
or import multiple components from single module file
import {MyNavbar1, MyNavbar2} from './module';
why making life hard-
PreparedStatement pstmt = conn.prepareStatement("select * from employee where id in ("+ StringUtils.join(arraylistParameter.iterator(),",") +)");
Here is a quick example:
public class One {
/**
* @param args
*/
public static void main(String[] args) {
double a = 4.56777;
System.out.println( new Float( Math.round(a)) );
}
}
the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double
values and provides whole long
values
Regards
It's actually quite easy, assuming you have an openssl installation handy. (What platform are you on?)
Assuming you're on linux/solaris/mac os/x, Van's Apache SSL/TLS mini-HOWTO has an excellent walkthrough that I won't reproduce here.
However, the executive summary is that you have to create a self-signed certificate. Since you're running apache for localhost presumably for development (i.e. not a public web server), you'll know that you can trust the self-signed certificate and can ignore the warnings that your browser will throw at you.
You don't have to change style for it. After setting up your toolbar as actionbar, You can code like this
android.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
android.getSupportActionBar().setHomeAsUpIndicator(R.drawable.back);
//here back is your drawable image
But You cannot change color of back arrow by this method
You can set content view (or design) of an activity. For example you can do it like this too :
public void onCreate(Bundle savedinstanceState) {
super.onCreate(savedinstanceState);
Button testButon = new Button(this);
setContentView(testButon);
}
Also watch this tutorial too.
For me, I had things unnecessarily split into separate folders. I'm running plotly dash and I had my Procfile
, and Pipfile
(and lock) together, but separate from the other features of my app (run.py
and app.py
, the actual content of the pages being used was in a subfolder). So joining much of that together repaired my H10 error
Here is usage of Math.PI
to find circumference of circle and Area
First we take Radius as a string in Message Box and convert it into integer
public class circle {
public static void main(String[] args) {
// TODO code application logic here
String rad;
float radius,area,circum;
rad = JOptionPane.showInputDialog("Enter the Radius of circle:");
radius = Integer.parseInt(rad);
area = (float) (Math.PI*radius*radius);
circum = (float) (2*Math.PI*radius);
JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
}
}
before .import command, type ".mode csv"
Make sure drush is installed (you may also need to make sure the dblog module is enabled) and use:
drush watchdog-show --tail
Available in drush v8 and below.
This will give you a live look at the logs from your console.
With the arrival of ES6 with sets and splat operator (at the time of being works only in Firefox, check compatibility table), you can write the following cryptic one liner:
var a = [34, 35, 45, 48, 49];_x000D_
var b = [48, 55];_x000D_
var union = [...new Set([...a, ...b])];_x000D_
console.log(union);
_x000D_
Little explanation about this line: [...a, ...b]
concatenates two arrays, you can use a.concat(b)
as well. new Set()
create a set out of it and thus your union. And the last [...x]
converts it back to an array.
require('url').parse('/status?name=ryan', {parseQueryString: true}).query
returns
{ name: 'ryan' }
You need to use:
:%s/,/^M/g
To get the ^M
character, press Ctrl + v followed by Enter.
You are using a path element, why don't you just give the path a curve? See here for how to make curves using path elements: http://www.w3.org/TR/SVG/paths.html#PathDataCurveCommands
Assuming my-app is a subdirectory under the current directory. The $LASTEXITCODE should be there from the last command:
.\my-app\my-fle.bat
If it was from a fileshare:
\\server\my-file.bat
I updated extension method from @AminRostami to return IAsyncEnumerable (so LINQ filtering can be applied) and it's mapping Model Column name of records returned from DB to models (Tested with EF Core 5):
Extension itself:
public static class QueryHelper
{
private static string GetColumnName(this MemberInfo info)
{
List<ColumnAttribute> list = info.GetCustomAttributes<ColumnAttribute>().ToList();
return list.Count > 0 ? list.Single().Name : info.Name;
}
/// <summary>
/// Executes raw query with parameters and maps returned values to column property names of Model provided.
/// Not all properties are required to be present in model (if not present - null)
/// </summary>
public static async IAsyncEnumerable<T> ExecuteQuery<T>(
[NotNull] this DbContext db,
[NotNull] string query,
[NotNull] params SqlParameter[] parameters)
where T : class, new()
{
await using DbCommand command = db.Database.GetDbConnection().CreateCommand();
command.CommandText = query;
command.CommandType = CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
await db.Database.OpenConnectionAsync();
await using DbDataReader reader = await command.ExecuteReaderAsync();
List<PropertyInfo> lstColumns = new T().GetType()
.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
while (await reader.ReadAsync())
{
T newObject = new();
for (int i = 0; i < reader.FieldCount; i++)
{
string name = reader.GetName(i);
PropertyInfo prop = lstColumns.FirstOrDefault(a => a.GetColumnName().Equals(name));
if (prop == null)
{
continue;
}
object val = await reader.IsDBNullAsync(i) ? null : reader[i];
prop.SetValue(newObject, val, null);
}
yield return newObject;
}
}
}
Model used (note that Column names are different than actual property names):
public class School
{
[Key] [Column("SCHOOL_ID")] public int SchoolId { get; set; }
[Column("CLOSE_DATE", TypeName = "datetime")]
public DateTime? CloseDate { get; set; }
[Column("SCHOOL_ACTIVE")] public bool? SchoolActive { get; set; }
}
Actual usage:
public async Task<School> ActivateSchool(int schoolId)
{
// note that we're intentionally not returning "SCHOOL_ACTIVE" with select statement
// this might be because of certain IF condition where we return some other data
return await _context.ExecuteQuery<School>(
"UPDATE SCHOOL SET SCHOOL_ACTIVE = 1 WHERE SCHOOL_ID = @SchoolId; SELECT SCHOOL_ID, CLOSE_DATE FROM SCHOOL",
new SqlParameter("@SchoolId", schoolId)
).SingleAsync();
}
For completeness - adding to accepted answer above - in case you are interested in any sibling regardless of the element type you can use variation:
following-sibling::*
There are two common approaches. First, you can pass System.Type
object GetColumnValue(string columnName, Type type)
{
// Here, you can check specific types, as needed:
if (type == typeof(int)) { // ...
This would be called like: int val = (int)GetColumnValue(columnName, typeof(int));
The other option would be to use generics:
T GetColumnValue<T>(string columnName)
{
// If you need the type, you can use typeof(T)...
This has the advantage of avoiding the boxing and providing some type safety, and would be called like: int val = GetColumnValue<int>(columnName);
$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');
Your code has two problems:
.IsBestAnswe
does not match what you thoughtaddClass()
, not addclass()
.Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer')
part to add only:
$('.IsBestAnswer').addClass('bestanswer');
You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer
vs. bestanswer
).
Have a look at the AlertDialog docs. As it states, to add a custom view to your alert dialog you need to find the frameLayout and add your view to that like so:
FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
Most likely you are going to want to create a layout xml file for your view, and inflate it:
LayoutInflater inflater = getLayoutInflater();
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false);
If the issue is that your SpringBootApplication/Configuration you are bringing in is component scanning the package your test configurations are in, you can actually remove the @Configuration annotation from the test configurations and you can still use them in the @SpringBootTest annotations. For example, if you have a class Application that is your main configuration and a class TestConfiguration that is a configuration for certain, but not all tests, you can set up your classes as follows:
@Import(Application.class) //or the specific configurations you want
//(Optional) Other Annotations that will not trigger an autowire
public class TestConfiguration {
//your custom test configuration
}
And then you can configure your tests in one of two ways:
With the regular configuration:
@SpringBootTest(classes = {Application.class}) //won't component scan your configuration because it doesn't have an autowire-able annotation
//Other annotations here
public class TestThatUsesNormalApplication {
//my test code
}
With the test custom test configuration:
@SpringBootTest(classes = {TestConfiguration.class}) //this still works!
//Other annotations here
public class TestThatUsesCustomTestConfiguration {
//my test code
}
Just had this issue with an Outlook client going through a Exchange server to an external address on Windows XP. Clearing the temp files seemed to do the trick.
I include definitions for computed columns
select 'CREATE TABLE [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END, name
from sysobjects so
cross apply
(SELECT
case when comps.definition is not null then ' ['+column_name+'] AS ' + comps.definition
else
' ['+column_name+'] ' + data_type +
case
when data_type like '%text' or data_type in ('image', 'sql_variant' ,'xml')
then ''
when data_type in ('float')
then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ')'
when data_type in ('datetime2', 'datetimeoffset', 'time')
then '(' + cast(coalesce(datetime_precision, 7) as varchar(11)) + ')'
when data_type in ('decimal', 'numeric')
then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ',' + cast(coalesce(numeric_scale, 0) as varchar(11)) + ')'
when (data_type like '%binary' or data_type like '%char') and character_maximum_length = -1
then '(max)'
when character_maximum_length is not null
then '(' + cast(character_maximum_length as varchar(11)) + ')'
else ''
end + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=so.name
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(so.name) as varchar) + ',' +
cast(ident_incr(so.name) as varchar) + ')'
else ''
end + ' ' +
(case when information_schema.columns.IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END
end + ', '
from information_schema.columns
left join sys.computed_columns comps
on OBJECT_ID(information_schema.columns.TABLE_NAME)=comps.object_id and information_schema.columns.COLUMN_NAME=comps.name
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
left join
information_schema.table_constraints tc
on tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
cross apply
(select '[' + Column_Name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY
ORDINAL_POSITION
FOR XML PATH('')) j (list)
where xtype = 'U'
AND name NOT IN ('dtproperties')
In my case my object also had property which was array of files. Since they are binary they should be dealt differently - index doesn't need to be part of the key. So i modified @Vladimir Novopashin's and @developer033's answer:
export function convertToFormData(data, formData, parentKey) {
if(data === null || data === undefined) return null;
formData = formData || new FormData();
if (typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
Object.keys(data).forEach(key =>
convertToFormData(data[key], formData, (!parentKey ? key : (data[key] instanceof File ? parentKey : `${parentKey}[${key}]`)))
);
} else {
formData.append(parentKey, data);
}
return formData;
}
I had the unresolved R problem because of the same image.png file in two places. One in res>anim and the same file in res>drawable-hdpi. This caused R to become unresolved. I created the problem by making a splash screen image and repeatedly moving it from the Moray graphics directory to the Android project directly. I must have dropped it into res>anim folder by accident. I fixed the problem by removing the duplicate image file from the res>anim folder and Android studio corrected itself.
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
First: reload(sys)
and setting some random default encoding just regarding the need of an output terminal stream is bad practice. reload
often changes things in sys which have been put in place depending on the environment - e.g. sys.stdin/stdout streams, sys.excepthook, etc.
The best solution I know for solving the encode problem of print
'ing unicode strings and beyond-ascii str
's (e.g. from literals) on sys.stdout is: to take care of a sys.stdout (file-like object) which is capable and optionally tolerant regarding the needs:
When sys.stdout.encoding
is None
for some reason, or non-existing, or erroneously false or "less" than what the stdout terminal or stream really is capable of, then try to provide a correct .encoding
attribute. At last by replacing sys.stdout & sys.stderr
by a translating file-like object.
When the terminal / stream still cannot encode all occurring unicode chars, and when you don't want to break print
's just because of that, you can introduce an encode-with-replace behavior in the translating file-like object.
Here an example:
#!/usr/bin/env python
# encoding: utf-8
import sys
class SmartStdout:
def __init__(self, encoding=None, org_stdout=None):
if org_stdout is None:
org_stdout = getattr(sys.stdout, 'org_stdout', sys.stdout)
self.org_stdout = org_stdout
self.encoding = encoding or \
getattr(org_stdout, 'encoding', None) or 'utf-8'
def write(self, s):
self.org_stdout.write(s.encode(self.encoding, 'backslashreplace'))
def __getattr__(self, name):
return getattr(self.org_stdout, name)
if __name__ == '__main__':
if sys.stdout.isatty():
sys.stdout = sys.stderr = SmartStdout()
us = u'aouäöü?zß²'
print us
sys.stdout.flush()
The only good reason to change the global default encoding (to UTF-8 only) I think is regarding an application source code decision - and not because of I/O stream encodings issues: For writing beyond-ascii string literals into code without being forced to always use u'string'
style unicode escaping. This can be done rather consistently (despite what anonbadger's article says) by taking care of a Python 2 or Python 2 + 3 source code basis which uses ascii or UTF-8 plain string literals consistently - as far as those strings potentially undergo silent unicode conversion and move between modules or potentially go to stdout. For that, prefer "# encoding: utf-8
" or ascii (no declaration). Change or drop libraries which still rely in a very dumb way fatally on ascii default encoding errors beyond chr #127 (which is rare today).
And do like this at application start (and/or via sitecustomize.py) in addition to the SmartStdout
scheme above - without using reload(sys)
:
...
def set_defaultencoding_globally(encoding='utf-8'):
assert sys.getdefaultencoding() in ('ascii', 'mbcs', encoding)
import imp
_sys_org = imp.load_dynamic('_sys_org', 'sys')
_sys_org.setdefaultencoding(encoding)
if __name__ == '__main__':
sys.stdout = sys.stderr = SmartStdout()
set_defaultencoding_globally('utf-8')
s = 'aouäöü?zß²'
print s
This way string literals and most operations (except character iteration) work comfortable without thinking about unicode conversion as if there would be Python3 only. File I/O of course always need special care regarding encodings - as it is in Python3.
Note: plains strings then are implicitely converted from utf-8 to unicode in SmartStdout
before being converted to the output stream enconding.
I found a solution in How I fixed the MTP issues on Nexus 7.
Another way of fixing this on Windows 8: This problem may happen, because you have the Google ADB driver from the Android SDK installed. Windows will pick the ADB driver over the MTP driver, even when USB debugging is turned off on the Nexus 7. It also comes back when you upgrade from Windows 8 to Windows 8.1. To fix this:
It was confirmed working with the Nexus 7 2013 as well.
In every distribute it has difference files so I write most common ones:
---- CentOS Linux distro
`cat /proc/version`
---- Debian Linux distro
`cat /etc/debian_version`
---- Redhat Linux distro
`cat /etc/redhat-release`
---- Ubuntu Linux distro
`cat /etc/issue` or `cat /etc/lsb-release`
in last one /etc/issue didn't exist so I tried the second one and it returned the right answer
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
If you transferred these files through disk or other means, it is likely they were not saved properly.
It is not an import problem. You simply call .dropDuplicates()
on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...)
is pyspark.sql.dataframe.DataFrame
, after you apply .collect()
it is a plain Python list
, and lists don't provide dropDuplicates
method. What you want is something like this:
(df1 = sqlContext
.createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
.dropDuplicates())
df1.collect()
EDIT: Note that this method won't work with crontab -e, but only works if you edit /etc/crontab directly. Otherwise, you may get an error like /bin/sh: www-data: command not found
Just before the program name:
*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
I will provide a detailed differences between Visual Studio and Visual Studio Code below.
If you really look at it the most obvious difference is that .NET has been split into two:
All native user interface technologies (Windows Presentation Foundation, Windows Forms, etc.) are part of the framework, not the core.
The "Visual" in Visual Studio (from Visual Basic) was largely synonymous with visual UI (drag & drop WYSIWYG) design, so in that sense, Visual Studio Code is Visual Studio without the Visual!
The second most obvious difference is that Visual Studio tends to be oriented around projects & solutions.
Visual Studio Code:
Visual Studio:
Visual Studio is aimed to be the world’s best IDE (integrated development environment), which provide full stack develop toolsets, including a powerful code completion component called IntelliSense, a debugger which can debug both source code and machine code, everything about ASP.NET development, and something about SQL development.
In the latest version of Visual Studio, you can develop cross-platform application without leaving the IDE. And Visual Studio takes more than 8 GB disk space (according to the components you select).
In brief, Visual Studio is an ultimate development environment, and it’s quite heavy.
Reference: https://www.quora.com/What-is-the-difference-between-Visual-Studio-and-Visual-Studio-Code
Something I did recently, hope it helps. I have a list of dictionaries and wanted to add a value to some existing documents.
for item in my_list:
my_collection.update({"_id" : item[key] }, {"$set" : {"New_col_name" :item[value]}})
You should probably use the ngHref directive along with the ngClick:
<a ng-href='#here' ng-click='go()' >click me</a>
Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
{{msg}}
<a ng-href='#here' ng-click='go()' >click me</a>
<div style='height:1000px'>
<a id='here'></a>
</div>
<h1>here</h1>
</body>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.go = function() {
$scope.msg = 'clicked';
}
});
I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.
** Update **
Here is a demo of the set and get working fine with a service.
http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, sharedProperties) {
$scope.name = 'World';
$scope.go = function(item) {
sharedProperties.setListName(item);
}
$scope.getItem = function() {
$scope.msg = sharedProperties.getListName();
}
});
app.service('sharedProperties', function () {
var list_name = '';
return {
getListName: function() {
return list_name;
},
setListName: function(name) {
list_name = name;
}
};
});
* Edit *
Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.
Install/update RVM with last ruby version
\curl -sSL https://get.rvm.io | bash -s stable
Install bundler
gem install bundler
after this two commands (sudo) gem install ....
started to work