I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.
Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine
<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
<li each="var p in products">${p.Name}</li>
</ul>
<else>
<p>No products available</p>
</else>
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;
Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.
N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.
I think this first failed because you are ordering value which is null. If Delivery is a foreign key associated table then you should include this table first, example below:
var itemList = from t in ctn.Items.Include(x=>x.Delivery)
where !t.Items && t.DeliverySelection
orderby t.Delivery.SubmissionDate descending
select t;
I've adjusted the answer of kd7 a little bit because elem.selectionStart will evaluate to false when the selectionStart is incidentally 0.
function setCaretPosition(elem, caretPos) {
var range;
if (elem.createTextRange) {
range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
elem.focus();
if (elem.selectionStart !== undefined) {
elem.setSelectionRange(caretPos, caretPos);
}
}
}
I like this one-liner, when I'm not using Rails, because then I don't have to make a second hash and hold two sets of data while I'm processing it:
my_hash = { "a" => 1, "b" => "string", "c" => true }
my_hash.keys.each { |key| my_hash[key.to_sym] = my_hash.delete(key) }
my_hash
=> {:a=>1, :b=>"string", :c=>true}
Hash#delete returns the value of the deleted key
They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.
saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html
use,
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); //before
dialog.setContentView(R.layout.logindialog);
Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"
Revised: January 27, 1999
It’s very old, but it is still useful.
If it isn't I could see things heading that way.
I'm working on redoing the website for the company I work for and the designer they hired used a 960px width layout. There is also a 960px grid system that seems to be getting quite popular (http://960.gs/).
I've been out of web stuff for a few years but from what I've read catching up on things it seems 960/980 is about right. For mobile ~320px sticks in my mind, by which 960 is divisible. 960 is also evenly divisible by 2, 3, 4, 5, and 6.
After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code:
//Store your XML Request in a variable
$input_xml = '<AvailRequest>
<Trip>ONE</Trip>
<Origin>BOM</Origin>
<Destination>JFK</Destination>
<DepartDate>2013-09-15</DepartDate>
<ReturnDate>2013-09-16</ReturnDate>
<AdultPax>1</AdultPax>
<ChildPax>0</ChildPax>
<InfantPax>0</InfantPax>
<Currency>INR</Currency>
<PreferredClass>E</PreferredClass>
<Eticket>true</Eticket>
<Clientid>777ClientID</Clientid>
<Clientpassword>*Your API Password</Clientpassword>
<Clienttype>ArzooINTLWS1.0</Clienttype>
<PreferredAirline></PreferredAirline>
</AvailRequest>';
Now I've made a little changes in the above curl_setopt declaration as follows:
$url = "http://59.162.33.102:9301/Avalability";
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
//convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
That's it the code works absolutely fine for me. I really appreciate @hakre & @Lucas For their wonderful support.
This gives you the first few digits of the hash and they are unique enough to use as say a version number.
git rev-parse --short HEAD
To search google using API you should use Google Custom Search, scraping web page is not allowed
In java you can use CustomSearch API Client Library for Java
The maven dependency is:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-customsearch</artifactId>
<version>v1-rev57-1.23.0</version>
</dependency>
Example code searching using Google CustomSearch API Client Library
public static void main(String[] args) throws GeneralSecurityException, IOException {
String searchQuery = "test"; //The query to search
String cx = "002845322276752338984:vxqzfa86nqc"; //Your search engine
//Instance Customsearch
Customsearch cs = new Customsearch.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), null)
.setApplicationName("MyApplication")
.setGoogleClientRequestInitializer(new CustomsearchRequestInitializer("your api key"))
.build();
//Set search parameter
Customsearch.Cse.List list = cs.cse().list(searchQuery).setCx(cx);
//Execute search
Search result = list.execute();
if (result.getItems()!=null){
for (Result ri : result.getItems()) {
//Get title, link, body etc. from search
System.out.println(ri.getTitle() + ", " + ri.getLink());
}
}
}
As you can see you will need to request an api key and setup an own search engine id, cx.
Note that you can search the whole web by selecting "Search entire web" on basic tab settings during setup of cx, but results will not be exactly the same as a normal browser google search.
Currently (date of answer) you get 100 api calls per day for free, then google like to share your profit.
This works for me (mostly).
Put this at the bottom of your page.
<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="application/javascript" src="/script/jquery.browser.js">
</script>
<script type="application/javascript" src="/script/jquery-iframe-auto-height.js">
</script>
<script type="application/javascript">
jQuery('iframe').iframeAutoHeight();
$(window).load(
function() {
jQuery('iframe').iframeAutoHeight();
}
);
// for when content is not html e.g. a PDF
function setIframeHeight() {
$('.iframe_fullHeight').each(
function (i, item) {
item.height = $(document).height();
}
);
};
$(document).ready( function () {
setIframeHeight();
});
$(window).resize( function () {
setIframeHeight();
});
</script>
The first half is from ???, and works when there is html in the iframe.
The second half sets the iframe to page height (not content height), when iframes class is iframe_fullHeight
. You can use this if the content is a PDF or other such like, but you have to set the class. Also can only be used when being full height is appropriate.
Note: for some reason, when it recalculates after window resize, it gets height wrong.
Very easy, just call the function within a specific amount of milliseconds using setTimeout()
setTimeout(myFunction, 2000)
function myFunction() {
alert('Was called after 2 seconds');
}
Or you can even initiate the function inside the timeout, like so:
setTimeout(function() {
alert('Was called after 2 seconds');
}, 2000)
Your memcpy
code is correct.
My guess is you are lacking an include of string.h. So the compiler assumes a wrong prototype of memcpy
and thus the warning.
Anyway, you should just assign the structs for the sake of simplicity (as Joachim Pileborg pointed out).
The control searches for a view in the following order:
As you do not have xxx.cshtml
in those locations, it returns a "view not found" error.
Solution: You can use the complete path of your view:
Like
PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
In case you are running it on Fedora or CentOS, this is what worked for me (PostgreSQL 9.6):
In terminal:
$ sudo visudo -f /etc/sudoers
modify the following text from:
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
to
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/pgsql-9.6/bin
exit, then:
$ printenv PATH
$ sudo su postgres
$ psql
To exit postgreSQL terminal, you need to digit:
$ \q
Source: https://serverfault.com/questions/541847/why-doesnt-sudo-know-where-psql-is#comment623883_541880
Actualy we can use the two providers(GPS & NETWORK). And they just share a public listener:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, (float) 10.0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 90 * 1000, (float) 10.0, listener);
This is necessary because the OnLocationChanged()
method always need to be called in time.
This is a simple, you can use spring boot maven plugin to finish your code deploy.
the plugin config like:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${debug.port}
</jvmArguments>
<profiles>
<profile>test</profile>
</profiles>
<executable>true</executable>
</configuration>
</plugin>
And, the jvmArtuments
is add for you jvm. profiles
will choose a profile to start your app. executable
can make your app driectly run.
and if you add mvnw
to your project, or you have a maven enveriment. You can just call./mvnw spring-boot:run
for mvnw or mvn spring-boot:run
for maven.
I tried %~dp0 in the Start in field and it is working fine in Windows 10 x64
echo "blahblah"> txt.txt
will erase the txt and put blahblah in it's place
echo "blahblah">> txt.txt
will write blahblah on a new line in the txt
I think that both will create a new txt if none exists (I know that the first one does)
Where "txt.txt
" is written above, a file path can be inserted if wanted. e.g. C:\Users\<username>\desktop
, which will put it on their desktop.
I know this thread is old, but i think it's worth mentioning the scenario i found this problem so it can help others.
Suppose you have nested elements like this:
<a href="#" id="profile-avatar-picker">
<span class="fa fa-camera fa-2x"></span>
<input id="avatar-file" name="avatar-file" type="file" style="display: none;" />
</a>
You cannot manipulate the child element events inside the event of its parent because it propagates to itself, making recursive calls until the exception is throwed.
So this code will fail:
$('#profile-avatar-picker').on('click', (e) => {
e.preventDefault();
$('#profilePictureFile').trigger("click");
});
You have two options to avoid this:
Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)
The option you're asking about is for the find
command though, not for bash. From your command line, you can man find
to see the options.
The one you're looking for is -o
for "or":
list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"
That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.
$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt
Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:
$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 one.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 two three.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 foo.bmp
The Bash FAQ has lots of other excellent tips about programming in bash.
You can use the code below.
<script src="http://maps.googleapis.com/maps/api/js?libraries=places" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
//alert("This function is working!");
//alert(place.name);
// alert(place.address_components[0].long_name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
and this part is inside your form:
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />
I hope it helps.
Solved this issue in Eclipse 3.5.2. Two completely identical layouts of which one had the warning. Closed down all tabs and when reopening the warning had disappeared.
Difference between IaaS PaaS & SaaS
In the following tabular format we will be explaining the difference in context of
pizza as a service
Another different answer to an old question. However, I found a implementation made specifically for bootstrap which might prove useful here. Hope this helps anybody who is looking...
Only use Popen
kill method
process = subprocess.Popen(
task.getExecutable(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
process.kill()
Template refs section tells how this has been unified:
ref="myEl"
; :ref=
with a v-for
const myEl = ref(null)
and expose it from setup
The reference carries the DOM element from mounting onwards.
addAccordian(type, data) { console.log(type, data);
let form = this.form;
if (!form.controls[type]) {
let ownerAccordian = new FormArray([]);
const group = new FormGroup({});
ownerAccordian.push(
this.applicationService.createControlWithGroup(data, group)
);
form.controls[type] = ownerAccordian;
} else {
const group = new FormGroup({});
(<FormArray>form.get(type)).push(
this.applicationService.createControlWithGroup(data, group)
);
}
console.log(this.form);
}
x = [10000.21, 22000.32, 10120.54]
Perhaps make a list (comprehension) for the labels, and then apply them "manually".
xlables = [f'{label:,}' for label in x]
plt.xticks(x, xlabels)
Generally speaking, you can update your index mapping using the put mapping api (reference here) :
curl -XPUT 'http://localhost:9200/advert_index/_mapping/advert_type' -d '
{
"advert_type" : {
"properties" : {
//your new mapping properties
}
}
}
'
It's especially useful for adding new fields. However, in your case, you will try to change the location type, which will cause a conflict and prevent the new mapping from being used.
You could use the put mapping api to add another property containing the location as a lat/lon array, but you won't be able to update the previous location field itself.
Finally, you will have to reindex your data for your new mapping to be taken into account.
The best solution would really be to create a new index.
If your problem with creating another index is downtime, you should take a look at aliases to make things go smoothly.
Note: I found this question looking for one of the steps in the answer to how to resize an existing array.
So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.
For anyone else finding this question looking for the same thing I was, it is very simple:
Array.Resize<T>(ref arrayVariable, newSize);
where T is the type, i.e. where arrayVariable is declared:
T[] arrayVariable;
That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.
See the MSDN article for more.
A problem with not putting 'return' explicitly at the end is that if one adds additional statements at the end of the method, suddenly the return value is wrong:
foo <- function() {
dosomething()
}
This returns the value of dosomething()
.
Now we come along the next day and add a new line:
foo <- function() {
dosomething()
dosomething2()
}
We wanted our code to return the value of dosomething()
, but instead it no longer does.
With an explicit return, this becomes really obvious:
foo <- function() {
return( dosomething() )
dosomething2()
}
We can see that there is something strange about this code, and fix it:
foo <- function() {
dosomething2()
return( dosomething() )
}
It's always problematic and often misleading to try and translate constructs and concepts between languages. Casting is no exception. Particularly because Java is a dynamic language and C++ is somewhat different.
All casting in Java, no matter how you do it, is done at runtime. Type information is held at runtime. C++ is a bit more of a mix. You can cast a struct in C++ to another and it's merely a reinterpretation of the bytes that represent those structs. Java doesn't work that way.
Also generics in Java and C++ are vastly different. Don't concern yourself overly with how you do C++ things in Java. You need to learn how to do things the Java way.
Swing vs AWT. Basically AWT came first and is a set of heavyweight UI components (meaning they are wrappers for operating system objects) whereas Swing built on top of AWT with a richer set of lightweight components.
Any serious Java UI work is done in Swing not AWT, which was primarily used for applets.
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}
Here's an example that uses the class:
try {
// Generate a temporary key. In practice, you would save this key.
// See also Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt("Don't tell anybody!");
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}
If it is an Angular application you can simply do this
input.ng-invalid.ng-touched
{
border: 1px solid red !important;
}
For Win7 Acrobat Pro X
Since I did all these without rechecking to see if the problem still existed afterwards, I am not sure which on of these actually fixed the problem, but one of them did. In fact, after doing the #3 and rebooting, it worked perfectly.
FYI: Below is the order in which I stepped through the repair.
Go to Control Panel
> folders options under each of the General
, View
and Search
Tabs
click the Restore Defaults
button and the Reset Folders
button
Go to Internet Explorer
, Tools
> Options
> Advanced
> Reset
( I did not need to delete personal settings)
Open Acrobat Pro X
, under Edit
> Preferences
> General
.
At the bottom of page select Default PDF Handler
. I chose Adobe Pro X
, and click Apply
.
You may be asked to reboot (I did).
Best Wishes
using zlib.h (http://refspecs.linuxbase.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/zlib-crc32-1.html):
#include <zlib.h>
unsigned long crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, (const unsigned char*)data_address, data_len);
Windows 10 home version with latest android studio (Nov/2019):
Enable virtualization from BIOS. If you have a laptop, google how to access the BIOS.
Enable via Windows Features: "Windows Hypervisor Platform". Restart. No need for Hyper-V and Win10 Pro.
Done. Open Android Studio, the annoying warning is gone, emulator starts just fine.
Escape special characters with a backslash. \.
, \*
, \+
, \\d
, and so on. If you are unsure, you may escape any non-alphabetical character whether it is special or not. See the javadoc for java.util.regex.Pattern for further information.
Think of TCP as a dedicated scheduled UPS/FedEx pickup/dropoff of packages between two locations, while UDP is the equivalent of throwing a postcard in a mailbox.
UPS/FedEx will do their damndest to make sure that the package you mail off gets there, and get it there on time. With the post card, you're lucky if it arrives at all, and it may arrive out of order or late (how many times have you gotten a postcard from someone AFTER they've gotten home from the vacation?)
TCP is as close to a guaranteed delivery protocol as you can get, while UDP is just "best effort".
To do what Jesse describes, from a Windows batch file you will need to write:
for /f "delims=" %%a in ('ver') do @set foobar=%%a
But, I instead suggest using Cygwin on your Windows system if you are used to Unix-type scripting.
There is no need to use :checkbox
, also replace #activelist
with #inactivelist
:
$('#inactivelist').change(function () {
alert('changed');
});
I was searching for similar solution. The replies here and the Tutorial on top is informative. I studied posts/blogs referred here to build mine successful. I am posting complete CMakeLists.txt worked for me. I guess, this would be helpful as a basic template for beginners.
"CMakeLists.txt"
cmake_minimum_required(VERSION 3.10.2)
# Target Project
project (ClientProgram)
# Begin: Including Sources and Headers
include_directories(include)
file (GLOB SOURCES "src/*.c")
# End: Including Sources and Headers
# Begin: Generate executables
add_executable (ClientProgram ${SOURCES})
# End: Generate executables
# This Project Depends on External Project(s)
include (ExternalProject)
# Begin: External Third Party Library
set (libTLS ThirdPartyTlsLibrary)
ExternalProject_Add (${libTLS}
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
# Begin: Download Archive from Web Server
URL http://myproject.com/MyLibrary.tgz
URL_HASH SHA1=<expected_sha1sum_of_above_tgz_file>
DOWNLOAD_NO_PROGRESS ON
# End: Download Archive from Web Server
# Begin: Download Source from GIT Repository
# GIT_REPOSITORY https://github.com/<project>.git
# GIT_TAG <Refer github.com releases -> Tags>
# GIT_SHALLOW ON
# End: Download Source from GIT Repository
# Begin: CMAKE Comamnd Argiments
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
CMAKE_ARGS -DUSE_SHARED_LIBRARY:BOOL=ON
# End: CMAKE Comamnd Argiments
)
# The above ExternalProject_Add(...) construct wil take care of \
# 1. Downloading sources
# 2. Building Object files
# 3. Install under DCMAKE_INSTALL_PREFIX Directory
# Acquire Installation Directory of
ExternalProject_Get_Property (${libTLS} install_dir)
# Begin: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# Include PATH that has headers required by Target Project
include_directories (${install_dir}/include)
# Import librarues from External Project required by Target Project
add_library (lmytls SHARED IMPORTED)
set_target_properties (lmytls PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmytls.so)
add_library (lmyxdot509 SHARED IMPORTED)
set_target_properties(lmyxdot509 PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmyxdot509.so)
# End: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# End: External Third Party Library
# Begin: Target Project depends on Third Party Component
add_dependencies(ClientProgram ${libTLS})
# End: Target Project depends on Third Party Component
# Refer libraries added above used by Target Project
target_link_libraries (ClientProgram lmytls lmyxdot509)
Try to install "Moesif CORS" extension if you are facing issue in google chrome. As it is cross origin request, so chrome is not accepting a response even when the response status code is 200
From JSP
<form method="post" id="myForm" action="someURL">
<input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden">
</form>
This is the simplest way that worked for me after struggling for 3hrs, just get the token from input hidden field like this and while doing the AJAX request to just need to pass this token in header as follows:-
From Jquery
var token = $('input[name="csrfToken"]').attr('value');
From plain Javascript
var token = document.getElementsByName("csrfToken").value;
Final AJAX Request
$.ajax({
url: route.url,
data : JSON.stringify(data),
method : 'POST',
headers: {
'X-CSRF-Token': token
},
success: function (data) { ... },
error: function (data) { ... }
});
Now you don't need to disable crsf security in web config, and also this will not give you 405( Method Not Allowed) error on console.
Hope this will help people..!!
I would say that one should omit the __init__.py
only if one wants to have the implicit namespace package. If you don't know what it means, you probably don't want it and therefore you should continue to use the __init__.py
even in Python 3.
Just Checkout This :
Solution 1 :
In Subgrid Function You have to write following :
var selectid = $(this).jqGrid('getCell', row_id, 'id');
alert(selectid);
Where row_id
is the variable which you define in subgrid as parameter.
And id
is the column name which you want to get value of the cell.
Solution 2 :
If You Get Jqgrid Row Id In alert Then set your primary key id as key:true
In ColModels. So You will get value of your database id in alert. Like this :
{name:"id",index:"id",hidden:true, width:15,key:true, jsonmap:"id"},
I know it's a little late for this. But I always thought that the best way to create event listeners is directly from JavaScript. Kind of like not applying inline CSS styles.
function validate(){
//do stuff
}
function init(){
document.getElementById('form').onsubmit = validate;
}
window.onload = init;
That way you don't have a bunch of event listeners throughout your HTML.
For me I was working under Ubuntu
The error disappeared if I use sudo with ng
sudo ng build
sudo ng serve
GPL-compiled ffmpeg can be used from non-GPL program (commercial project) only if it is invoked in the separate process as command line utility; all wrappers that are linked with ffmpeg library (including Microsoft's FFMpegInterop) can use only LGPL build of ffmpeg.
You may try my .NET wrapper for FFMpeg: Video Converter for .NET (I'm an author of this library). It embeds FFMpeg.exe into the DLL for easy deployment and doesn't break GPL rules (FFMpeg is NOT linked and wrapper invokes it in the separate process with System.Diagnostics.Process).
There is no implicit style that you have to choose, it involves writing a bit of code using the QuartzCore
framework:
//first, you
#import <QuartzCore/QuartzCore.h>
//.....
//Here I add a UITextView in code, it will work if it's added in IB too
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 220, 200, 100)];
//To make the border look very close to a UITextField
[textView.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
[textView.layer setBorderWidth:2.0];
//The rounded corner part, where you specify your view's corner radius:
textView.layer.cornerRadius = 5;
textView.clipsToBounds = YES;
It only works on OS 3.0 and above, but I guess now it's the de facto platform anyway.
If all vectors have equal size, create a matrix and plot it.
Each column is plotted with a different color automatically
Then you can use legend
to indicate columns:
data = randn(100, 5);
figure;
plot(data);
legend(cellstr(num2str((1:size(data,2))')))
Or, if you have a cell with kernels names, use
legend(names)
I handle validation exceptions in Laravel 5.3 like this. If you use Laravel Collective it will automatically display errors next to inputs and if you use laracasts/flash it will also show first validation error as a notice.
Handler.php
render:
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Validation\ValidationException) {
return $this->handleValidationException($request, $e);
}
(..)
}
And the function:
protected function handleValidationException($request, $e)
{
$errors = @$e->validator->errors()->toArray();
$message = null;
if (count($errors)) {
$firstKey = array_keys($errors)[0];
$message = @$e->validator->errors()->get($firstKey)[0];
if (strlen($message) == 0) {
$message = "An error has occurred when trying to register";
}
}
if ($message == null) {
$message = "An unknown error has occured";
}
\Flash::error($message);
return \Illuminate\Support\Facades\Redirect::back()->withErrors($e->validator)->withInput();
}
.img-responsive {
margin: 0 auto;
}
you can write like above code in your document so no need to add one another class in image tag.
You rarely need loops for vector operations in numpy. You can create an uninitialized array and assign to all entries at once:
>>> a = numpy.empty((3,3,))
>>> a[:] = numpy.nan
>>> a
array([[ NaN, NaN, NaN],
[ NaN, NaN, NaN],
[ NaN, NaN, NaN]])
I have timed the alternatives a[:] = numpy.nan
here and a.fill(numpy.nan)
as posted by Blaenk:
$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a.fill(np.nan)"
10000 loops, best of 3: 54.3 usec per loop
$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a[:] = np.nan"
10000 loops, best of 3: 88.8 usec per loop
The timings show a preference for ndarray.fill(..)
as the faster alternative. OTOH, I like numpy's convenience implementation where you can assign values to whole slices at the time, the code's intention is very clear.
Note that ndarray.fill
performs its operation in-place, so numpy.empty((3,3,)).fill(numpy.nan)
will instead return None
.
Please note that: ajaxStart / ajaxStop is not working for ajax jsonp request (ajax json request is ok)
I am using jquery 1.7.2 while writing this.
here is one of the reference I found: http://bugs.jquery.com/ticket/8338
This may be the good solution for you: change the code like this very little change
.box{
position: relative;
}
.box:hover .hidden{
opacity: 1;
width:500px;
}
.box .hidden{
background: yellow;
height: 334px;
position: absolute;
top: 0;
left: 0;
width: 0;
opacity: 0;
transition: all 1s ease;
}
See demo here
purrr::flatten_*()
is also a good option. the flatten_*
functions add thin sanity checks and ensure type safety.
myList <- list('A'=1, 'B'=2, 'C'=3)
purrr::flatten_dbl(myList)
## [1] 1 2 3
you can set an image URL for the content prop instead of the background-image.
content: url(/img/border-left3.png);
One of the first differences that I can recall from top of my head are multiple domains running in the same server, partial resource retrieval, this allows you to retrieve and speed up the download of a resource (it's what almost every download accelerator does).
If you want to develop an application like a website or similar, you don't need to worry too much about the differences but you should know the difference between GET
and POST
verbs at least.
Now if you want to develop a browser then yes, you will have to know the complete protocol as well as if you are trying to develop a HTTP server.
If you are only interested in knowing the HTTP protocol I would recommend you starting with HTTP/1.1 instead of 1.0.
One other way would be to use 4 letter commands to validate if zookeeper service is healthy or not
echo stat | nc <zookeeper ip> 2181
echo mntr | nc <zookeeper ip> 2181
echo isro | nc <zookeeper ip> 2181
More details on the documentation link below https://zookeeper.apache.org/doc/r3.1.2/zookeeperAdmin.html#sc_zkCommands
c99 has given us log2
. This removes the need for all the special sauce log2
implementations you see on this page. You can use the standard's log2
implementation like this:
const auto n = 13UL;
const auto Index = (unsigned long)log2(n);
printf("MSB is: %u\n", Index); // Prints 3 (zero offset)
An n
of 0UL
needs to be guarded against as well, because:
-8 is returned and FE_DIVBYZERO is raised
I have written an example with that check that arbitrarily sets Index
to ULONG_MAX
here: https://ideone.com/u26vsi
The visual-studio corollary to ephemient's gcc only answer is:
const auto n = 13UL;
unsigned long Index;
_BitScanReverse(&Index, n);
printf("MSB is: %u\n", Index); // Prints 3 (zero offset)
The documentation for _BitScanReverse
states that Index
is:
Loaded with the bit position of the first set bit (1) found
In practice I've found that if n
is 0UL
that Index
is set to 0UL
, just as it would be for an n
of 1UL
. But the only thing guaranteed in the documentation in the case of an n
of 0UL
is that the return is:
0 if no set bits were found
Thus, similarly to the preferable log2
implementation above the return should be checked setting Index
to a flagged value in this case. I've again written an example of using ULONG_MAX
for this flag value here: http://rextester.com/GCU61409
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.
Recently I had to deal with FF which underlines were too thick and too far from the text in FF, and found a better way to deal with it using a pair of box-shadows:
.custom-underline{
box-shadow: inset 0 0px 0 white, inset 0 -1px 0 black
}
First shadow is put on top of the second one and that's how you can control the second one by varying the 'px' value of both.
Plus: various colors, thickness and underline position
Minus: can not use on non-solid backgrounds
Here I made couple of examples: http://jsfiddle.net/xsL6rktx/
While trace flag 272 may work for many, it definitely won't work for hosted Sql Server Express installations. So, I created an identity table, and use this through an INSTEAD OF trigger. I'm hoping this helps someone else, and/or gives others an opportunity to improve my solution. The last line allows returning the last identity column added. Since I typically use this to add a single row, this works to return the identity of a single inserted row.
The identity table:
CREATE TABLE [dbo].[tblsysIdentities](
[intTableId] [int] NOT NULL,
[intIdentityLast] [int] NOT NULL,
[strTable] [varchar](100) NOT NULL,
[tsConcurrency] [timestamp] NULL,
CONSTRAINT [PK_tblsysIdentities] PRIMARY KEY CLUSTERED
(
[intTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
and the insert trigger:
-- INSERT --
IF OBJECT_ID ('dbo.trgtblsysTrackerMessagesIdentity', 'TR') IS NOT NULL
DROP TRIGGER dbo.trgtblsysTrackerMessagesIdentity;
GO
CREATE TRIGGER trgtblsysTrackerMessagesIdentity
ON dbo.tblsysTrackerMessages
INSTEAD OF INSERT AS
BEGIN
DECLARE @intTrackerMessageId INT
DECLARE @intRowCount INT
SET @intRowCount = (SELECT COUNT(*) FROM INSERTED)
SET @intTrackerMessageId = (SELECT intIdentityLast FROM tblsysIdentities WHERE intTableId=1)
UPDATE tblsysIdentities SET intIdentityLast = @intTrackerMessageId + @intRowCount WHERE intTableId=1
INSERT INTO tblsysTrackerMessages(
[intTrackerMessageId],
[intTrackerId],
[strMessage],
[intTrackerMessageTypeId],
[datCreated],
[strCreatedBy])
SELECT @intTrackerMessageId + ROW_NUMBER() OVER (ORDER BY [datCreated]) AS [intTrackerMessageId],
[intTrackerId],
[strMessage],
[intTrackerMessageTypeId],
[datCreated],
[strCreatedBy] FROM INSERTED;
SELECT TOP 1 @intTrackerMessageId + @intRowCount FROM INSERTED;
END
put:
If I want to update my first
name, then I send a put request:
{ "first": "Nazmul", "last": "hasan" }
But here is a problem with using put
request: When I want to send put
request I have to send all two parameters that is first
and last
(whereas I only need to update first
) so it is mandatory to send them all again with put
request.
patch:
patch
request, on the other hand, says: only specify the data
which you need to update
and it won't be affecting or changing other data.
So no need to send all values again. Do I only need to change first
name? Well, It only suffices to specify first
in patch
request.
Currently i'm using the below method. Works with no issues.
* * * * * /bin/bash -c ' for i in {1..X}; do YOUR_COMMANDS ; sleep Y ; done '
If you want to run every N seconds then X will be 60/N and Y will be N.
PHP's mail()
function does not have support for SMTP. You're going to need to use something like the PEAR Mail package.
Here is a sample SMTP mail script:
<?php
require_once("Mail.php");
$from = "Your Name <[email protected]>";
$to = "Their Name <[email protected]>";
$subject = "Subject";
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";
$host = "mailserver.blahblah.com";
$username = "smtp_username";
$password = "smtp_password";
$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);
$smtp = Mail::factory('smtp', array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if ( PEAR::isError($mail) ) {
echo("<p>Error sending mail:<br/>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message sent.</p>");
}
?>
Add Unique Index on your table:
ALTER IGNORE TABLE TableA
ADD UNIQUE INDEX (member_id, quiz_num, question_num, answer_num);
is work very well
Function pointers can be passed as template parameters, and this is part of standard C++ . However in the template they are declared and used as functions rather than pointer-to-function. At template instantiation one passes the address of the function rather than just the name.
For example:
int i;
void add1(int& i) { i += 1; }
template<void op(int&)>
void do_op_fn_ptr_tpl(int& i) { op(i); }
i = 0;
do_op_fn_ptr_tpl<&add1>(i);
If you want to pass a functor type as a template argument:
struct add2_t {
void operator()(int& i) { i += 2; }
};
template<typename op>
void do_op_fntr_tpl(int& i) {
op o;
o(i);
}
i = 0;
do_op_fntr_tpl<add2_t>(i);
Several answers pass a functor instance as an argument:
template<typename op>
void do_op_fntr_arg(int& i, op o) { o(i); }
i = 0;
add2_t add2;
// This has the advantage of looking identical whether
// you pass a functor or a free function:
do_op_fntr_arg(i, add1);
do_op_fntr_arg(i, add2);
The closest you can get to this uniform appearance with a template argument is to define do_op
twice- once with a non-type parameter and once with a type parameter.
// non-type (function pointer) template parameter
template<void op(int&)>
void do_op(int& i) { op(i); }
// type (functor class) template parameter
template<typename op>
void do_op(int& i) {
op o;
o(i);
}
i = 0;
do_op<&add1>(i); // still need address-of operator in the function pointer case.
do_op<add2_t>(i);
Honestly, I really expected this not to compile, but it worked for me with gcc-4.8 and Visual Studio 2013.
If you have already git merge bugfix
on main
, you can squash your merge commit into one with:
git reset --soft HEAD^1
git commit
I would like to share my thoughts as well, since I've bumped into the same issue.
Well, just answering the question would be:
1 - Add an extenssion to the observable collection class like this:
namespace YourNameSpace
{
public static class ObservableCollectionExtension
{
public static void OrderByReference<T>(this ObservableCollection<T> collection, List<T> comparison)
{
for (int i = 0; i < comparison.Count; i++)
{
if (!comparison.ElementAt(i).Equals(collection.ElementAt(i)))
collection.Move(collection.IndexOf(comparison[i]), i);
}
}
public static void InsertInPlace<T>(this ObservableCollection<T> collection, List<T> comparison, T item)
{
int index = comparison.IndexOf(item);
comparison.RemoveAt(index);
collection.OrderByReference(comparison);
collection.Insert(index, item);
}
}
}
2 - Then use it like this:
_animals.OrderByReference(_animals.OrderBy(x => x).ToList());
This changes your ObservableCollection, you can use linq and it doesn't change the bindings!
Extra:
I've extended @Marco and @Contango answers to my own liking. First I thought of using a list directly as the comparison, so you would have this:
public static void OrderByReference<T>(this ObservableCollection<T> collection, List<T> comparison)
{
for (int i = 0; i < comparison.Count; i++)
{
collection.Move(collection.IndexOf(comparison[i]), i);
}
}
And using like this:
YourObservableCollection.OrderByReference(YourObservableCollection.DoYourLinqOrdering().ToList());
Then I've thought, since this always move everything and triggers the move in the ObservableCollection why not compare if the object is already in there, and this brings what I've put in the begining with the Equals comparator.
Adding the object to the correct place also sounded good, but I wanned a simple way to do it. So I've came up with that:
public static void InsertInPlace<T>(this ObservableCollection<T> collection, List<T> comparison, T item)
{
collection.Insert(comparison.IndexOf(item), item);
}
You send a list with the new object where you want and also this new object, so you need to create a list, then add this new object, like this:
var YourList = YourObservableCollection.ToList();
var YourObject = new YourClass { ..... };
YourList.Add(YourObject);
YourObservableCollection.InsertInPlace(YourList.DoYourLinqOrdering().ToList(), YourObject);
But since the ObservableCollection could be in a different order than the list because of the selection in the "DoYourLinqOrdering()" (this would happen if the collection wasn't previously ordered) I've added the first extession (OrderByReference) in the insert as you can see in the begining of the answer. It will not take long if it doesn't need to move the itens arround, so I did't saw a problem in using it.
As performance goes, I've compared the methods by checking the time it takes for each to finish, so not ideal, but anyway, I've tested an observable collection with 20000 itens. For the OrderByReference I didn't saw great difference in the performance by adding the Equal object checker, but if not all itens need to be moved it is faster and it doesn't fire unecessary Move events on the collecitonChanged, so thats something. For the InsertInPlace is the same thing, if the ObservableCollection is already sorted, just checking if the objects are in the right place is faster than moving all the itens around, so there was not a huge difference in time if it is just passing through the Equals statement and you get the benefit of being sure everything is where it should be.
Be aware that if you use this extession with objects that dont mach or with a list that have more or less objects you will get an ArgumentOutOfRangeException or some other unexpect behaviour.
Hopes this helps somebody!
There are at least three very good reasons for using the Visitor Pattern:
Reduce proliferation of code which is only slightly different when data structures change.
Apply the same computation to several data structures, without changing the code which implements the computation.
Add information to legacy libraries without changing the legacy code.
Please have a look at an article I've written about this.
I faced the same 415
http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON.
In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.
As mentioned in the other responses I have correctly set the Accept
and Content-Type
headers to application/json
, but it doesn't suffice.
Solution
I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.
Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:
Wrong
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
Right
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO() {
}
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
I lost hours, I hope this'll save yours ;-)
You should definitely have a look at this answer of mine:
and also have a look at all the links included therein.
Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.
You need to also install cygrunsrv
so you can set cron up as a windows service, then run cron-config
.
If you want the cron jobs to send email of any output you'll also need to install either exim
or ssmtp
(before running cron-config
.)
See /usr/share/doc/Cygwin/cron-*.README
for more details.
Regarding programs without a .exe
extension, they are probably shell scripts of some type. If you look at the first line of the file you could see what program you need to use to run them (e.g., "#!/bin/sh
"), so you could perhaps execute them from the windows scheduler by calling the shell program (e.g., "C:\cygwin\bin\sh.exe -l /my/cygwin/path/to/prog
".)
You are just returning a memory address, it's allowed but probably an error.
Yes if you try to dereference that memory address you will have undefined behavior.
int * ref () {
int tmp = 100;
return &tmp;
}
int main () {
int * a = ref();
//Up until this point there is defined results
//You can even print the address returned
// but yes probably a bug
cout << *a << endl;//Undefined results
}
I recommend that before executing SaveAs, delete the file it exists.
If Dir("f:ull\path\with\filename.xls") <> "" Then
Kill "f:ull\path\with\filename.xls"
End If
It's easier than setting DisplayAlerts off and on, plus if DisplayAlerts remains off due to code crash, it can cause problems if you work with Excel in the same session.
You can use google map Obtaining User Location here!
After obtaining your location(longitude and latitude), you can use google place api
This code can help you get your location easily but not the best way.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
Easy solution: Check if it works for you..
Goto web.config
Find binding used by client.
change as,
maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
Done.
IMHO, There is no need to install all the additional applications/packages.
Check available versions using the command:
> /usr/libexec/java_home -V
Matching Java Virtual Machines (8):
11, x86_64: "Java SE 11-ea" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
10.0.2, x86_64: "Java SE 10.0.2" /Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home
9.0.1, x86_64: "Java SE 9.0.1" /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
1.8.0_181-zulu-8.31.0.1, x86_64: "Zulu 8" /Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home
1.8.0_151, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
1.7.0_80, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home
1.6.0_65-b14-468, x86_64: "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
1.6.0_65-b14-468, i386: "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Now if you want to pick Azul JDK 8 in the above list, and NOT Oracle's Java SE 8, invoke the command as below:
> /usr/libexec/java_home -v 1.8.0_181
/Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home
To pick Oracle's Java SE 8 you would invoke the command:
> /usr/libexec/java_home -v 1.8.0_151
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
As you can see the version number provided shall be the unique set of strings: 1.8.0_181 vs 1.8.0_151
Your setting is all right. Some web servers require to specify the media and static folder files specifically. For example in pythonanywhere.com you have to go to the 'Web' section and add the url od the media folders and static folder. For example:
URL Directory
/static/ /home/Saidmamad/discoverthepamirs/static
/accounts/static/ /home/Saidmamad/discoverthepamirs/accounts/static
/media/ /home/Saidmamad/discoverthepamirs/discoverthepamirs/media
I know that it is late, but just to help those who visit this link because of the same problem ;)
The problem in my case was that I needed to add environment variables for http_proxy
and https_proxy
.
E.g.,
http_proxy=http://your_proxy:your_port
https_proxy=https://your_proxy:your_port
To set these environment variables in Windows, see the answers to this question.
var app = angular.module('myApp', [])
app.controller('MainCtrl', ['$scope', function($scope){
$scope.num1 = 1;
$scope.num2 = 1;
$scope.total = parseInt($scope.num1 + $scope.num2);
}]);
Demo: parseInt with AngularJS
This question is a bit old now, but I would like to offer an alternative solution that doesn't mutate source data and requires minimal manual effort:
function mapOut(sourceObject, removeKeys = []) {
const sourceKeys = Object.keys(sourceObject);
const returnKeys = sourceKeys.filter(k => !removeKeys.includes(k));
let returnObject = {};
returnKeys.forEach(k => {
returnObject[k] = sourceObject[k];
});
return returnObject;
}
const array = [
{"bad": "something", "good":"something"},
{"bad":"something", "good":"something"},
];
const newArray = array.map(obj => mapOut(obj, [ "bad", ]));
It's still a little less than perfect, but maintains some level of immutability and has the flexibility to name multiple properties that you want to remove. (Suggestions welcome)
To simulate a low bandwidth connection for testing web sites use Google Chrome, you can go to the Network Tab in F12 Tools and select a bandwidth level to simulate or create custom bandwidth to simulate.
If you want to use them like that, define the function with the variable names as normal:
def my_function(school, standard, city, name):
schoolName = school
cityName = city
standardName = standard
studentName = name
Now you can use **
when you call the function:
data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}
my_function(**data)
and it will work as you want.
P.S. Don't use reserved words such as class
.(e.g., use klass
instead)
Implement override Equals()
and GetHashCode()
public class CartProduct
{
public Int32 ID;
...
public CartProduct(Int32 ID, ...)
{
this.ID = ID;
...
}
public override int GetHashCode()
{
return ID;
}
public override bool Equals(Object obj)
{
if (obj == null || !(obj is CartProduct))
return false;
else
return GetHashCode() == ((CartProduct)obj).GetHashCode();
}
}
used:
if (CartProducts.Contains(p))
Since vars passed through url are $_GET vars, you can use filter_input()
function:
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$othervar = filter_input(INPUT_GET, 'othervar', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
It would store the values of each var and sanitize/validate them too.
Location is a struct. If there aren't any convenience members, you'll need to reassign the entire Location:
this.balancePanel.Location = new Point(
this.optionsPanel.Location.X,
this.balancePanel.Location.Y);
Most structs are also immutable, but in the rare (and confusing) case that it is mutable, you can also copy-out, edit, copy-in;
var loc = this.balancePanel.Location;
loc.X = this.optionsPanel.Location.X;
this.balancePanel.Location = loc;
Although I don't recommend the above, since structs should ideally be immutable.
In setting.py
in MIDDLEWARE you can simply remove/comment this line:
'django.middleware.csrf.CsrfViewMiddleware',
You'll need the cookie plugin, which provides several additional signatures to the cookie function.
$.cookie('cookie_name', 'cookie_value')
stores a transient cookie (only exists within this session's scope, while $.cookie('cookie_name', 'cookie_value', 'cookie_expiration")
creates a cookie that will last across sessions - see http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/ for more information on the JQuery cookie plugin.
If you want to set cookies that are used for the entire site, you'll need to use JavaScript like this:
document.cookie = "name=value; expires=date; domain=domain; path=path; secure"
There are three ways scope can be added in the directive:
The directive and its parent(controller/directive inside which it lies) scope is same. So any changes made to the scope variables inside directive are reflected in the parent controller as well. You don't need to specify this as it is the default.
Here, if you change the scope variables inside directive, it won't reflect in the parent scope, but if you change the property of a scope variable, that is reflected in the parent scope, as you actually modified the scope variable of the parent.
Example,
app.directive("myDirective", function(){
return {
restrict: "EA",
scope: true,
link: function(element, scope, attrs){
scope.somvar = "new value"; //doesnot reflect in the parent scope
scope.someObj.someProp = "new value"; //reflects as someObj is of parent, we modified that but did not override.
}
};
});
This happens when you are creating plugins as this makes the directive generic since it can be placed in any HTML and does not gets affected by its parent scope.
Now, if you don't want any interaction with the parent scope, then you can just specify scope as an empty object. like,
scope: {} //this does not interact with the parent scope in any way
Mostly this is not the case as we need some interaction with the parent scope, so we want some of the values/ changes to pass through. For this reason, we use:
1. "@" ( Text binding / one-way binding )
2. "=" ( Direct model binding / two-way binding )
3. "&" ( Behaviour binding / Method binding )
@ means that the changes from the controller scope will be reflected in the directive scope but if you modify the value in the directive scope, the controller scope variable will not get affected.
@ always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}.
= is bidirectional so if you change the variable in directive scope, the controller scope variable gets affected as well
& is used to bind controller scope method so that if needed we can call it from the directive
The advantage here is that the name of the variable need not be same in controller scope and directive scope.
Example, the directive scope has a variable "dirVar" which syncs with variable "contVar" of the controller scope. This gives a lot of power and generalization to the directive as one controller can sync with variable v1 while another controller using the same directive can ask dirVar to sync with variable v2.
Below is the example of usage:
The directive and controller are:
var app = angular.module("app", []);
app.controller("MainCtrl", function( $scope ){
$scope.name = "Harry";
$scope.color = "#333333";
$scope.reverseName = function(){
$scope.name = $scope.name.split("").reverse().join("");
};
$scope.randomColor = function(){
$scope.color = '#'+Math.floor(Math.random()*16777215).toString(16);
};
});
app.directive("myDirective", function(){
return {
restrict: "EA",
scope: {
name: "@",
color: "=",
reverse: "&"
},
link: function(element, scope, attrs){
//do something like
$scope.reverse();
//calling the controllers function
}
};
});
And the html(note the differnce for @ and =):
<div my-directive
class="directive"
name="{{name}}"
reverse="reverseName()"
color="color" >
</div>
Here is a link to the blog which describes it nicely.
One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.
One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).
Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.
-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
ID INT IDENTITY(1, 1) NOT NULL,
CallTime DATETIME NOT NULL DEFAULT GETDATE(),
CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
ID INT IDENTITY(1, 1) NOT NULL,
CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
Subject VARCHAR(250) NOT NULL,
Notes VARCHAR(8000) NOT NULL,
Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
PhoneCallID INT NOT NULL,
TicketID INT NOT NULL
)
It's pretty simple.
var oFile = document.getElementById("fileUpload").files[0]; // <input type="file" id="fileUpload" accept=".jpg,.png,.gif,.jpeg"/>
if (oFile.size > 2097152) // 2 MiB for bytes.
{
alert("File size must under 2MiB!");
return;
}
I see that this question is already old but still...
We made a sipmle library at our company for achieving what is desired - An interactive info window with views and everything. You can check it out on github.
I hope it helps :)
As of .NET 4.5 you can use Caller Information Attributes:
CallerFilePath
- The source file that called the function;CallerLineNumber
- Line of code that called the function; CallerMemberName
- Member that called the function.
public void WriteLine(
[CallerFilePath] string callerFilePath = "",
[CallerLineNumber] long callerLineNumber = 0,
[CallerMemberName] string callerMember= "")
{
Debug.WriteLine(
"Caller File Path: {0}, Caller Line Number: {1}, Caller Member: {2}",
callerFilePath,
callerLineNumber,
callerMember);
}
This facility is also present in ".NET Core" and ".NET Standard".
References
Late to the game, but you can do it without @string/xyz
by using ?android:attr
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?android:attr/versionName"
/>
<!-- or -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?android:attr/versionCode"
/>
In the tour guide app of Udacity's Basic ANdroid course I have used the concept of Fragments. I got stuck for a while experiencing difficulty to access some string resources described in strings, xml file. Finally got a solution.
This is the main activity class
package com.example.android.tourguidekolkata;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
//lines of code
//lines of code
//lines of code
YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext());
//lines of code
// getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter
}
}
This is the non Activity class that extends FragmentPageAdapter
public class YourClass extends FragmentPagerAdapter {
private String yourStringArray[] = new String[4];
Context context;
public YourClass (FragmentManager fm, Context context)
{
super(fm);
this.context = context; // store the context of main activity
// now you can use this context to access any resource
yourStringArray[0] = context.getResources().getString(R.string.tab1);
yourStringArray[1] = context.getResources().getString(R.string.tab2);
yourStringArray[2] = context.getResources().getString(R.string.tab3);
yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
{
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
You can use a subquery:
SELECT *
FROM terms
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ');
and if you need to show all columns from both tables:
SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'
int a = srand(time(NULL))
arr[i] = a;
Should be
arr[i] = rand();
And put srand(time(NULL))
somewhere at the very beginning of your program.
The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")
check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print
Use FileUtils to handle all these headaches.
Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.
openOutputStream(File file [, boolean append])
Use like ..
<div style="background-image: url(../images/test-background.gif); height: 200px; width: 400px; border: 1px solid black;">Example of a DIV element with a background image:</div>
<div style="background-image: url(../images/test-background.gif); height: 200px; width: 400px; border: 1px solid black;"> </div>
I solved this by overriding the default Content-Type:
const config = { headers: {'Content-Type': 'application/json'} };
axios.put(url, content, config).then(response => {
...
});
Based on m experience, the default Conent-Type is application/x-www-form-urlencoded for strings, and application/json for objects (including arrays). Your server probably expects JSON.
Combine both. The Date-Time-Picker does support picking time, too.
You just have to change the Format-Property and maybe the CustomFormat-Property.
You can read the data into an array. From there you can do the match in memory, instead of reading one cell at a time.
You first have to define a JTextArea as per usual:
public final JTextArea mainConsole = new JTextArea("");
Then you put a JScrollPane over the TextArea
JScrollPane scrollPane = new JScrollPane(mainConsole);
scrollPane.setBounds(10,60,780,500);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
The last line says that the vertical scrollbar will always be there. There is a similar command for horizontal. Otherwise, the scrollbar will only show up when it is needed (or never, if you use _SCROLLBAR_NEVER). I guess it's your call which way you want to use it.
You can also add wordwrap to the JTextArea if you want to:Guide Here
Good luck,
Norm M
P.S. Make sure you add the ScrollPane to the JPanel and not add the JTextArea.
I started mongod in cmd,It threw error like C:\data\db\ not found. Created folder then typed mongod opened another cmd typed mongo it worked.
This is a common error people face when using Entity Framework. This occurs when the entity associated with the table being saved has a mandatory datetime field and you do not set it with some value.
The default datetime object is created with a value of 01/01/1000
and will be used in place of null. This will be sent to the datetime column which can hold date values from 1753-01-01 00:00:00
onwards, but not before, leading to the out-of-range exception.
This error can be resolved by either modifying the database field to accept null or by initializing the field with a value.
In my case the error was due to lack of permissions to the folder path. I entered and saved the credentials the issue was solved.
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
Here is the PHP's version (input values are: $latitude
and $longitude
):
$latitude_pattern = '/\A[+-]?(?:90(?:\.0{1,18})?|\d(?(?<=9)|\d?)\.\d{1,18})\z/x';
$longitude_pattern = '/\A[+-]?(?:180(?:\.0{1,18})?|(?:1[0-7]\d|\d{1,2})\.\d{1,18})\z/x';
if (preg_match($latitude_pattern, $latitude) && preg_match($longitude_pattern, $longitude)) {
// Valid coordinates.
}
Here is how I solved this problem for the old (< 4.3) HttpClient (which I cannot upgrade), using the answer of Santosh Singh (who I gave a +1):
HttpClient httpclient = new HttpClient();
if (System.getProperty("http.proxyHost") != null) {
try {
HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")));
httpclient.setHostConfiguration(hostConfiguration);
this.getLogger().warn("USING PROXY: "+httpclient.getHostConfiguration().getProxyHost());
} catch (Exception e) {
throw new ProcessingException("Cannot set proxy!", e);
}
}
Though this question was asked a few years ago, a jQuery plugin isn't required anymore provided the date value in question is a string with format mm/dd/yyyy
(like when using a date-picker);
var birthdateVal = $('#birthdate').val();
//birthdateVal: 11/8/2014
var birthdate = new Date(birthdateVal);
//birthdate: Sat Nov 08 2014 00:00:00 GMT-0500 (Eastern Standard Time)
I am using Debian 10 buster and try download a file with youtube-dl and get this error:
sudo youtube-dl -k https://youtu.be/uscis0CnDjk
[youtube] uscis0CnDjk: Downloading webpage ERROR: Unable to download webpage: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)> (caused by URLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)')))
Certificates with python2 and python3.8 are installed correctly, but i persistent receive the same error.
finally (which is not the best solution, but works for me was to eliminate the certificate check as it is given as an option in youtube-dl) whith this command
sudo youtube-dl -k --no-check-certificate https://youtu.be/uscis0CnDjk
function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}
SELECT REPLACE(CONVERT(varchar(20), (CAST(9876543 AS money)), 1), '.00', '')
output= 9,876,543
and you can replace 9876543 by your column name.
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
This worked for me to stop silly work breaks from happening within Chrome textareas
word-break: keep-all;
git checkout master -go to the master branch first
git checkout <your-branch> -- <your-file> --copy your file data from your branch.
git show <your-branch>:path/to/<your-file>
Hope this will help you. Please let me know If you have any query.
Just consider your drive as a folder so do cd e:
You can use shared preferences from flutter's official plugins. https://github.com/flutter/plugins/tree/master/packages/shared_preferences
It uses Shared Preferences for Android, NSUserDefaults for iOS.
It is the directory from where you run the command to execute your batch file.
As mentioned in the above answers you can add the below command to your script to verify:
> set current_dir=%cd%
> echo %current_dir%
You can use ObjectAnimator
like this:
ObjectAnimator.ofInt(yourScrollView, "scrollY", yourView.getTop()).setDuration(1500).start();
I also struggled with this but got it working once I figured out how the paths work in UploadHandler.php: upload_dir and upload_url are about the only settings to look at to get it working. Also check your server error logs for debugging information.
From inside the Service class:
Intent dialogIntent = new Intent(this, MyActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.
Since c++11 mutable
can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):
int x = 0;
auto f1 = [=]() mutable {x = 42;}; // OK
auto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda
Have you tried Autodia yet? Last time I tried it it wasn't perfect, but it was good enough.
Objects have methods and attributes(variables) which are derived from classes, in order to specify which methods and variables belong to a particular object the this
reserved word is used. in the case of instance variables, it is important to understand the difference between implicit and explicit parameters. Take a look at the fillTank
call for the audi
object.
Car audi= new Car();
audi.fillTank(5); // 5 is the explicit parameter and the car object is the implicit parameter
The value in the parenthesis is the implicit parameter and the object itself is the explicit parameter, methods that don't have explicit parameters, use implicit parameters, the fillTank
method has both an explicit and an implicit parameter.
Lets take a closer look at the fillTank
method in the Car
class
public class Car()
{
private double tank;
public Car()
{
tank = 0;
}
public void fillTank(double gallons)
{
tank = tank + gallons;
}
}
In this class we have an instance variable "tank". There could be many objects that use the tank instance variable, in order to specify that the instance variable "tank" is used for a particular object, in our case the "audi" object we constructed earlier, we use the this
reserved keyword. for instance variables the use of 'this' in a method indicates that the instance variable, in our case "tank", is instance variable of the implicit parameter.
The java compiler automatically adds the this
reserved word so you don't have to add it, it's a matter of preference. You can not use this
without a dot(.) because those are the rules of java ( the syntax).
In summary.
this
on an instance variable in a method indicates that, the instance variable belongs to the implicit parameter, or that it is an instance variable of the implicit parameter. this
cannot be used without a dot(.) this is syntactically invalidthis
can also be used to distinguish between local variables and global variables that have the same namethis
reserve word also applies to methods, to indicate a method belongs to a particular object. " error: command 'gcc' failed with exit status 1 ". the installation failed because of missing python-devel and some dependencies.
the best way to correct gcc problem:
You need to reinstall gcc , gcc-c++ and dependencies.
For python 2.7
$ sudo yum -y install gcc gcc-c++ kernel-devel
$ sudo yum -y install python-devel libxslt-devel libffi-devel openssl-devel
$ pip install "your python packet"
For python 3.4
$ sudo apt-get install python3-dev
$ pip install "your python packet"
Hope this will help.
If you are using grunt to build your application, it's possible that during build the paths change. In this case you need to modify your grunt file like this:
copy: {
main: {
files: [{
src: ['fonts/**'],
dest: 'dist/fonts/',
filter: 'isFile',
expand: true,
flatten: true
}, {
src: ['bower_components/font-awesome/fonts/**'],
dest: 'dist/css/',
filter: 'isFile',
expand: true,
flatten: false
}]
}
},
Further to meteore's answer, I found the code
df.index = df.index.astype('i8')
doesn't work for me. So I put my code here for the convenience of others stuck with this issue.
city_cluster_df = pd.read_csv(text_filepath, encoding='utf-8')
# the field 'city_en' is a string, when converted to Numpy array, it will be an object
city_cluster_arr = city_cluster_df[['city_en','lat','lon','cluster','cluster_filtered']].to_records()
descr=city_cluster_arr.dtype.descr
# change the field 'city_en' to string type (the index for 'city_en' here is 1 because before the field is the row index of dataframe)
descr[1]=(descr[1][0], "S20")
newArr=city_cluster_arr.astype(np.dtype(descr))
This answer was made pre-JPA2 implementations, if you're using JPA2, see the ElementCollection answer above:
Lists of objects inside a model object are generally considered "OneToMany" relationships with another object. However, a String is not (by itself) an allowable client of a One-to-Many relationship, as it doesn't have an ID.
So, you should convert your list of Strings to a list of Argument-class JPA objects containing an ID and a String. You could potentially use the String as the ID, which would save a little space in your table both from removing the ID field and by consolidating rows where the Strings are equal, but you would lose the ability to order the arguments back into their original order (as you didn't store any ordering information).
Alternatively, you could convert your list to @Transient and add another field (argStorage) to your class that is either a VARCHAR() or a CLOB. You'll then need to add 3 functions: 2 of them are the same and should convert your list of Strings into a single String (in argStorage) delimited in a fashion that you can easily separate them. Annotate these two functions (that each do the same thing) with @PrePersist and @PreUpdate. Finally, add the third function that splits the argStorage into the list of Strings again and annotate it @PostLoad. This will keep your CLOB updated with the strings whenever you go to store the Command, and keep the argStorage field updated before you store it to the DB.
I still suggest doing the first case. It's good practice for real relationships later.
As said above:
git diff origin/master..HEAD
But if you are using git gui
After opening gui interface, Select "Repository"->Under that "Visualize History"
Note: Some people like to use CMD Prompt/Terminal while some like to use Git GUI (for simplicity)
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
I don't think desc
takes an na.rm
argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NA
s, use na.omit
(base) or tidyr::drop_na
:
outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If you only want to remove NA
s from the HeartAttackDeath column, filter with is.na
, or use tidyr::drop_na
:
outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
As pointed out at the dupe, complete.cases
can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:
outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
Corrected code :
setlocal enabledelayedexpansion
for /f "usebackq eol= tokens=* delims= " %%a in (`findstr /n ^^^^ "name with spaces.txt"`) do (
set line=%%a
set "line=!line:*:=!"
echo(!line!
)
endlocal
pause
\b\d+,
\b------->word boundary
\d+------>one or digit
,-------->containing commas,
Eg:
sddsgg 70,000 sdsfdsf fdgfdg70,00
sfsfsd 5,44,4343 5.7788,44 555
It will match:
70,
5,
44,
,44
Install jquery-ui-dist
use npm
npm install --save jquery-ui-dist
or yarn
yarn add jquery-ui-dist
Import it inside your app code
import 'jquery-ui-dist/jquery-ui';
or
require('jquery-ui-dist/jquery-ui');
ConcurrentLinkedQueue
uses a lock-free queue (based off the newer CAS instruction).
some_list[-1]
is the shortest and most Pythonic.
In fact, you can do much more with this syntax. The some_list[-n]
syntax gets the nth-to-last element. So some_list[-1]
gets the last element, some_list[-2]
gets the second to last, etc, all the way down to some_list[-len(some_list)]
, which gives you the first element.
You can also set list elements in this way. For instance:
>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
Note that getting a list item by index will raise an IndexError
if the expected item doesn't exist. This means that some_list[-1]
will raise an exception if some_list
is empty, because an empty list can't have a last element.
Updated Answer
As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.
This answer is no longer valid
As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.
Here you can find some public REST services for encryption and security related things: http://security.jelastic.servint.net
Just a small correction for Marko's answer: exact number can't be produced out of some general calculations straight forward due to the next fact: Valid IP addresses should also not end with binary 0 or 1 sequences that have same length as zero sequence in subnet mask. So the final answer really depends on the total number of subnets (Marko's answer - 2 * total subnet count).
I was looking for a pretty and simple solution and I found this:
this.setState({ [`image${i}`]: image })
Hope this helps
To set ANDROID_HOME environment on ubuntu 20.04 visit Ubuntu's snap store and install Android studio and then open
vim $HOME/.bashrc
And set the environment variables as follows:
export ANDROID_HOME=${HOME}/Android/Sdk
export PATH=${ANDROID_HOME}/tools:${PATH}
export PATH=${ANDROID_HOME}/emulator:${PATH}
export PATH=${ANDROID_HOME}/platform-tools:${PATH}
With recent versions of Android studio replace ANDROID_HOME with ANDROID_SDK_ROOT otherwise builds will complain that ANDROID_HOME is deprecated.
Probably the shortest version:
[System.Collections.ArrayList]$someArray
It is also faster because it does not call relatively expensive New-Object
.
you can use this :
return redirect()->back()->withSuccess('IT WORKS!');
and use this in your view :
@if(session('success'))
<h1>{{session('success')}}</h1>
@endif
Replace GetMonthName
with GetAbbreviatedMonthName
so that it reads:
string strMonthName = mfi.GetAbbreviatedMonthName(8);
simply use delete
, but be aware that you should read fully what the effects are of using this:
delete object.index; //true
object.index; //undefined
but if I was to use like so:
var x = 1; //1
delete x; //false
x; //1
but if you do wish to delete variables in the global namespace, you can use it's global object such as window
, or using this
in the outermost scope i.e
var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true
http://perfectionkills.com/understanding-delete/
another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice
which is a prototype of the array object.
Example Array:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
if I was to do:
delete myCars[1];
the resulting array would be:
["Saab", undefined, "BMW"]
but using splice like so:
myCars.splice(1,1);
would result in:
["Saab", "BMW"]
The Error
constructor is used to create an error object. Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.
User-defined Errors are thrown via the throw
statement. program control will be passed to the first catch
block in the call stack.
The difference between throwing an error with and without Error object:
throw {'hehe':'haha'};
In chrome devtools looks like this:
Chrome tells us that we have an uncaught error which just is a JS object. The object itself could have information regarding the error but we still don't know immediately where it came from. Not very useful when we are working on our code and debugging it.
throw new Error({'hehe':'haha'});
In chrome devtools looks like this:
An error thrown with the Error object gives us a stack trace when we expand it. This gives us valuable information where the error precisely came from which is often valuable information when debugging your code. Further note that the error says [object Object]
, this is because the Error
constructor expects a message string as a first argument. When it receives a object it will coerce it into a string.
As stated many times, the lower bound on comparison based sorting for general data is going to be O(n log n). To briefly resummarize these arguments, there are n! different ways a list can be sorted. Any sort of comparison tree that has n! (which is in O(n^n)) possible final sorts is going to need at least log(n!) as its height: this gives you a O(log(n^n)) lower bound, which is O(n log n).
So, for general data on a linked list, the best possible sort that will work on any data that can compare two objects is going to be O(n log n). However, if you have a more limited domain of things to work in, you can improve the time it takes (at least proportional to n). For instance, if you are working with integers no larger than some value, you could use Counting Sort or Radix Sort, as these use the specific objects you're sorting to reduce the complexity with proportion to n. Be careful, though, these add some other things to the complexity that you may not consider (for instance, Counting Sort and Radix sort both add in factors that are based on the size of the numbers you're sorting, O(n+k) where k is the size of largest number for Counting Sort, for instance).
Also, if you happen to have objects that have a perfect hash (or at least a hash that maps all values differently), you could try using a counting or radix sort on their hash functions.
I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.
#!/bin/bash
# Open file descriptor (fd) 3 for read/write on a text file.
exec 3<> poem.txt
# Let's print some text to fd 3
echo "Roses are red" >&3
echo "Violets are blue" >&3
echo "Poems are cute" >&3
echo "And so are you" >&3
# Close fd 3
exec 3>&-
Then cat
the file on terminal
$ cat poem.txt
Roses are red
Violets are blue
Poems are cute
And so are you
This example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd's then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in /proc/sys/file-max
or /proc/sys/fs/file-max
but using any fd above 9 is dangerous as it could conflict with fd's used by the shell internally. So don't bother and only use fd's 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways :)
Anyhow, fd's can be used in a lot of interesting ways.
git checkout --[ours/theirs] .
will do what you want, as long as you're at the root of all conflicts. ours/theirs only affects unmerged files so you shouldn't have to grep/find/etc conflicts specifically.
From what I recall, it's based on the size of a memory address. So on a system with a 32-bit address scheme, sizeof will return 4, since that's 4 bytes.
Alex Answer is pretty neat but when using context rotate it can be hard to trace x,y coordinates, so I have made a Demo showing how to keep track of that.
Basically I am using this function & giving it the angle & the amount of distance traveled in that angel before drawing object.
function rotCor(angle, length){
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var newx = length*cos;
var newy = length*sin;
return {
x : newx,
y : newy
};
}
A)
Object* o;
o = new Object();
`` B)
Object* o = new Object();
I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.
One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).
Global variables can be used in Node when used wisely.
Declaration of global variables in Node:
a = 10;
GLOBAL.a = 10;
global.a = 10;
All of the above commands the same actions with different syntaxes.
Use global variables when they are not about to be changed
Here an example of something that can happen when using global variables:
// app.js
a = 10; // no var or let or const means global
// users.js
app.get("/users", (req, res, next) => {
res.send(a); // 10;
});
// permissions.js
app.get("/permissions", (req, res, next) => {
a = 11; // notice that there is no previous declaration of a in the permissions.js, means we looking for the global instance of a.
res.send(a); // 11;
});
Explained:
Run users route first and receive 10;
Then run permissions route and receive 11;
Then run again the users route and receive 11 as well instead of 10;
Global variables can be overtaken!
Now think about using express and assignin res object as global.. And you end up with async error become corrupt and server is shuts down.
When to use global vars?
As I said - when var is not about to be changed.
Anyways it's more recommended that you will be using the process.env
object from the config file.
You can use full datetime
variables with timedelta
, and by providing a dummy date then using time
to just get the time value.
For example:
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())
results in the two values, three seconds apart:
11:34:59
11:35:02
You could also opt for the more readable
b = a + datetime.timedelta(seconds=3)
if you're so inclined.
If you're after a function that can do this, you can look into using addSecs
below:
import datetime
def addSecs(tm, secs):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(seconds=secs)
return fulldate.time()
a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)
This outputs:
09:11:55.775695
09:16:55
According to this, you will need .NET 4.5 installed. For more details, visit the webpage. The gist of it is that after you have .NET 4.5 installed, your 4.0 apps will use the 4.5 System.dll. You can enable TLS 1.2 in two ways:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319: SchUseStrongCrypto
to DWORD 1
In IE 8, cookies (verified only against localhost) are shared between ports. In FF 10, they are not.
I've posted this answer so that readers will have at least one concrete option for testing each scenario.
You can add an IBAction to the uiTextField(the releation event is "Did End On Exit"),and the IBAction may named hideKeyboard,
-(IBAction)hideKeyboard:(id)sender
{
[uitextfield resignFirstResponder];
}
also,you can apply it to the other textFields or buttons,for example,you may add a hidden button to the view,when you click it to hide the keyboard.
NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24'
- it is a performance killer:
DATE()
for all rows, including those, that don't matchIt is much faster to use
SELECT * FROM tablename
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
as this will allow index use without calculation.
EDIT
As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read
SELECT * FROM tablename
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'
The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.
The keyword you're looking for is list comprehensions:
>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]
Answer to add multiple markers.
UPDATE (GEOCODE MULTIPLE ADDRESSES)
Here's the working Example Geocoding with multiple addresses.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(21.0000, 78.0000);
var mapOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = [
'New Delhi, India',
'Mumbai, India',
'Bangaluru, Karnataka, India',
'Hyderabad, Ahemdabad, India',
'Gurgaon, Haryana, India',
'Cannaught Place, New Delhi, India',
'Bandra, Mumbai, India',
'Nainital, Uttranchal, India',
'Guwahati, India',
'West Bengal, India',
'Jammu, India',
'Kanyakumari, India',
'Kerala, India',
'Himachal Pradesh, India',
'Shillong, India',
'Chandigarh, India',
'Dwarka, New Delhi, India',
'Pune, India',
'Indore, India',
'Orissa, India',
'Shimla, India',
'Gujarat, India'
];
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
As we can resolve this issue with setTimeout()
function.
Still we should not geocode known locations every time you load your page as said by @geocodezip
Another alternatives of these are explained very well in the following links:
How To Avoid GoogleMap Geocode Limit!
Here is yet another one-liner for you:
your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);
Yes you should not install react-scripts globally, it will not work.
I think i didn't use the --save when i first created the project (on another machine), so for me this fixed the problem :
npm install --save react react-dom react-scripts
Although adequate answers have already been given, I'd like to propose a less verbose solution, that can be used without the helper methods available in an MVC controller class. Using a third party library called "RazorEngine" you can use .Net file IO to get the contents of the razor file and call
string html = Razor.Parse(razorViewContentString, modelObject);
Get the third party library here.
UPDATE: My original answer doesn't cover iPad in desktop mode (the default changes to desktop mode in upcoming iPadOS 13 and higher).
That's fine for my usecases, if it's not for you, use this update:
// iPhone and iPad including iPadOS 13+ regardless of desktop mode settings
iOSiPadOS = /^iP/.test(navigator.platform) ||
/^Mac/.test(navigator.platform) && navigator.maxTouchPoints > 4;
^
first checks the starting position of the platform string and stops if there is no "iP" (faster than searching the long UA string until the end anyway)navigator.userAgent
check as navigator.platform
is much less likely fakedThis one is IMHO fast, save, and working well:
iOS = /^iP/.test(navigator.platform);
// or, if you prefer it verbose:
iOS = /^(iPhone|iPad|iPod)/.test(navigator.platform);
IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.
You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle
documentation just tells you the basics of using IDLE itself, and its idlelib
library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.
Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal
is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)
Learning to read the termcap
entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.
Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.
But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses
. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.
The simple thing is to put the script below the document, just before your closing </body>
tag:
<body>
<div id="main">
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
<script src="app.js"></script>
</body>
app.js file:
var main = new Vue({
el: '#main',
data: {
currentActivity: 'home'
}
});
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
For full support (additionally to @ricca 's verions).
wordsArray = ['hello', 'to', 'nice', 'day']_x000D_
yourString = 'Hello. Today is a nice day'.toLowerCase()_x000D_
result = wordsArray.every(w => yourString.includes(w))_x000D_
console.log('result:', result)
_x000D_
you mentioned "entire line" , so i assumed mystring is the entire line.
if "token" in mystring:
print(mystring)
however if you want to just get "token qwerty",
>>> mystring="""
... qwertyuiop
... asdfghjkl
...
... zxcvbnm
... token qwerty
...
... asdfghjklñ
... """
>>> for item in mystring.split("\n"):
... if "token" in item:
... print (item.strip())
...
token qwerty
You could do this simply by:
NOTE: you can find the right GApp version here:
This worked for me:
yourViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
Also; auto it = std::next(v.begin(), index);
Update: Needs a C++11x compliant compiler
If you migrate Visual Studio 2012 to 2013, then open *.csprorj project file with edior.
and check 'Project' tag's ToolsVersion element.
That's value 4.0
You make it to 12.0
From
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0"
To
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0"
Or If you build with msbuild then just specify VisualStudioVersion property
msbuild /p:VisualStudioVersion=12.0
Even shorter version of the solution from Dominic Zukiewicz:
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
But this means that you will trust all certificates. For a service that isn't just run locally, something a bit smarter will be needed. In the first instance you could use this code to just test whether it solves your problem.
This answer has been updated for Swift 4.2.
The general form for making and setting an attributed string is like this. You can find other common options below.
// create attributed string
let myString = "Swift Attributed String"
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
// set attributed text on a UILabel
myLabel.attributedText = myAttrString
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]
let myAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myAttribute = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ]
let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray
let myAttribute = [ NSAttributedString.Key.shadow: myShadow ]
The rest of this post gives more detail for those who are interested.
String attributes are just a dictionary in the form of [NSAttributedString.Key: Any]
, where NSAttributedString.Key
is the key name of the attribute and Any
is the value of some Type. The value could be a font, a color, an integer, or something else. There are many standard attributes in Swift that have already been predefined. For example:
NSAttributedString.Key.font
, value: a UIFont
NSAttributedString.Key.foregroundColor
, value: a UIColor
NSAttributedString.Key.link
, value: an NSURL
or NSString
There are many others. See this link for more. You can even make your own custom attributes like:
key name: NSAttributedString.Key.myName
, value: some Type.
if you make an extension:
extension NSAttributedString.Key {
static let myName = NSAttributedString.Key(rawValue: "myCustomAttributeKey")
}
You can declare attributes just like declaring any other dictionary.
// single attributes declared one at a time
let singleAttribute1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let singleAttribute2 = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
let singleAttribute3 = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]
// multiple attributes declared at once
let multipleAttributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.foregroundColor: UIColor.green,
NSAttributedString.Key.backgroundColor: UIColor.yellow,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]
// custom attribute
let customAttribute = [ NSAttributedString.Key.myName: "Some value" ]
Note the rawValue
that was needed for the underline style value.
Because attributes are just Dictionaries, you can also create them by making an empty Dictionary and then adding key-value pairs to it. If the value will contain multiple types, then you have to use Any
as the type. Here is the multipleAttributes
example from above, recreated in this fashion:
var multipleAttributes = [NSAttributedString.Key : Any]()
multipleAttributes[NSAttributedString.Key.foregroundColor] = UIColor.green
multipleAttributes[NSAttributedString.Key.backgroundColor] = UIColor.yellow
multipleAttributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.double.rawValue
Now that you understand attributes, you can make attributed strings.
Initialization
There are a few ways to create attributed strings. If you just need a read-only string you can use NSAttributedString
. Here are some ways to initialize it:
// Initialize with a string only
let attrString1 = NSAttributedString(string: "Hello.")
// Initialize with a string and inline attribute(s)
let attrString2 = NSAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])
// Initialize with a string and separately declared attribute(s)
let myAttributes1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let attrString3 = NSAttributedString(string: "Hello.", attributes: myAttributes1)
If you will need to change the attributes or the string content later, you should use NSMutableAttributedString
. The declarations are very similar:
// Create a blank attributed string
let mutableAttrString1 = NSMutableAttributedString()
// Initialize with a string only
let mutableAttrString2 = NSMutableAttributedString(string: "Hello.")
// Initialize with a string and inline attribute(s)
let mutableAttrString3 = NSMutableAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])
// Initialize with a string and separately declared attribute(s)
let myAttributes2 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let mutableAttrString4 = NSMutableAttributedString(string: "Hello.", attributes: myAttributes2)
As an example, let's create the attributed string at the top of this post.
First create an NSMutableAttributedString
with a new font attribute.
let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myString = NSMutableAttributedString(string: "Swift", attributes: myAttribute )
If you are working along, set the attributed string to a UITextView
(or UILabel
) like this:
textView.attributedText = myString
You don't use textView.text
.
Here is the result:
Then append another attributed string that doesn't have any attributes set. (Notice that even though I used let
to declare myString
above, I can still modify it because it is an NSMutableAttributedString
. This seems rather unSwiftlike to me and I wouldn't be surprised if this changes in the future. Leave me a comment when that happens.)
let attrString = NSAttributedString(string: " Attributed Strings")
myString.append(attrString)
Next we'll just select the "Strings" word, which starts at index 17
and has a length of 7
. Notice that this is an NSRange
and not a Swift Range
. (See this answer for more about Ranges.) The addAttribute
method lets us put the attribute key name in the first spot, the attribute value in the second spot, and the range in the third spot.
var myRange = NSRange(location: 17, length: 7) // range starting at location 17 with a lenth of 7: "Strings"
myString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: myRange)
Finally, let's add a background color. For variety, let's use the addAttributes
method (note the s
). I could add multiple attributes at once with this method, but I will just add one again.
myRange = NSRange(location: 3, length: 17)
let anotherAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
myString.addAttributes(anotherAttribute, range: myRange)
Notice that the attributes are overlapping in some places. Adding an attribute doesn't overwrite an attribute that is already there.
In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.
You need to find the location of what you're looking for with .indexOf()
then remove it with .splice()
function remove(arr, what) {
var found = arr.indexOf(what);
while (found !== -1) {
arr.splice(found, 1);
found = arr.indexOf(what);
}
}
var array = new Array();
array.push("A");
array.push("B");
array.push("C");
?
remove(array, 'B');
alert(array)????;
This will take care of all occurrences.
This is what the Python documentation has got to say about None
:
The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.
Changed in version 2.4: Assignments to None are illegal and raise a SyntaxError.
Note The names None and debug cannot be reassigned (assignments to them, even as an attribute name, raise SyntaxError), so they can be considered “true” constants.
Let's confirm the type of None
first
print type(None)
print None.__class__
Output
<type 'NoneType'>
<type 'NoneType'>
Basically, NoneType
is a data type just like int
, float
, etc. You can check out the list of default types available in Python in 8.15. types — Names for built-in types.
And, None
is an instance of NoneType
class. So we might want to create instances of None
ourselves. Let's try that
print types.IntType()
print types.NoneType()
Output
0
TypeError: cannot create 'NoneType' instances
So clearly, cannot create NoneType
instances. We don't have to worry about the uniqueness of the value None
.
Let's check how we have implemented None
internally.
print dir(None)
Output
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Except __setattr__
, all others are read-only attributes. So, there is no way we can alter the attributes of None
.
Let's try and add new attributes to None
setattr(types.NoneType, 'somefield', 'somevalue')
setattr(None, 'somefield', 'somevalue')
None.somefield = 'somevalue'
Output
TypeError: can't set attributes of built-in/extension type 'NoneType'
AttributeError: 'NoneType' object has no attribute 'somefield'
AttributeError: 'NoneType' object has no attribute 'somefield'
The above seen statements produce these error messages, respectively. It means that, we cannot create attributes dynamically on a None
instance.
Let us check what happens when we assign something None
. As per the documentation, it should throw a SyntaxError
. It means, if we assign something to None
, the program will not be executed at all.
None = 1
Output
SyntaxError: cannot assign to None
We have established that
None
is an instance of NoneType
None
cannot have new attributesNone
cannot be changed.NoneType
None
by assigning values to it.So, as mentioned in the documentation, None
can really be considered as a true constant
.
Happy knowing None
:)
Group Join method is unnecessary to achieve joining of two data sets.
Inner Join:
var qry = Foos.SelectMany
(
foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id),
(foo, bar) => new
{
Foo = foo,
Bar = bar
}
);
For Left Join just add DefaultIfEmpty()
var qry = Foos.SelectMany
(
foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id).DefaultIfEmpty(),
(foo, bar) => new
{
Foo = foo,
Bar = bar
}
);
EF and LINQ to SQL correctly transform to SQL. For LINQ to Objects it is beter to join using GroupJoin as it internally uses Lookup. But if you are querying DB then skipping of GroupJoin is AFAIK as performant.
Personlay for me this way is more readable compared to GroupJoin().SelectMany()
https://www.w3schools.com/tags/av_event_timeupdate.asp
// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");
// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};
function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
document.getElementById("demo").innerHTML = vid.currentTime;
}
see this answer - HTML form readonly SELECT tag/input
You should keep the select element disabled but also add another hidden input with the same name and value.
If you reenable your SELECT, you should copy it's value to the hidden input in an onchange event.
see this fiddle to demnstrate how to extract the selected value in a disabled select into a hidden field that will be submitted in the form.
<select disabled="disabled" id="sel_test">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="hidden" id="hdn_test" />
<div id="output"></div>
$(function(){
var select_val = $('#sel_test option:selected').val();
$('#hdn_test').val(select_val);
$('#output').text('Selected value is: ' + select_val);
});
hope that helps.
Here's a comparison of the two:
Entity Type
Message consumption
Use Case
Persistence
Consumer Type
Sample applications
You can try changing it to this:
If myTableData.Rows.Count > 0 Then
For i As Integer = 0 To myTableData.Rows.Count - 1
''Dim DataType() As String = myTableData.Rows(i).Item(1)
ListBox2.Items.Add(myTableData.Rows(i)(1))
Next
End If
Note: Your loop needs to be one less than the row count since it's a zero-based index.
Firefox Developer Edition (59.0b6) has Scratchpad (Shift +F4) where you can run javascript
For people coming to this late: Java 7 adds named groups. Matcher.group(String groupName) documentation.
In our case on IIS 8 we found the error was produced when attempting to view Authentication" for a site, when:
Marking the site Feature Delegation "Authentication - Windows" = "Read/Write", the error went away. It appears that, with the feature marked "Read Only", the web.config is not allowed to reference it at all even to disable it, as this apparently constitutes a write.
for SQL > odd:
select * from id in(select id from employee where id%2=1)
for SQL > Even:
select * from id in(select id from employee where id%2=0).....f5
the best solution is to fork react-scripts
, this is actually mentioned in the official documentation, see: Alternatives to Ejecting