The Icon property for a project specifies the icon file (.ico) that will be displayed for the compiled application in Windows Explorer and in the Windows taskbar.
The Icon property can be accessed in the Application pane of the Project Designer; it contains a list of icons that have been added to a project either as resources or as content files.
To specify an application icon
- With a project selected in Solution Explorer, on the Project menu click Properties.
- Select the Application pane.
- Select an icon (.ico) file from the Icon drop-down list.
To specify an application icon and add it to your project
- With a project selected in Solution Explorer, on the Project menu, click Properties.
- Select the Application pane.
- Select Browse from the Icon drop-down list and browse to the location of the icon file that you want.
The icon file is added to your project as a content file and can be seen on top left corner.
And if you want to show separate icons for every form you have to go to each form's properties, select icon attribute and browse for an icon you want.
Here's MSDN link for the same purpose...
Hope this helps.
Response.Redirect
simply sends a message (HTTP 302) down to the browser.
Server.Transfer
happens without the browser knowing anything, the browser request a page, but the server returns the content of another.
This works for me.
Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
So if you want to access your domain name do consider to include the application name in case of:
====================================
For the dev.x.us/web
it return this strong text
Example with IHttpActionResult
in ApiController
.
[HttpGet]
[Route("file/{id}/")]
public IHttpActionResult GetFileForCustomer(int id)
{
if (id == 0)
return BadRequest();
var file = GetFile(id);
IHttpActionResult response;
HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
responseMsg.Content = new ByteArrayContent(file.SomeData);
responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;
responseMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response = ResponseMessage(responseMsg);
return response;
}
If you don't want to download the PDF and use a browsers built in PDF viewer instead remove the following two lines:
responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;
There are three ways to add your filter,
@Component
@Bean
with Filter
type in Spring @Configuration
@Bean
with FilterRegistrationBean
type in Spring @Configuration
Either #1 or #2 will do if you want your filter applies to all requests without customization, use #3 otherwise. You don't need to specify component scan for #1 to work as long as you place your filter class in the same or sub-package of your SpringApplication
class. For #3, use along with #2 is only necessary when you want Spring to manage your filter class such as have it auto wired dependencies. It works just fine for me to new my filter which doesn't need any dependency autowiring/injection.
Although combining #2 and #3 works fine, I was surprised it doesn't end up with two filters applying twice. My guess is that Spring combines the two beans as one when it calls the same method to create both of them. In case you want to use #3 alone with authowiring, you can AutowireCapableBeanFactory
. The following is an example,
private @Autowired AutowireCapableBeanFactory beanFactory;
@Bean
public FilterRegistrationBean myFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
Filter myFilter = new MyFilter();
beanFactory.autowireBean(myFilter);
registration.setFilter(myFilter);
registration.addUrlPatterns("/myfilterpath/*");
return registration;
}
%pip install fedex #fedex = package name
in 2019.
In older versions of conda:
import sys
!{sys.executable} -m pip install fedex #fedex = package name
*note - you do need to import sys
Note : This answer is now out-of-date. This changes the theme in "preview" only as @imjohnking and @john-ktejik pointed out. As @Shahzeb mentioned, theme can modified in res>values>styles
Android Studio 0.8.2 provides a slightly easier way to change the theme. In the preview window, you can select the theme of "Holo.Light.DarkActionBar" by clicking on the theme combo box just above the phone.
Or do a ctrl + click on the @style/AppTheme in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.
When using the Support Library, you must instead use the Theme.AppCompat themes:
Source http://forums.udacity.com/questions/100200635/choosing-theme-in-android-studio-08x
on your terminal run this command on your ionic project folder ionic info
and you will get the following :
cli packages: (/usr/local/lib/node_modules)
@ionic/cli-utils : 1.19.2
ionic (Ionic CLI) : 3.20.0
global packages:
cordova (Cordova CLI) : 8.0.0
local packages:
@ionic/app-scripts : 3.1.8
Cordova Platforms : android 7.0.0 ios 4.5.5
Ionic Framework : ionic-angular 3.9.2
System:
Node : v8.9.3
npm : 6.1.0
OS : macOS
Xcode : Xcode 10.1 Build version 10B61
Environment Variables:
ANDROID_HOME : not set
Misc:
backend : pro
Regex: match everything but:
foo
):
world.
at the end):
foo
) (no POSIX compliant patern, sorry):
|
symbol):
foo
):
cat
): /cat(*SKIP)(*FAIL)|[^c]*(?:c(?!at)[^c]*)*/i
or /cat(*SKIP)(*FAIL)|(?:(?!cat).)+/is
(cat)|[^c]*(?:c(?!at)[^c]*)*
(or (?s)(cat)|(?:(?!cat).)*
, or (cat)|[^c]+(?:c(?!at)[^c]*)*|(?:c(?!at)[^c]*)+[^c]*
) and then check with language means: if Group 1 matched, it is not what we need, else, grab the match value if not empty[^a-z]+
(any char other than a lowercase ASCII letter)|
: [^|]+
Demo note: the newline \n
is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.
Anchor note: In many languages, use \A
to define the unambiguous start of string, and \z
(in Python, it is \Z
, in JavaScript, $
is OK) to define the very end of the string.
Dot note: In many flavors (but not POSIX, TRE, TCL), .
matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s
in PCRE/Boost/.NET/Python/Java and /m
in Ruby) for the .
to match any char including a newline.
Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n
for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\.
will be declared as "world\\."
, or use a character class: "world[.]"
). Use raw string literals (Python r'\bworld\b'
), C# verbatim string literals @"world\."
, or slashy strings/regex literal notations like /world\./
.
Nowadays you can also use lazy_eval
function from lazyeval
package.
> lazyeval::lazy_eval("5+5")
[1] 10
I would like to add that if you want to do this process automatically (download, stop and restart a new container with the same settings as described by @Yaroslav) you can use WatchTower. A program that auto updates your containers when they are changed https://github.com/v2tec/watchtower
I've found timezone.make_aware(datetime.datetime.now())
is helpful in django (I'm on 1.9.1). Unfortunately you can't simply make a datetime
object offset-aware, then timetz()
it. You have to make a datetime
and make comparisons based on that.
If you're using Anaconda to manage Python on your system, you can install it with:
$ conda install pyqt=4
Omit the =4
to install the most current version.
Answer from How to install PyQt4 in anaconda?
Ben is completely correct in his answer - so keep what he says in mind. What I'm about to tell you isn't a full explanation, but it's a very easy way to remember how e.target
, e.currentTarget
work in relation to mouse events and the display list:
e.target
= The thing under the mouse (as ben says... the thing that triggers the event).
e.currentTarget
= The thing before the dot... (see below)
So if you have 10 buttons inside a clip with an instance name of "btns" and you do:
btns.addEventListener(MouseEvent.MOUSE_OVER, onOver);
// btns = the thing before the dot of an addEventListener call
function onOver(e:MouseEvent):void{
trace(e.target.name, e.currentTarget.name);
}
e.target
will be one of the 10 buttons and e.currentTarget
will always be the "btns" clip.
It's worth noting that if you changed the MouseEvent to a ROLL_OVER or set the property btns.mouseChildren
to false, e.target
and e.currentTarget
will both always be "btns".
I would do it this way
$("#idElement").val('optionValue').trigger('change');
No need for an external library if you use Nodejs all you need to do is import the file system module. feel free to edit the code below: const fs = require('fs')
const path = './file.txt'
fs.access(path, fs.F_OK, (err) => {
if (err) {
console.error(err)
return
}
//file exists
})
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script
. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat
. This will be in the $_POST
array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready();
enviroment
var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;
) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts()
function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100
or $('footer').offset().top
for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.log
s in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.
I compare only solutions A-F because they give valid result for all cased used in snippet in details section. For all browsers
in
(A) is fast or fastesthas
(B) is slowestI perform 4 tests cases:
Below snippet presents differences between solutions A B C D E F G H I J K
// SO https://stackoverflow.com/q/135448/860099
// src: https://stackoverflow.com/a/14664748/860099
function A(x) {
return 'key' in x
}
// src: https://stackoverflow.com/a/11315692/860099
function B(x) {
return _.has(x, 'key')
}
// src: https://stackoverflow.com/a/40266120/860099
function C(x) {
return Reflect.has( x, 'key')
}
// src: https://stackoverflow.com/q/135448/860099
function D(x) {
return x.hasOwnProperty('key')
}
// src: https://stackoverflow.com/a/11315692/860099
function E(x) {
return Object.prototype.hasOwnProperty.call(x, 'key')
}
// src: https://stackoverflow.com/a/136411/860099
function F(x) {
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
return hasOwnProperty(x,'key')
}
// src: https://stackoverflow.com/a/135568/860099
function G(x) {
return typeof(x.key) !== 'undefined'
}
// src: https://stackoverflow.com/a/22740939/860099
function H(x) {
return x.key !== undefined
}
// src: https://stackoverflow.com/a/38332171/860099
function I(x) {
return !!x.key
}
// src: https://stackoverflow.com/a/41184688/860099
function J(x) {
return !!x['key']
}
// src: https://stackoverflow.com/a/54196605/860099
function K(x) {
return Boolean(x.key)
}
// --------------------
// TEST
// --------------------
let x1 = {'key': 1};
let x2 = {'key': "1"};
let x3 = {'key': true};
let x4 = {'key': []};
let x5 = {'key': {}};
let x6 = {'key': ()=>{}};
let x7 = {'key': ''};
let x8 = {'key': 0};
let x9 = {'key': false};
let x10= {'key': undefined};
let x11= {'nokey': 1};
let b= x=> x ? 1:0;
console.log(' 1 2 3 4 5 6 7 8 9 10 11');
[A,B,C,D,E,F,G,H,I,J,K ].map(f=> {
console.log(
`${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))} ${b(f(x11))} `
)})
console.log('\nLegend: Columns (cases)');
console.log('1. key = 1 ');
console.log('2. key = "1" ');
console.log('3. key = true ');
console.log('4. key = [] ');
console.log('5. key = {} ');
console.log('6. key = ()=>{} ');
console.log('7. key = "" ');
console.log('8. key = 0 ');
console.log('9. key = false ');
console.log('10. key = undefined ');
console.log('11. no-key ');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
And here are example results for chrome
I'd use datediff
, and not care about format conversions:
SELECT *
FROM mytable
WHERE DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3
In addition to existing answers:
RUN apt-get update && apt-get install -y gnupg
-y flag agrees to terms during installation process. It is important not to break the build
We can add for all devices with platform specific size
<link rel="apple-touch-icon" sizes="57x57" href="fav_icons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="fav_icons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="fav_icons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="fav_icons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="fav_icons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="fav_icons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="fav_icons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="fav_icons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="fav_icons/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="fav_icons/android-icon-192x192.pn">
<link rel="icon" type="image/png" sizes="32x32" href="fav_icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="fav_icons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="fav_icons/favicon-16x16.png">
###################################################
###################################################
###################################################
AVOID THIS
###################################################
###################################################
###################################################
/*for (Song s: songList){
System.out.println(s + "," + songList.indexOf(s);
}*/
it is possible in linked list.
you have to make toString() in song class. if you don't it will print out reference of the song.
probably irrelevant for you by now. ^_^
We have plenty of options to validate the react js forms. Maybe the npm packages have some own limitations. Based up on your needs you can choose the right validator packages. I would like to recommend some, those are listed below.
If anybody knows a better solution than this, please put it on the comment section for other people references.
You want to use single quotes:
if(c=='\0')
Double quotes (") are for strings, which are sequences of characters. Single quotes (') are for individual characters.
However, the end-of-line is represented by the newline character, which is '\n'.
Note that in both cases, the backslash is not part of the character, but just a way you represent special characters. Using backslashes you can represent various unprintable characters and also characters which would otherwise confuse the compiler.
"View -> Show Symbol -> uncheck Show All characters" may not work if you have pending update for notepad++. So update Notepad++ and then View -> Show Symbol -> uncheck Show All characters
Hope this is helpful!
If you want a super class to call a function from a subclass, the cleanest way is to define an abstract pattern, in this manner you explicitly know the method exists somewhere and must be overridden by a subclass.
This is as an example, normally you do not call a sub method within the constructor as the sub instance is not initialized yet… (reason why you have an "undefined" in your question's example)
abstract class A {
// The abstract method the subclass will have to call
protected abstract doStuff():void;
constructor(){
alert("Super class A constructed, calling now 'doStuff'")
this.doStuff();
}
}
class B extends A{
// Define here the abstract method
protected doStuff()
{
alert("Submethod called");
}
}
var b = new B();
Test it Here
And if like @Max you really want to avoid implementing the abstract method everywhere, just get rid of it. I don't recommend this approach because you might forget you are overriding the method.
abstract class A {
constructor() {
alert("Super class A constructed, calling now 'doStuff'")
this.doStuff();
}
// The fallback method the subclass will call if not overridden
protected doStuff(): void {
alert("Default doStuff");
};
}
class B extends A {
// Override doStuff()
protected doStuff() {
alert("Submethod called");
}
}
class C extends A {
// No doStuff() overriding, fallback on A.doStuff()
}
var b = new B();
var c = new C();
Try it Here
Answering for C++ 14,
Yes, you can get the first character of a string simply by the following code snippet.
string s = "Happynewyear";
cout << s[0];
if you want to store the first character in a separate string,
string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;
To Delete the duplicate record in a table.
delete from job s
where rowid < any
(select rowid from job k
where s.site_id = k.site_id and
s.title = k.title and
s.company = k.company);
or
delete from job s
where rowid not in
(select max(rowid) from job k
where s.site_id = k.site_id and
s.title = k.title and
s.company = k.company);
for this problem please follow bellow code:
$time= '10:09';
$new_time=date('H:i',strtotime($time.'+ 1 hour'));
echo $new_time;`
// now output will be: 11:09
You can use the unzip
command.
You can use querySelectorAll()
like this:
var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');
This translates to:
get all inputs with the attribute "value" and has the attribute "value" that is not blank.
In this demo, it disables the checkbox with a non-blank value.
You can't style the drop down box itself, only the input field. The box is rendered by the operating system.
If you want more control over the look of your input fields, you can always look into JavaScript solutions.
If, however, your intent was to remove the border from the input itself, your selector is wrong. Try this instead:
select#xyz {
border: none;
}
There's a good article on the topic in the Python wiki: Why Lists Can't Be Dictionary Keys. As explained there:
What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?
It can be done without really breaking any of the requirements, but it leads to unexpected behavior. Lists are generally treated as if their value was derived from their content's values, for instance when checking (in-)equality. Many would - understandably - expect that you can use any list [1, 2]
to get the same key, where you'd have to keep around exactly the same list object. But lookup by value breaks as soon as a list used as key is modified, and for lookup by identity requires you to keep around exactly the same list - which isn't requires for any other common list operation (at least none I can think of).
Other objects such as modules and object
make a much bigger deal out of their object identity anyway (when was the last time you had two distinct module objects called sys
?), and are compared by that anyway. Therefore, it's less surprising - or even expected - that they, when used as dict keys, compare by identity in that case as well.
The OData protocol is built on top of the AtomPub protocol. The AtomPub protocol is one of the best examples of REST API design. So, in a sense you are right - the OData is just another REST API and each OData implementation is a REST-ful web service.
The difference is that OData is a specific protocol; REST is architecture style and design pattern.
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from datetime import datetime
from time import mktime
dt = datetime.fromtimestamp(mktime(struct))
You can use curl
in order to both fetch the data, and be identified (for both "basic" and "digest" auth), without requiring extended permissions (like exec or allow_url_fopen).
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/file.xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
$result = curl_exec($ch);
curl_close($ch);
Your result will then be stored in the $result
variable.
There is a simple solution I learned with "We <3 Swift" if you can't either import Foundation, use round() and/or does not want a String:
var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0
result: 31.726
Oh, I just found that command on PostgreSQL forum:
SELECT * FROM pg_stat_activity;
An alternative is to use the vroom
package. Now on CRAN.
vroom
doesn't load the entire file, it indexes where each record is located, and is read later when you use it.
Only pay for what you use.
See Introduction to vroom, Get started with vroom and the vroom benchmarks.
The basic overview is that the initial read of a huge file, will be much faster, and subsequent modifications to the data may be slightly slower. So depending on what your use is, it could be the best option.
See a simplified example from vroom benchmarks below, the key parts to see is the super fast read times, but slightly sower operations like aggregate etc..
package read print sample filter aggregate total
read.delim 1m 21.5s 1ms 315ms 764ms 1m 22.6s
readr 33.1s 90ms 2ms 202ms 825ms 34.2s
data.table 15.7s 13ms 1ms 129ms 394ms 16.3s
vroom (altrep) dplyr 1.7s 89ms 1.7s 1.3s 1.9s 6.7s
I have started writing one tutorial for everyone on this topic, see making gadgets for Windows 7.
Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).
I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number)
.
I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:
DECLARE
DNO NUMBER;
MAXSAL NUMBER;
BEGIN
DNO := NULL;
GET_MAXSAL_BY_DEPT(
DNO => DNO,
MAXSAL => MAXSAL
);
DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;
I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:
Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc.
To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor
.
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
-- Modify the code to output the variable
-- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;
However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
v_rec emp%rowtype;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
loop
fetch v_Return into v_rec;
exit when v_Return%notfound;
DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
end loop;
END;
The output from the same location:
Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc.
Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:
var rc refcursor
exec :rc := get_emps_by_dept(30)
print rc
In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).
The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.
"When I type just
var rc refcursor;
and select it and run it, I get this error (GUI):"
There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor
and click Execute Statement
(or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script
(or F5 ), even for a single line of SQL*Plus.
"I am so close ... please help."
You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:
exec :rc := get_account(1)
What you need is something like the following. I have used the named notation for clarity.
var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor
exec :tran_cnt := 0
exec :msg_cnt := 123
exec get_account (Vret_val => :ret1,
Vtran_count => :tran_cnt,
Vmessage_count => :msg_cnt,
Vaccount_id => 1,
rc1 => :rc )
print tran_count
print rc
That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.
Download the file and from the same directory run docker build -t nodebb .
This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb
(you can change nodebb to your own name).
Last but not least, I've found this page. Is quite complete the cause and further explanation.
You want to call .name on the object's class:
result.class.name
those scripts don't accomplish all the problem...Try this better:
du -ha | grep -i -o "\./.*" | grep -v "\.svn\|another_file\|another_folder" | xargs grep -i -n "$1"
this script is so better, because it uses "real" regular expressions to avoid directories from search. just separate folder or file names with "\|" on the grep -v
enjoy it! found on my linux shell! XD
just go to your angular project directory via terminal and ng -v
give all information like this
Angular CLI: 1.7.4
Node: 8.11.1
OS: linux x64
Angular: 5.2.11
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
@angular/cli: 1.7.4
@angular-devkit/build-optimizer: 0.3.2
@angular-devkit/core: 0.3.2
@angular-devkit/schematics: 0.3.2
@ngtools/json-schema: 1.2.0
@ngtools/webpack: 1.10.2
@schematics/angular: 0.3.2
@schematics/package-update: 0.3.2
typescript: 2.5.3
webpack: 3.11.0
If you check ng-v
outside angular project directoty then it will show only angular-cli version.
Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:
.flex-row-container {_x000D_
background: #aaa;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
flex: 1 1 30%; /*grow | shrink | basis */_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
background-color: #fff4e6;_x000D_
border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
<div class="flex-row-item">1</div>_x000D_
<div class="flex-row-item">2</div>_x000D_
<div class="flex-row-item">3</div>_x000D_
<div class="flex-row-item">4</div>_x000D_
<div class="flex-row-item">5</div>_x000D_
<div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
Hope this helps someone else.
The error possibly comes because of the different structure of the code that you are committing and that present on GitHub. You may refer to: How to deal with "refusing to merge unrelated histories" error:
$ git pull --allow-unrelated-histories
$ git push -f origin master
You are attempting to attach an event listener function before the element is loaded. Place fun()
inside an onload
event listener function. Call f1()
within this function, as the onclick
attribute will be ignored.
function f1() {
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
}
window.onload = function() {
document.getElementById("Save").onclick = function fun() {
alert("hello");
f1();
//validation code to see State field is mandatory.
}
}
I solved this in a somewhat different way. Here's what happened.
First, I popped on the wrong branch and got conflicts. The stash remained intact but the index was in conflict resolution, blocking many commands.
A simple git reset HEAD
aborted the conflict resolution and left the uncommitted (and UNWANTED) changes.
Several git co <filename>
reverted the index to the initial state. Finally, I switched branch with git co <branch-name>
and run a new git stash pop
, which resolved without conflicts.
What I have found is that simply wrapping code in the componentDidMount
or componentDidUpdate
with a setTimeout
with a time of 0 milliseconds ensures that the browser DOM has been updated with the React changes before executing the setTimeout
function.
Like this:
componentDidMount() {
setTimeout(() => {
$("myclass") // $ is available here
}, 0)
}
This puts the anonymous function on the JS Event Queue to run immediately after the currently running React stack frame has completed.
probably the onclick
handler should read onclick='hello();'
instead of onclick=hello();
You got the order wrong. The if
should be after the for
(unless it is in an if-else
ternary operator)
[y for y in a if y not in b]
This would work however:
[y if y not in b else other_value for y in a]
zzzzBov's answer above is good, but it does not account for stray closing tags, like for example:
/<[a-z][\s\S]*>/i.test('foo </b> bar'); // false
A version that also catches closing tags could be this:
/<[a-z/][\s\S]*>/i.test('foo </b> bar'); // true
If you handle the draw.dt event after page.dt, you can detect exactly after moving the page. After work, draw.dt must be unbind
$(document).on("page.dt", () => {
$(document).on("draw.dt", changePage);
});
const changePage = () => {
// TODO
$(document).unbind("draw.dt", changePage);
}
import time
def timer(n):
while n!=0:
n=n-1
time.sleep(n)#time.sleep(seconds) #here you can mention seconds according to your requirement.
print "00 : ",n
timer(30) #here you can change n according to your requirement.
Following is the example code for how to use foreach in golang
package main
import (
"fmt"
)
func main() {
arrayOne := [3]string{"Apple", "Mango", "Banana"}
for index,element := range arrayOne{
fmt.Println(index)
fmt.Println(element)
}
}
This is a running example https://play.golang.org/p/LXptmH4X_0
I did something like this. I passed "fragmentType" and created two ViewHolders
and on basis of this, i classified my Layouts accordingly in a single adapter that can have different Layouts
and LayoutManagers
private Context mContext;
protected IOnLoyaltyCardCategoriesItemClicked mListener;
private String fragmentType;
private View view;
public LoyaltyCardsCategoriesRecyclerViewAdapter(Context context, IOnLoyaltyCardCategoriesItemClicked itemListener, String fragmentType) {
this.mContext = context;
this.mListener = itemListener;
this.fragmentType = fragmentType;
}
public class LoyaltyCardCategoriesFragmentViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView lc_categories_iv;
private TextView lc_categories_name_tv;
private int pos;
public LoyaltyCardCategoriesFragmentViewHolder(View v) {
super(v);
view.setOnClickListener(this);
lc_categories_iv = (ImageView) v.findViewById(R.id.lc_categories_iv);
lc_categories_name_tv = (TextView) v.findViewById(R.id.lc_categories_name_tv);
}
public void setData(int pos) {
this.pos = pos;
lc_categories_iv.setImageResource(R.mipmap.ic_launcher);
lc_categories_name_tv.setText("Loyalty Card Categories");
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onLoyaltyCardCategoriesItemClicked(pos);
}
}
}
public class MyLoyaltyCardsFragmentTagViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageButton lc_categories_btn;
private int pos;
public MyLoyaltyCardsFragmentTagViewHolder(View v) {
super(v);
lc_categories_btn = (ImageButton) v.findViewById(R.id.lc_categories_btn);
lc_categories_btn.setOnClickListener(this);
}
public void setData(int pos) {
this.pos = pos;
lc_categories_btn.setImageResource(R.mipmap.ic_launcher);
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onLoyaltyCardCategoriesItemClicked(pos);
}
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (fragmentType.equalsIgnoreCase(Constants.LoyaltyCardCategoriesFragmentTag)) {
view = LayoutInflater.from(mContext).inflate(R.layout.loyalty_cards_categories_frag_item, parent, false);
return new LoyaltyCardCategoriesFragmentViewHolder(view);
} else if (fragmentType.equalsIgnoreCase(Constants.MyLoyaltyCardsFragmentTag)) {
view = LayoutInflater.from(mContext).inflate(R.layout.my_loyalty_cards_categories_frag_item, parent, false);
return new MyLoyaltyCardsFragmentTagViewHolder(view);
} else {
return null;
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (fragmentType.equalsIgnoreCase(Constants.LoyaltyCardCategoriesFragmentTag)) {
((LoyaltyCardCategoriesFragmentViewHolder) holder).setData(position);
} else if (fragmentType.equalsIgnoreCase(Constants.MyLoyaltyCardsFragmentTag)) {
((MyLoyaltyCardsFragmentTagViewHolder) holder).setData(position);
}
}
@Override
public int getItemCount() {
return 7;
}
}
Statements a == object2
and a.equals(object2)
both will always return false
because a
is a string
while object2
is an instance of MyClass
A Subquery in the Select clause, as in your case, is also known as a Scalar Subquery, which means that it's a form of expression. Meaning that it can only return one value.
I'm afraid you can't return multiple columns from a single Scalar Subquery, no.
Here's more about Oracle Scalar Subqueries:
http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions010.htm#i1033549
There is a few benefits of using modules. You can use it only with Apple's framework unless module map is created. @import
is a bit similar to pre-compiling headers files when added to .pch
file which is a way to tune app the compilation process. Additionally you do not have to add libraries in the old way, using @import
is much faster and efficient in fact. If you still look for a nice reference I will highly recommend you reading this article.
You need something like a full outer join. System.Linq.Enumerable has no method that implements a full outer join, so we have to do it ourselves.
var dict1 = list1.ToDictionary(l1 => l1.Name);
var dict2 = list2.ToDictionary(l2 => l2.Name);
//get the full list of names.
var names = dict1.Keys.Union(dict2.Keys).ToList();
//produce results
var result = names
.Select( name =>
{
Person p1 = dict1.ContainsKey(name) ? dict1[name] : null;
Person p2 = dict2.ContainsKey(name) ? dict2[name] : null;
//left only
if (p2 == null)
{
p1.Change = 0;
return p1;
}
//right only
if (p1 == null)
{
p2.Change = 0;
return p2;
}
//both
p2.Change = p2.Value - p1.Value;
return p2;
}).ToList();
Run this command:
rvm get stable --auto-dotfiles
and make sure to read all the output. RVM
will tell you if something is wrong, which in your case might be because GEM_HOME
is set to something different then PATH
.
Similar to @joran's answer. Reshape the df so that the prices for each product are in different columns:
xx <- reshape(df, idvar=c("skew","version","color"),
v.names="price", timevar="product", direction="wide")
xx will have columns price.p1, ... price.p4, so:
ggp <- ggplot(xx,aes(x=price.p1, y=price.p3, color=factor(skew))) +
geom_point(shape=19, size=5)
ggp + facet_grid(color~version)
gives the result from your image.
I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.
For example:
$("#id_form").on("submit", function(){
//Code: Action (like ajax...)
return false;
})
Assuming you can put ID's on the inputs:
$('#name').change(function() {
$('#firstname').val($(this).val());
});
Otherwise you'll have to select using the names:
$('input[name="name"]').change(function() {
$('input[name="firstname"]').val($(this).val());
});
What you (probably want) are Flex 2.5.4 (some people are now "maintaining" it and producing newer versions, but IMO they've done more to screw it up than fix any real shortcomings) and byacc 1.9 (likewise). (Edit 2017-11-17: Flex 2.5.4 is not available on Sourceforge any more, and the Flex github repository only goes back to 2.5.5. But you can apparently still get it from a Gnu ftp server at ftp://ftp.gnu.org/old-gnu/gnu-0.2/src/flex-2.5.4.tar.gz.)
Since it'll inevitably be recommended, I'll warn against using Bison. Bison was originally written by Robert Corbett, the same guy who later wrote Byacc, and he openly states that at the time he didn't really know or understand what he was doing. Unfortunately, being young and foolish, he released it under the GPL and now the GPL fans push it as the answer to life's ills even though its own author basically says it should be thought of as essentially a beta test product -- but by the convoluted reasoning of GPL fans, byacc's license doesn't have enough restrictions to qualify as "free"!
There is a builtin environment: browser
that includes window
.
Example .eslintrc.json
:
"env": {
"browser": true,
"node": true,
"jasmine": true
},
More information: http://eslint.org/docs/user-guide/configuring.html#specifying-environments
Also see the package.json
answer by chevin99 below.
I would do something like this:
;WITH x
AS (SELECT *,
Row_number()
OVER(
partition BY employeeid
ORDER BY datestart) rn
FROM employeehistory)
SELECT *
FROM x x1
LEFT OUTER JOIN x x2
ON x1.rn = x2.rn + 1
Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.
ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.
OU=Your_OU,OU=other_ou,dc=example,dc=com
You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain
Now i miss a parameter to authenticate, this works the same as the path for the username
CN=username,OU=users,DC=example,DC=com
Contrary to what pointy says, the blur()
method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Javascript test</title>
<script type="text/javascript" language="javascript">
window.onload = function()
{
var field = document.getElementById("field");
var link = document.getElementById("link");
var output = document.getElementById("output");
field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
link.onmouseover = function() { field.blur(); };
};
</script>
</head>
<body>
<form name="MyForm">
<input type="text" name="field" id="field" />
<a href="javascript:void(0);" id="link">Blur field on hover</a>
<div id="output"></div>
</form>
</body>
</html>
Note that I used link.onmouseover
instead of link.onclick
, because otherwise the click itself would have removed the focus.
Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" )
. After the required positional arguments, you can specify specific optional arguments by name.
in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.
Well, my solution is sort of hack, but it works and I am using it.
1vw = 1% of viewport width
1vh = 1% of viewport height
1vmin = 1vw or 1vh, whichever is smaller
1vmax = 1vw or 1vh, whichever is larger
h1 {
font-size: 5.9vw;
}
h2 {
font-size: 3.0vh;
}
p {
font-size: 2vmin;
}
The GPS icon seems to change its state according to received broadcast intents. You can change its state yourself with the following code samples:
Notify that the GPS has been enabled:
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
Notify that the GPS is receiving fixes:
Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
Notify that the GPS is no longer receiving fixes:
Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
Notify that the GPS has been disabled:
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
Example code to register receiver to the intents:
// MyReceiver must extend BroadcastReceiver
MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter("android.location.GPS_ENABLED_CHANGE");
filter.addAction("android.location.GPS_FIX_CHANGE");
registerReceiver(receiver, filter);
By receiving these broadcast intents you can notice the changes in GPS status. However, you will be notified only when the state changes. Thus it is not possible to determine the current state using these intents.
Doing the following in a command prompt works for me, also adding to my User environment variables worked fine as well:
set PATH=%PATH%;C:\Program Files\7-Zip\
echo %PATH%
7z
You should see as output (or something similar - as this is on my laptop running Windows 7):
C:\Users\Phillip>set PATH=%PATH%;C:\Program Files\7-Zip\
C:\Users\Phillip>echo %PATH%
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Wi
ndows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\
WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\To
ols\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Fil
es (x86)\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Notepad+
+;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\7-Zip\
C:\Users\Phillip>7z
7-Zip [64] 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]
[<@listfiles...>]
<Commands>
a: Add files to archive
b: Benchmark
d: Delete files from archive
e: Extract files from archive (without using directory names)
l: List contents of archive
t: Test integrity of archive
u: Update files to archive
x: eXtract files with full paths
<Switches>
-ai[r[-|0]]{@listfile|!wildcard}: Include archives
-ax[r[-|0]]{@listfile|!wildcard}: eXclude archives
-bd: Disable percentage indicator
-i[r[-|0]]{@listfile|!wildcard}: Include filenames
-m{Parameters}: set compression Method
-o{Directory}: set Output directory
-p{Password}: set Password
-r[-|0]: Recurse subdirectories
-scs{UTF-8 | WIN | DOS}: set charset for list files
-sfx[{name}]: Create SFX archive
-si[{name}]: read data from stdin
-slt: show technical information for l (List) command
-so: write data to stdout
-ssc[-]: set sensitive case mode
-ssw: compress shared files
-t{Type}: Set type of archive
-u[-][p#][q#][r#][x#][y#][z#][!newArchiveName]: Update options
-v{Size}[b|k|m|g]: Create volumes
-w[{path}]: assign Work directory. Empty path means a temporary directory
-x[r[-|0]]]{@listfile|!wildcard}: eXclude filenames
-y: assume Yes on all queries
You could use list comprehension:
with open("names", "r") as f:
names_list = [line.strip() for line in f if line.strip()]
Updated: Removed unnecessary readlines()
.
To avoid calling line.strip()
twice, you can use a generator:
names_list = [l for l in (line.strip() for line in f) if l]
I'm using a simplyfied version (just using position relative) based on @SimonEast answer:
li:before {
content: "\e080";
font-family: 'Glyphicons Halflings';
font-size: 9px;
position: relative;
margin-right: 10px;
top: 3px;
color: #ccc;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Parameter | openSession | getCurrentSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session creation | Always open new session | It opens a new Session if not exists , else use same session which is in current hibernate context. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session close | Need to close the session object once all the database operations are done | No need to close the session. Once the session factory is closed, this session object is closed. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Flush and close | Need to explicity flush and close session objects | No need to flush and close sessions , since it is automatically taken by hibernate internally. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Performance | In single threaded environment , it is slower than getCurrentSession | In single threaded environment , it is faster than openSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Configuration | No need to configure any property to call this method | Need to configure additional property: |
| | | <property name=""hibernate.current_session_context_class"">thread</property> |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
I ran into this problem when I checked out an older version of a repository from git. Git replaced my .py
files, but left the untracked .pyc
files. Since the .py
files and .pyc
files were out of sync, the import
command in a .py
file could not find the corresponding module in the .pyc
files.
The solution was simply to delete the .pyc
files, and let them be automatically regenerated.
The documentation makes indeed a difference between the purpose
An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.
and the use case
Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.
whose wording does not preclude other use cases in general. Since the primary purpose is to indicate a functional interface, your actual question boils down to “Are there other use cases for functional interfaces other than lambda expressions and method/constructor references?”
Since functional interface is a Java language construct defined by the Java Language Specification, only that specification can answer that question:
JLS §9.8. Functional Interfaces:
…
In addition to the usual process of creating an interface instance by declaring and instantiating a class (§15.9), instances of functional interfaces can be created with method reference expressions and lambda expressions (§15.13, §15.27).
So the Java Language Specification doesn’t say otherwise, the only use case mentioned in that section is that of creating interface instances with method reference expressions and lambda expressions. (This includes constructor references as they are noted as one form of method reference expression in the specification).
So in one sentence, no, there is no other use case for it in Java 8.
While this is usefull in rare cases (if that was not the case, the language would've allowed it directly), take a look at the Base from Member idiom. It's not a code free solution, you'd have to add an extra layer of inheritance, but it gets the job done. To avoid boilerplate code you could use boost's implementation
If you want timestamps that correspond to actual real times BUT also want them to be unique (for a given application instance), you can use the following code:
public class HiResDateTime
{
private static long lastTimeStamp = DateTime.UtcNow.Ticks;
public static long UtcNowTicks
{
get
{
long orig, newval;
do
{
orig = lastTimeStamp;
long now = DateTime.UtcNow.Ticks;
newval = Math.Max(now, orig + 1);
} while (Interlocked.CompareExchange
(ref lastTimeStamp, newval, orig) != orig);
return newval;
}
}
}
It's possible you forgot a sheet1
each time somewhere before the columns.count
, or it will count the activesheet
columns and not the sheet1
's.
Also, shouldn't it be xltoleft instead of xltoright? (Ok it is very late here, but I think I know my right from left) I checked it, you must write xltoleft.
lastColumn = Sheet1.Cells(1, sheet1.Columns.Count).End(xlToleft).Column
Maybe this way:
const m = new Map([["a", 1], ["b", 2], ["c", 3]]);
m.map((k, v) => [k, v * 2]); // Map { 'a' => 2, 'b' => 4, 'c' => 6 }
You would only need to monkey patch Map
before:
Map.prototype.map = function(func){
return new Map(Array.from(this, ([k, v]) => func(k, v)));
}
We could have wrote a simpler form of this patch:
Map.prototype.map = function(func){
return new Map(Array.from(this, func));
}
But we would have forced us to then write m.map(([k, v]) => [k, v * 2]);
which seems a bit more painful and ugly to me.
We could also map values only, but I wouldn't advice going for that solution as it is too specific. Nevertheless it can be done and we would have the following API:
const m = new Map([["a", 1], ["b", 2], ["c", 3]]);
m.map(v => v * 2); // Map { 'a' => 2, 'b' => 4, 'c' => 6 }
Just like before patching this way:
Map.prototype.map = function(func){
return new Map(Array.from(this, ([k, v]) => [k, func(v)]));
}
Maybe you can have both, naming the second mapValues
to make it clear that you are not actually mapping the object as it would probably be expected.
url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi
Function fncToLetters(vintCol As Integer) As String
Dim mstrDigits As String
' Convert a positive number n to its digit representation in base 26.
mstrDigits = ""
Do While vintCol > 0
mstrDigits = Chr(((vintCol - 1) Mod 26) + 65) & mstrDigits
vintCol = Int((vintCol - 1) / 26)
Loop
fncToLetters = mstrDigits
End Function
Like this:
#include <string>
#include <vector>
struct user
{
std::string username;
std::vector<unsigned char> userpassword;
};
int main()
{
user r; // r.username is "" and r.userpassword is empty
// ...
}
$start_date = date('Y-m-d h:m:s');
$end_date = date('Y-m-d h:m:s', strtotime($start_date . "+".$userSubscription['duration']." months") );
$user_subscription_array = array(
array(
'user_id' => $request->input('user_id'),
'user_subscription_plan_id' => $request->input('subscription_plan_id'),
'name' => $userSubscription['name'],
'description' => $userSubscription['description'],
'duration' => $userSubscription['duration'],
'start_datetime' => $start_date,
'end_datetime' => $end_date,
'amount' => $userSubscription['amount'],
'invoice_id' => '',
'transection_datetime' => '',
'created_by' => '1',
'status_id' => '1', ),
array(
'user_id' => $request->input('user_id'),
'user_subscription_plan_id' => $request->input('subscription_plan_id'),
'name' => $userSubscription['name'],
'description' => $userSubscription['description'],
'duration' => $userSubscription['duration'],
'start_datetime' => $start_date,
'end_datetime' => $end_date,
'amount' => $userSubscription['amount'],
'invoice_id' => '',
'transection_datetime' => '',
'created_by' => '1',
'status_id' => '1', )
);
dd(UserSubscription::insert($user_subscription_array));
UserSubscription
is my model name.
This will return "true" if insert successfully else "false".
Well, timing to the rescue again. It seems switch
is generally faster than if
statements.
So that, and the fact that the code is shorter/neater with a switch
statement leans in favor of switch
:
# Simplified to only measure the overhead of switch vs if
test1 <- function(type) {
switch(type,
mean = 1,
median = 2,
trimmed = 3)
}
test2 <- function(type) {
if (type == "mean") 1
else if (type == "median") 2
else if (type == "trimmed") 3
}
system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs
Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:
> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("mean") 709 771 864 951 16122411
2 test2("mean") 1007 1073 1147 1223 8012202
> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("trimmed") 733 792 843 944 60440833
2 test2("trimmed") 2022 2133 2203 2309 60814430
Final Update Here's showing how versatile switch
is:
switch(type, case1=1, case2=, case3=2.5, 99)
This maps case2
and case3
to 2.5
and the (unnamed) default to 99
. For more information, try ?switch
As of kafka 2.3.0 version, there is an alternate way to soft deletion of Kafka (old approach are deprecated ).
Update retention.ms to 1 sec (1000ms) then set it again after a min, to default setting i.e 7 days (168 hours, 604,800,000 in ms )
Soft deletion:- (rentention.ms=1000) (using kafka-configs.sh)
bin/kafka-configs.sh --zookeeper 192.168.1.10:2181 --alter --entity-name kafka_topic3p3r --entity-type topics --add-config retention.ms=1000
Completed Updating config for entity: topic 'kafka_topic3p3r'.
Setting to default:- 7 days (168 hours , retention.ms= 604800000)
bin/kafka-configs.sh --zookeeper 192.168.1.10:2181 --alter --entity-name kafka_topic3p3r --entity-type topics --add-config retention.ms=604800000
Since the remove method is depreciated in the mongoose library we can use the deleteMany function with no parameters passed.
Model.deleteMany();
This will delete all content of this particular Model and your collection will be empty.
You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)
usually the log file is in
/var/log/apache2/error.log
or
/var/log/httpd/error.log
Despite that the other answers are correct and thoroughly explained, I found some difficulties understanding them. Here is the method I used (Taken from here):
openssl pkcs12 -in filename.pfx -out cert.pem -nodes
Extracts the private key form a PFX to a PEM file:
openssl pkcs12 -in filename.pfx -nocerts -out key.pem
Exports the certificate (includes the public key only):
openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
Removes the password (paraphrase) from the extracted private key (optional):
openssl rsa -in key.pem -out server.key
just click file in your android studio then click Sync Project with Gradle Files..
if it won't work, click Build click Clean Project.
it always work for me
The following example shows the general best practice to implement IDisposable
interface. Reference
Keep in mind that you need a destructor(finalizer) only if you have unmanaged resources in your class. And if you add a destructor you should suppress Finalization in the Dispose, otherwise it will cause your objects resides in memory for two garbage cycles (Note: Read how Finalization works). Below example elaborate all above.
public class DisposeExample
{
// A base class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
public class MyResource: IDisposable
{
// Pointer to an external unmanaged resource.
private IntPtr handle;
// Other managed resource this class uses.
private Component component = new Component();
// Track whether Dispose has been called.
private bool disposed = false;
// The class constructor.
public MyResource(IntPtr handle)
{
this.handle = handle;
}
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
CloseHandle(handle);
handle = IntPtr.Zero;
// Note disposing has been done.
disposed = true;
}
}
// Use interop to call the method necessary
// to clean up the unmanaged resource.
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~MyResource()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
}
public static void Main()
{
// Insert code here to create
// and use the MyResource object.
}
}
There is a fully legit reason to use it in C#: if the code must be extensible from VB.NET as well. (Otherwise, I would not.)
Since VB.NET is is case insensitive, there is no simple way to access the protected field
member in this code:
public class CSharpClass
{
protected int field;
public int Field { get { return field; } }
}
E.g. this will access the property getter, not the field:
Public Class VBClass
Inherits CSharpClass
Function Test() As Integer
Return Field
End Function
End Class
Heck, I cannot even write field
in lowercase - VS 2010 just keeps correcting it.
In order to make it easily accessible to derived classes in VB.NET, one has to come up with another naming convention. Prefixing an underscore is probably the least intrusive and most "historically accepted" of them.
Two other ways are strcpy(str, "");
and string[0] = 0
To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.
#include <string.h>
...
int i=0;
for(i=0;i<strlen(string);i++)
{
string[i] = 0;
}
In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.
At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.
It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)
I hope this was useful for anybody ;)
In order to get drawn, divider of LinearLayout
must have some height while ColorDrawable
(which is essentially #00ff00
as well as any other hardcoded color) doesn't have. Simple (and correct) way to solve this, is to wrap your color into some Drawable
with predefined height, such as shape
drawable
For max value, we can write sql query as
select age from table_name order by age desc limit 1
same way we can write in mongodb too.
db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age
You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"
If your function resides in an mvc controller u can use the below code with a dictionary object of what you want to convert to json
Json(someDictionaryObj, JsonRequestBehavior.AllowGet);
Also try and look at system.web.script.serialization.javascriptserializer if you are using .net 3.5
as for your web request...it seems ok at first glance..
I would use something like this..
public void WebRequestinJson(string url, string postData)
{
StreamWriter requestWriter;
var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
}
May be you can make the post and json string a parameter and use this as a generic webrequest method for all calls.
As I learnd in university most of the answers above are right. In PRACTISE on different platforms (always using python) spawning multiple threads ends up like spawning one process. The difference is the multiple cores share the load instead of only 1 core processing everything at 100%. So if you spawn for example 10 threads on a 4 core pc, you will end up getting only the 25% of the cpus power!! And if u spawn 10 processes u will end up with the cpu processing at 100% (if u dont have other limitations). Im not a expert in all the new technologies. Im answering with own real experience background
I don't see any problem, unless you are not managing them using a connection pool.
If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.
From here: http://docs.oracle.com/javase/tutorial/information/glossary.html
field
property
attribute
variable
The clean way to do so is to pass a new instance of the created entity through the controller:
//GET
public ActionResult CreateNewMyEntity(string default_value)
{
MyEntity newMyEntity = new MyEntity();
newMyEntity._propertyValue = default_value;
return View(newMyEntity);
}
If you want to pass the default value through ActionLink
@Html.ActionLink("Create New", "CreateNewMyEntity", new { default_value = "5" })
I tested and used this command in kafka confluent V4.0.0
and apache kafka V 1.0.0 and 1.0.1
/opt/kafka/confluent-4.0.0/bin/kafka-configs --zookeeper XX.XX.XX.XX:2181 --entity-type topics --entity-name test --alter --add-config retention.ms=55000
test
is the topic name.
I think it works well in other versions too
Right...with strings...the moment you deviate from primitives or strings things change and you need to implement hashcode/equals to get the desired effect.
EDIT: Initialize your ArrayList<String>
then attempt to add an item.
This code will help you to make a result like FEB 17 20:49 .
String myTimestamp="2014/02/17 20:49";
SimpleDateFormat form = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Date date = null;
Date time = null;
try
{
date = form.parse(myTimestamp);
time = new Date(myTimestamp);
SimpleDateFormat postFormater = new SimpleDateFormat("MMM dd");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String newDateStr = postFormater.format(date).toUpperCase();
String newTimeStr = sdf.format(time);
System.out.println("Date : "+newDateStr);
System.out.println("Time : "+newTimeStr);
}
catch (Exception e)
{
e.printStackTrace();
}
Result :
Date : FEB 17
Time : 20:49
$(this).css('background-color', 'red');
If you have
varname <- c("a", "b", "d")
you can do
get(varname[1]) + 2
for
a + 2
or
assign(varname[1], 2 + 2)
for
a <- 2 + 2
So it looks like you use GET when you want to evaluate a formula that uses a variable (such as a concatenate), and ASSIGN when you want to assign a value to a pre-declared variable.
Syntax for assign: assign(x, value)
x: a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.
value: value to be assigned to x.
I solve the problem. So simple. Syntax error.
But I also want to know how to pass a function with parameters to view....
@Dan,
Do I not need msdtc enabled for transactions to work?
Only distributed transactions - Those that involve more than a single connection. Make doubly sure you are only opening a single connection within the transaction and it won't escalate - Performance will be much better too.
I'd say, it depends on your situation. For example, I work in local government, and we have lots of images like mugshots, etc. We don't have a high number of users, but we need to have good security and auditing around the data. The database is a better solution for us since it makes this easier and we aren't going to run into scaling problems.
Just do
LogManager.getLogManager().reset();
localhost:55828/token
(not localhost:55828/API/token
)[email protected]&password=Test123$&grant_type=password
When you use JavaScript to make post request, you may use following:
$http.post("localhost:55828/token",
"userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password",
{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
).success(function (data) {//...
See screenshots below from Postman:
A pure CSS solution with no wrapper div
or other useless code:
img {
object-fit: cover;
width:230px;
height:230px;
}
Press F11 to Build and the Run the program. Once you run the program, you will have a list of classes. Select your main class from the list and click ok to run.
I was not able to install cv2 on Anaconda-Jupyter notebook running on Ubuntu on Google Cloud Platform. But I found a way to do it as follows:
Run the following command from the ssh terminal and follow the instruction:
sudo apt-get install libsm6 libxrender1 libfontconfig1
Once its installed Open the Jupyter notebook and run following command:
!pip install opencv-contrib-python
Note: I tried to run this command: "sudo python3 -m pip install opencv-contrib-python"but it was showing an error. But above command worked for me.
Now refresh the notebook page and check whether it's installed or not by running import cv2
in the notebook.
This is the job for style
property:
document.getElementById("remember").style.visibility = "visible";
Java 8
To get body lines use escape()
body_line = escape("\n");
so
href = "mailto:[email protected]?body=hello,"+body_line+"I like this.";
here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.
$('html').click(function(e){
if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
// clicked menu content or children
} else {
// didnt click menu content
}
});
my actual code:
$('html').click(function(e){
if (e.target.id != 'datepicker'
&& $(e.target).parents('#datepicker').length == 0
&& !$(e.target).hasClass('datepicker')
) {
$('#datepicker').remove();
}
});
But I need the match result to be ... not in a match group...
For what you are trying to do, this should work. \K
resets the starting point of the match.
\bObject Name:\s+\K\S+
You can do the same for getting your Security ID
matches.
\bSecurity ID:\s+\K\S+
Use Do...Loop with Until keyword
num=0
Do Until //certain_condition_to_break_loop
num=num+1
Loop
This loop will continue to execute, Until the condition becomes true
While...Wend is the old syntax and does not provide feature to break loop! Prefer do while loops
Try the <wbr>
tag - not as elegant as the word-wrap
property that others suggested, but it's a working solution until all major browsers (read IE) implement CSS3.
Try getting the input stream from this you can then get the text data as so:-
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.mysite.se/index.asp?data=99");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
You can probably use other inputstream readers such as buffered reader also.
The problem is that when you open the connection - it does not 'pull' any data.
Here is a small improvement trick that allows sort 'val' inside the groups:
# 1. Data set
set.seed(100)
df <- data.frame(
cat = c(rep("aaa", 5), rep("ccc", 5), rep("bbb", 5)),
val = runif(15))
# 2. 'dplyr' approach
df %>%
arrange(cat, val) %>%
group_by(cat) %>%
mutate(id = row_number())
you can test if have exactly some values, by example:
for(MyBoolean b : MyBoolean.values()) {
switch(b) {
case TRUE:
break;
case FALSE:
break;
default:
throw new IllegalArgumentException(b.toString());
}
for(String s : new String[]{"TRUE", "FALSE" }) {
MyBoolean.valueOf(s);
}
If someone removes or adds a value, some of test fails.
I've solved this problem by using the search function on Docker's website where '*' is a valid search that returns 200k repositories and then I crawled each invididual page. HTML parsing allows me to extract all the image names on each page.
copying Superfly Jon's comment into an answer:
To create a new branch without committing on master
, you can use:
git checkout -b <branchname>
Very nice example using paste and substitute to typeset both symbols (mathplot) and variables at http://vis.supstat.com/2013/04/mathematical-annotation-in-r/
Here is a ggplot adaptation
library(ggplot2)
x_mean <- 1.5
x_sd <- 1.2
N <- 500
n <- ggplot(data.frame(x <- rnorm(N, x_mean, x_sd)),aes(x=x)) +
geom_bar() + stat_bin() +
labs(title=substitute(paste(
"Histogram of random data with ",
mu,"=",m,", ",
sigma^2,"=",s2,", ",
"draws = ", numdraws,", ",
bar(x),"=",xbar,", ",
s^2,"=",sde),
list(m=x_mean,xbar=mean(x),s2=x_sd^2,sde=var(x),numdraws=N)))
print(n)
For EntityFrameworkCore you can use the following:
Update-Database -Migration 0
This will remove all migrations from the database. Then you can use:
Remove-Migration
To remove your migration. Finally you can recreate your migration and apply it to the database.
Add-Migration Initialize
Update-Database
Tested on EFCore v2.1.0
Programatically: myTV.setText("My Text" + "\n" + myString);
If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();
Here's how I do it. Pretty brief and doesn't rely on temp tables.
CAST(year(TheDate) AS char(4)) + '-Q' +
CAST(CEILING(CAST(month(TheDate) AS decimal(9,2)) / 3) AS char(1))
As an example:
SELECT convert(char(10), getdate(), 101) AS TheDate,
CAST(year(getdate()) AS char(4)) + '-Q' +
CAST(CEILING(CAST(month(getdate()) AS decimal(4,2)) / 3) AS char(1)) AS SelectQuarter
This will return:
TheDate SelectQuarter
---------- -------------
07/10/2013 2013-Q3
Obviously the string itself can be changed to suit your own format. Hope this is helpful.
Copy your XML schema here & get the JSON schema code to the online tools which are available to generate JSON schema from XML schema.
Whether you are coding in Smalltalk or not Smalltalk Best Practice Patterns is a great read. Full of small observations that will change the way you code; for the better.
The only selector I see is a[id$="name"]
(all links with id finishing by "name") but it's not as restrictive as it should.
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
CNAME'ing a root record is technically not against RFC, but does have limitations meaning it is a practice that is not recommended.
Normally your root record will have multiple entries. Say, 3 for your name servers and then one for an IP address.
Per RFC:
If a CNAME RR is present at a node, no other data should be present;
And Per IETF 'Common DNS Operational and Configuration Errors' Document:
This is often attempted by inexperienced administrators as an obvious way to allow your domain name to also be a host. However, DNS servers like BIND will see the CNAME and refuse to add any other resources for that name. Since no other records are allowed to coexist with a CNAME, the NS entries are ignored. Therefore all the hosts in the podunk.xx domain are ignored as well!
References:
In case anybody has an issue with setting datetimepicker control to blank during the form load event, and then show the current date as needed, here is an example:
MAKE SURE THAT CustomFormat = " "
has same number of spaces (at least one space) in both methods
Private Sub setDateTimePickerBlank(ByVal dateTimePicker As DateTimePicker)
dateTimePicker.Visible = True
dateTimePicker.Format = DateTimePickerFormat.Custom
dateTimePicker.CustomFormat = " "
End Sub
Private Sub dateTimePicker_MouseHover(ByVal sender As Object, ByVal e As
System.EventArgs) Handles dateTimePicker.MouseHover
Dim dateTimePicker As DateTimePicker = CType(sender, DateTimePicker)
If dateTimePicker.Text = " " Then
dateTimePicker.Text = Format(DateTime.Now, "MM/dd/yyyy")
End If
End Sub
You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?
My solution for finding maximum values in columns:
df.ix[df.idxmax()]
, also minimum:
df.ix[df.idxmin()]
You can print some text by using SELECT
command like that:
SELECT 'some text'
Result:
+-----------+
| some text |
+-----------+
| some text |
+-----------+
1 row in set (0.02 sec)
It's hard to know how to help you without understanding the context / structure of your data, but I believe this might help you:
SELECT
SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count
,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count
,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count
FROM table
You need ReDim
:
m = 5
n = 8
Dim my_array()
ReDim my_array(1 To m, 1 To n)
For i = 1 To m
For j = 1 To n
my_array(i, j) = i * j
Next
Next
For i = 1 To m
For j = 1 To n
Cells(i, j) = my_array(i, j)
Next
Next
As others have pointed out, your actual problem would be better solved with ranges. You could try something like this:
Dim r1 As Range
Dim r2 As Range
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
totalRow = ws1.Range("A1").End(xlDown).Row
totalCol = ws1.Range("A1").End(xlToRight).Column
Set r1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(totalRow, totalCol))
Set r2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(totalRow, totalCol))
r2.Value = r1.Value
As Rob mentioned, you probably just want to print the float to 1 decimal place. In this case, you can do something like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
return 0;
}
If you want to actually round the stored value, that's a little more complicated. For one, your one-decimal-place representation will rarely have an exact analog in floating-point. If you just want to get as close as possible, something like this might do the trick:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
conver = conver*10.0f;
conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
conver = conver/10.0f;
//If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
//conver = roundf(conver*10.0f)/10.0f;
printf("conver is now %f\n",conver);
return 0;
}
I doubt this second example is what you're looking for, but I included it for completeness. If you do require representing your numbers in this way internally, and not just on output, consider using a fixed-point representation instead.
You can display the ActiveRecord generated SQL:
Before the query runs:
$this->db->_compile_select();
And after it has run:
$this->db->last_query();
You need to define a copy constructor, assignment, operator.
class Test {
Test(const Test &that); //Copy constructor
Test& operator= (const Test &rhs); //assignment operator
}
Your copy that is pushed on the queue is pointing to the same memory your original is. When the first is destructed, it deletes the memory. The second destructs and tries to delete the same memory.
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
input[type="button"]{
outline:none;
}
input[type="button"]::-moz-focus-inner {
border: 0;
}
/* Don't forget! User accessibility is important */
input[type="button"]:focus {
/* your custom focused styles here */
}
I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:
if len(my_list) == 0:
print "my_list is empty"
Angular elements (such as the root element of a directive) are jQuery [Lite] objects. This means we can register the event listener like so:
link($scope, $el) {
const fileInputSelector = '.my-file-input'
function setFile() {
// access file via $el.find(fileInputSelector).get(0).files[0]
}
$el.on('change', fileInputSelector, setFile)
}
This is jQuery event delegation. Here, the listener is attached to the root element of the directive. When the event is triggered, it will bubble up to the registered element and jQuery will determine if the event originated on an inner element matching the defined selector. If it does, the handler will fire.
Benefits of this method are:
ng-if
or ng-switch
)Please keep attention at this syntax:
* */6 * * *
This means 60 times (every minute) every 6 hours,
not
one time every 6 hours.
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
Weston Ruther built a similar thing using the WebKit proposal for css transitions:
http://weston.ruter.net/projects/jquery-css-transitions/
This implementation might be useful for you.
Swift 2.0 Works fine for me!
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
let edgeInsets = (screenWight - (CGFloat(elements.count) * 50) - (CGFloat(elements.count) * 10)) / 2
return UIEdgeInsetsMake(0, edgeInsets, 0, 0);
}
Where: screenWight: basically its my collection's width (full screen width) - I made constants: let screenWight:CGFloat = UIScreen.mainScreen().bounds.width because self.view.bounds shows every-time 600 - coz of SizeClasses elements - array of cells 50 - my manual cell width 10 - my distance between cells
By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);
It helps avoid having to write code like this:
[if ($this->uri->segment(3) === FALSE)
{
$product_id = 0;
}
else
{
$product_id = $this->uri->segment(3);
}]
3 options, same result:
1. All steps:
$ rake db:drop # deletes the database for the current env
$ rake db:create # creates the database for the current env
$ rake db:schema:load # loads the schema already generated from schema.rb / erases data
$ rake db:seed # seed with initial data
2. Reset:
$ rake db:reset # drop / schema:load / seed
3. Migrate:reset:
$ rake db:migrate:reset # drop / create / migrate
$ rake db:seed
Notes:
The following solution was implemented because recently our IDE stopped compiling and building [refresh or clean] on the standard Eclipse IDE for Java Developers version. We kept receiving the error "Your project contains error(s), please fix it before running it." We reviewed all errors, cleaned over and over, rebuilt and even created a new workspace and imported the files however nothing worked. Our product manager Johnpaul, found the error with in the compiled build path and even though it was a manual fix it would come back on the next refresh or rebuild so he recommended we back-up our work-space and do a complete re-install of the developers environment.
We made the switch as a recommendation we found from: http://knol.google.com/k/fred-grott/which-eclipse-package-for-android/166jfml0mowlh/18#report-comment-166jfml0mowlh.7wc65w
We now use the Eclipse IDE [Indigo]for Java and Report Developers Windows 64 Bit without a problem.
After the IDE broke we downloaded:
We then:
Next we:
Windows 64 Bit
We kept all of the default preferences and now everything is working perfectly again. Actually better as the rewrite also solved a few problems with our app not working on some devices. No idea as to why but we aren't complaining. Hope this helps as it is not a true install however a reinstall for Fall 2011 in a Windows 7 64 bit environment.
Open Notepad, create a file called XlsToCsv.vbs and paste this in:
if WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
Then from a command line, go to the folder you saved the .vbs file in and run:
XlsToCsv.vbs [sourcexlsFile].xls [destinationcsvfile].csv
This requires Excel to be installed on the machine you are on though.
seq -w
will detect the max input width and normalize the width of the output.
for num in $(seq -w 01 05); do
...
done
At time of writing this didn't work on the newest versions of OSX, so you can either install macports and use its version of seq
, or you can set the format explicitly:
seq -f '%02g' 1 3
01
02
03
But given the ugliness of format specifications for such a simple problem, I prefer the solution Henk and Adrian gave, which just uses Bash. Apple can't screw this up since there's no generic "unix" version of Bash:
echo {01..05}
Or:
for number in {01..05}; do ...; done
This can be done by using unlist
before as.vector
.
The result is the same as using the parameter use.names=FALSE
.
as.vector(unlist(myList))
A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.
For instance, a Dashboard has a speed
field in its state, and passes it to a Gauge child thats displays this speed. Its render
method is just return <Gauge speed={this.state.speed} />
. When the Dashboard calls this.setState({speed: this.state.speed + 1})
, the Gauge is re-rendered with the new value for speed
.
Just before this happens, Gauge's componentWillReceiveProps
is called, so that the Gauge has a chance to compare the new value to the old one.
WPF only
don't have the exact code to hand, but in a recent project I think I used MouseDown event and simply put this:
frmBorderless.DragMove();
In the schema you have in your question, child1
or child2
can appear in any order, any number of times. So this sounds like what you are looking for.
Edit: if you wanted only one of them to appear an unlimited number of times, the unbounded would have to go on the elements instead:
Edit: Fixed type in XML.
Edit: Capitalised O in maxOccurs
<xs:element name="foo">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element name="child1" type="xs:int" maxOccurs="unbounded"/>
<xs:element name="child2" type="xs:string" maxOccurs="unbounded"/>
</xs:choice>
</xs:complexType>
</xs:element>
You can wrap all tasks which can fail in block, and use ignore_errors: yes
with that block.
tasks:
- name: ls
command: ls -la
- name: pwd
command: pwd
- block:
- name: ls non-existing txt file
command: ls -la no_file.txt
- name: ls non-existing pic
command: ls -la no_pic.jpg
ignore_errors: yes
Read more about error handling in blocks here.
I now always use (even on Windows with GoW -- Gnu on Windows):
grep --include="*.xxx" -nRHI "my Text to grep" *
That includes the following options:
--include=PATTERN
Recurse in directories only searching file matching
PATTERN
.
-n, --line-number
Prefix each line of output with the line number within its input file.
(Note: phuclv adds in the comments that -n
decreases performance a lot so, so you might want to skip that option)
-R, -r, --recursive
Read all files under each directory, recursively; this is equivalent to the
-d recurse
option.
-H, --with-filename
Print the filename for each match.
-I
Process a binary file as if it did not contain matching data;
this is equivalent to the--binary-files=without-match
option.
And I can add 'i
' (-nRHIi
), if I want case-insensitive results.
I can get:
/home/vonc/gitpoc/passenger/gitlist/github #grep --include="*.php" -nRHI "hidden" *
src/GitList/Application.php:43: 'git.hidden' => $config->get('git', 'hidden') ? $config->get('git', 'hidden') : array(),
src/GitList/Provider/GitServiceProvider.php:21: $options['hidden'] = $app['git.hidden'];
tests/InterfaceTest.php:32: $options['hidden'] = array(self::$tmpdir . '/hiddenrepo');
vendor/klaussilveira/gitter/lib/Gitter/Client.php:20: protected $hidden;
vendor/klaussilveira/gitter/lib/Gitter/Client.php:170: * Get hidden repository list
vendor/klaussilveira/gitter/lib/Gitter/Client.php:176: return $this->hidden;
...
Although the question refers to only PhoneGap and iOS usage, and although it was already answered, I can add a few points to the broader question of detecting screen orientation with JS in 2019:
window.orientation
property is deprecated and not supported by Android browsers.There is a newer property that provides more information about the orientation - screen.orientation
. But it is still experimental and not supported by iOS Safari. So to achieve the best result you probably need to use the combination of the two: const angle = screen.orientation ? screen.orientation.angle : window.orientation
.
As @benallansmith mentioned in his comment, window.onorientationchange
event is fired before window.onresize
, so you won't get the actual dimensions of the screen unless you add some delay after the orientationchange event.
There is a Cordova Screen Orientation Plugin for supporting older mobile browsers, but I believe there is no need in using it nowadays.
There was also a screen.onorientationchange
event, but it is deprecated and should not be used. Added just for completeness of the answer.
In my use-case, I didn't care much about the actual orientation, but rather about the actual width and height of the window, which obviously changes with orientation. So I used resize
event to avoid dealing with delays between orientationchange
event and actualizing window dimensions:
window.addEventListener('resize', () => {
console.log(`Actual dimensions: ${window.innerWidth}x${window.innerHeight}`);
console.log(`Actual orientation: ${screen.orientation ? screen.orientation.angle : window.orientation}`);
});
Note 1: I used EcmaScript 6 syntax here, make sure to compile it to ES5 if needed.
Note 2: window.onresize
event is also fired when virtual keyboard is toggled, not only when orientation changes.
After I plotted all the lines, I was able to set the transparency of all of them as follows:
for l in fig_field.gca().lines:
l.set_alpha(.7)
EDIT: please see Joe's answer in the comments.
In addition to all the wonderful answers here, I'd like to throw in a special mention for the MySQLi and PDO libraries.
In order to...
The best option is to configure the libraries to throw exceptions.
Add this near the top of your script
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This is best placed before you use new mysqli()
or mysqli_connect()
.
Set the PDO::ATTR_ERRMODE
attribute to PDO::ERRMODE_EXCEPTION
on your connection instance. You can either do this in the constructor
$pdo = new PDO('driver:host=localhost;...', 'username', 'password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
or after creation
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
It seems like you can also use the patch command. Put the diff in the root of the repository and run patch
from the command line.
patch -i yourcoworkers.diff
or
patch -p0 -i yourcoworkers.diff
You may need to remove the leading folder structure if they created the diff without using --no-prefix
.
If so, then you can remove the parts of the folder that don't apply using:
patch -p1 -i yourcoworkers.diff
The -p(n) signifies how many parts of the folder structure to remove.
More information on creating and applying patches here.
You can also use
git apply yourcoworkers.diff --stat
to see if the diff by default will apply any changes. It may say 0 files affected if the patch is not applied correctly (different folder structure).
Often used with/as a part of OOAD and business modeling. The definition by Neil is correct, but it is basically identical to MVC, but just abstracted for the business. The "Good summary" is well done so I will not copy it here as it is not my work, more detailed but inline with Neil's bullet points.
In light of the passage of time, as people have mentioned, you can now safely just use:
li { cursor: pointer; }
Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class
myObj:any = {
doSomething: function () { console.log('doing something'); return 'doing something'; },
};
myArray:any;
constructor() { }
ngOnInit() {
this.myArray = [this.myObj];
}
You can use it in template html file as following:
<div>test-1: {{ myObj?.doSomething()}}</div>
<div>test-2: {{ myArray[0].doSomething()}}</div>
<div>test-3: {{ myArray[2]?.doSomething()}}</div>
You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.
In most cases, the JSON source (read as .json
file) is the most suitable config source.
Note: don't be confused when someone says that config file should be
appsettings.json
. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.
But, as the real world is complicated, there are a lot of different configuration providers:
and so on. You even could use/write a custom provider.
Actually, app.config
configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.
I'm assuming you mean a datetime picker in a winforms application.
in your code, you can do the following:
string theDate = dateTimePicker1.Value.ToShortDateString();
or, if you'd like to specify the format of the date:
string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:
Make sure you study this thread, as overriding a signed tag is not as easy:
git tag
man page seriously advised against a simple git tag -f B
to replace a tag name "A
"don't try to recreate a signed tag with git tag -f
(see the thread extract below)
(it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):
Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:
- in the tag object itself as a contents of 'tag' header (you can see it in output of "
git show <tag>
" and also in output of "git cat-file -p <tag>
", where<tag>
is heavyweight tag, e.g.v1.6.3
ingit.git
repository),- and also is default name of tag reference (reference in "
refs/tags/*
" namespace) pointing to a tag object.
Note that the tag reference (appropriate reference in the "refs/tags/*
" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3
', other can have in 'refs/tags/sub/v0.1.3
' for example.So when you create signed tag '
A
', you have the following situation (assuming that it points at some commit)
35805ce <--- 5b7b4ead <=== refs/tags/A
(commit) tag A
(tag)
Please also note that "
git tag -f A A
" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.If you do "
git tag -f -s A A
": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of-s
/-a
/-m
options is used to force annotated tag (creation of tag object), you will get the following situation
35805ce <--- 5b7b4ea <--- ada8ddc <=== refs/tags/A
(commit) tag A tag A
(tag) (tag)
Note also that "
git show A
" would show the whole chain down to the non-tag object...
Building on Lauritz` answer, here's a version with the following changes
__call__
instead of __getitem__
from bisect import bisect_right
class Interpolate:
def __init__(self, x_list, y_list):
if any(y - x <= 0 for x, y in zip(x_list, x_list[1:])):
raise ValueError("x_list must be in strictly ascending order!")
self.x_list = x_list
self.y_list = y_list
intervals = zip(x_list, x_list[1:], y_list, y_list[1:])
self.slopes = [(y2 - y1) / (x2 - x1) for x1, x2, y1, y2 in intervals]
def __call__(self, x):
if not (self.x_list[0] <= x <= self.x_list[-1]):
raise ValueError("x out of bounds!")
if x == self.x_list[-1]:
return self.y_list[-1]
i = bisect_right(self.x_list, x) - 1
return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
Example usage:
>>> interp = Interpolate([1, 2.5, 3.4, 5.8, 6], [2, 4, 5.8, 4.3, 4])
>>> interp(4)
5.425
You can list all unreachable commits by writing this command in terminal -
git fsck --unreachable
Check unreachable commit hash -
git show hash
Finally apply if you find the stashed item -
git stash apply hash
You can unbind your handler with .off
, but there's a caveat; if you're doing this just prevent the handler from being triggered again while it's already running, you need to defer rebinding the handler.
For example, consider this code, which uses a 5-second hot sleep to simulate something synchronous and computationally expensive being done from within the handler (like heavy DOM manipulation, say):
<button id="foo">Click Me!</div>
<script>
function waitForFiveSeconds() {
var startTime = new Date();
while (new Date() - startTime < 5000) {}
}
$('#foo').click(function handler() {
// BAD CODE, DON'T COPY AND PASTE ME!
$('#foo').off('click');
console.log('Hello, World!');
waitForFiveSeconds();
$('#foo').click(handler);
});
</script>
This won't work. As you can see if you try it out in this JSFiddle, if you click the button while the handler is already executing, the handler will execute a second time once the first execution finishes. What's more, at least in Chrome and Firefox, this would be true even if you didn't use jQuery and used addEventListener
and removeEventListener
to add and remove the handler instead. The browser executes the handler after the first click, unbinding and rebinding the handler, and then handles the second click and checks whether there's a click handler to execute.
To get around this, you need to defer rebinding of the handler using setTimeout
, so that clicks that happen while the first handler is executing will be processed before you reattach the handler.
<button id="foo">Click Me!</div>
<script>
function waitForFiveSeconds() {
var startTime = new Date();
while (new Date() - startTime < 5000) {}
}
$('#foo').click(function handler() {
$('#foo').off('click');
console.log('Hello, World!');
waitForFiveSeconds();
// Defer rebinding the handler, so that any clicks that happened while
// it was unbound get processed first.
setTimeout(function () {
$('#foo').click(handler);
}, 0);
});
</script>
You can see this in action at this modified JSFiddle.
Naturally, this is unnecessary if what you're doing in your handler is already asynchronous, since then you're already yielding control to the browser and letting it flush all the click events before you rebind your handler. For instance, code like this will work fine without a setTimeout
call:
<button id="foo">Save Stuff</div>
<script>
$('#foo').click(function handler() {
$('#foo').off('click');
$.post( "/some_api/save_stuff", function() {
$('#foo').click(handler);
});
});
</script>
click appears to be blocking? - here's another way to wait if you're using WebDriverJS:
driver.findElement(webdriver.By.name('mybutton')).click().then(function(){
driver.getPageSource().then(function(source) {
console.log(source);
});
});
The code above waits after the button is clicked for the next page to load and then grabs the source of the next page.
For me is working this way, using port and security (I had issues to send emails from gmail using PHP without security settings)
I hope will help someone.
var sendEmail = function(somedata){
var smtpConfig = {
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL,
// you can try with TLS, but port is then 587
auth: {
user: '***@gmail.com', // Your email id
pass: '****' // Your password
}
};
var transporter = nodemailer.createTransport(smtpConfig);
// replace hardcoded options with data passed (somedata)
var mailOptions = {
from: '[email protected]', // sender address
to: '[email protected]', // list of receivers
subject: 'Test email', // Subject line
text: 'this is some text', //, // plaintext body
html: '<b>Hello world ?</b>' // You can choose to send an HTML body instead
}
transporter.sendMail(mailOptions, function(error, info){
if(error){
return false;
}else{
console.log('Message sent: ' + info.response);
return true;
};
});
}
exports.contact = function(req, res){
// call sendEmail function and do something with it
sendEmail(somedata);
}
all the config are listed here (including examples)
#include <iostream>
class bar
{
public:
bar()
{
std::cout << "bar() called" << std::endl;
}
~bar()
{
std::cout << "~bar() called" << std::endl;
}
};
class foo
{
public:
foo()
: b(new bar())
{
std::cout << "foo() called" << std::endl;
throw "throw something";
}
~foo()
{
delete b;
std::cout << "~foo() called" << std::endl;
}
private:
bar *b;
};
int main(void)
{
try {
std::cout << "heap: new foo" << std::endl;
foo *f = new foo();
} catch (const char *e) {
std::cout << "heap exception: " << e << std::endl;
}
try {
std::cout << "stack: foo" << std::endl;
foo f;
} catch (const char *e) {
std::cout << "stack exception: " << e << std::endl;
}
return 0;
}
the output:
heap: new foo
bar() called
foo() called
heap exception: throw something
stack: foo
bar() called
foo() called
stack exception: throw something
the destructors are not called, so if a exception need to be thrown in a constructor, a lot of stuff(e.g. clean up?) to do.
A different approach that I found ugly compared to the classic dict+append, but that works:
df = df.T
df[0] = ['1/1/2013', 'Smith','test',123]
df = df.T
df
Out[6]:
Date Name Action ID
0 1/1/2013 Smith test 123
grep
find the lines and output the line numbers, but does not let you "program" other things. If you want to include arbitrary text and do other "programming", you can use awk,
$ awk '/null/{c++;print $0," - Line number: "NR}END{print "Total null count: "c}' file
example two null, - Line number: 2
example four null, - Line number: 4
Total null count: 2
Or only using the shell(bash/ksh)
c=0
while read -r line
do
case "$line" in
*null* ) (
((c++))
echo "$line - Line number $c"
;;
esac
done < "file"
echo "total count: $c"
You won't see a simple answer because there isn't one.
First, Unicode doesn't contain "every character from every language", although it sure does try.
Unicode itself is a mapping, it defines codepoints and a codepoint is a number, associated with usually a character. I say usually because there are concepts like combining characters. You may be familiar with things like accents, or umlauts. Those can be used with another character, such as an a
or a u
to create a new logical character. A character therefore can consist of 1 or more codepoints.
To be useful in computing systems we need to choose a representation for this information. Those are the various unicode encodings, such as utf-8, utf-16le, utf-32 etc. They are distinguished largely by the size of of their codeunits. UTF-32 is the simplest encoding, it has a codeunit that is 32bits, which means an individual codepoint fits comfortably into a codeunit. The other encodings will have situations where a codepoint will need multiple codeunits, or that particular codepoint can't be represented in the encoding at all (this is a problem for instance with UCS-2).
Because of the flexibility of combining characters, even within a given encoding the number of bytes per character can vary depending on the character and the normalization form. This is a protocol for dealing with characters which have more than one representation (you can say "an 'a' with an accent"
which is 2 codepoints, one of which is a combining char or "accented 'a'"
which is one codepoint).
If you do not have the ability to modify your php.ini file, use cURL: PHP Curl And Cookies
Here is an example function I created:
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => true, // Validate SSL Cert
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
return $header;
}
NOTE: In revisiting this function I noticed that I had disabled SSL checks in this code. That is generally a BAD thing even though in my particular case the site I was using it on was local and was safe. As a result I've modified this code to have SSL checks on by default. If for some reason you need to change that, you can simply update the value for CURLOPT_SSL_VERIFYPEER, but I wanted the code to be secure by default if someone uses this.
You can easily get what you want by adding the line in ax:
ax.plot([], [], '-r', label = 'temp')
or
ax.plot(np.nan, '-r', label = 'temp')
This would plot nothing but add a label to legend of ax.
I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.
The whole code is as below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()
#---------- look at below -----------
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2.plot(time, temp, '-r') # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp') # Make an agent in ax
ax.legend(loc=0)
#---------------done-----------------
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
The plot is as below:
Update: add a better version:
ax.plot(np.nan, '-r', label = 'temp')
This will do nothing while plot(0, 0)
may change the axis range.
One extra example for scatter
ax.scatter([], [], s=100, label = 'temp') # Make an agent in ax
ax2.scatter(time, temp, s=10) # The true scatter in ax2
ax.legend(loc=1, framealpha=1)
Open the file again using vi. and then press " i " or press insert key ,
For save and quit
Enter Esc
and write the following command
:wq
without save and quit
:q!
<LinearLayout
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="9"
android:orientation="horizontal" >
<ImageView
android:id="@+id/ring_oss"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/ring_oss" />
<ImageView
android:id="@+id/maila_oss"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/maila_oss" />
<EditText
android:id="@+id/edittxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/maila_oss" />
</LinearLayout>
For apache-tomcat-8.5.28 version just do this,
catalina.bat jpda start
As the default settings already configured for us in catalina.bat as
if not "%JPDA_OPTS%" == "" goto gotJpdaOpts set JPDA_OPTS=-agentlib:jdwp=transport=%JPDA_TRANSPORT%,address=%JPDA_ADDRESS%,server=y,suspend=%JPDA_SUSPEND%
So no need of any other config. And when you execute command catalina.bat jpda start, you can see debug port 8000 is opened.
Try looking at CASSIS. The idea is to mix PHP with JS so both can work on client and server side.
The answers to this question, while they are correct, are very unnecessarily complicated. It doesn't take that much code for text to show up in the header/footer. Here is a simple example of adding text to the header/footer.
The current version of iTextSharp works by implementing a callback class which is defined by the IPdfPageEvent
interface. From what I understand, it's not a good idea to add things during the OnStartPage
method, so instead I will be using the OnEndPage
page method. The events are triggered depending on what is happening to the PdfWriter
First, create a class which implements IPdfPageEvent
. In the:
public void OnEndPage(PdfWriter writer, Document document)
function, obtain the PdfContentByte
object by calling
PdfContentByte cb = writer.DirectContent;
Now you can add text very easily:
ColumnText ct = new ColumnText(cb);
cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
//Note, (0,0) in this case is at the bottom of the document
cb.SetTextMatrix(document.LeftMargin, document.BottomMargin);
cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
cb.EndText();
So the full for the OnEndPage
function will be:
public void OnEndPage(PdfWriter writer, Document document)
{
PdfContentByte cb = writer.DirectContent;
ColumnText ct = new ColumnText(cb);
cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
cb.SetTextMatrix(document.LeftMargin, document.BottomMargin);
cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
cb.EndText();
}
This will show up at the bottom of your document. One last thing. Don't forget to assign the IPdfPageEvent
like this:
writter.PageEvent = new PDFEvents();
To the PdfWriter
writter object
For the header it is very similar. Just flip the SetTextMatrix
y coordinate:
cb.SetTextMatrix(document.LeftMargin, document.PageSize.Height - document.TopMargin);
New Date(number) returns a date that's number
milliseconds after 1 Jan 1970. Odds are you date format isn't showing hours, minutes, and seconds for you to see that it's just a little bit after 1 Jan 1970.
You need to parse the date according to the correct parsing routing. I don't know what a 1220227200 is, but if it's seconds after 1 JAN 1970, then multiply it to yield milliseconds. If it is not, then convert it in some manner to milliseconds after 1970 (if you want to continue to use java.util.Date).
In my case I am using jQuery .load()
to update DIVs in a SPA (single page [web] app) .
Being new to working with $(window).on('hashchange', ..)
event listener , this one proved challenging and took a bit to hack on. Thanks to reading a lot of answers and trying different variations, finally figured out how to make it work in the following manner. Far as I can tell, it is looking stable so far.
In summary - there is the variable
globalCurrentHash
that should be set each time you load a view.Then when
$(window).on('hashchange', ..)
event listener runs, it checks the following:
- If
location.hash
has the same value, it means Going Forward- If
location.hash
has different value, it means Going Back
I realize using global vars isn't the most elegant solution, but doing things OO in JS seems tricky to me so far. Suggestions for improvement/refinement certainly appreciated
Set Up:
var globalCurrentHash = null;
When calling .load()
to update the DIV, update the global var as well :
function loadMenuSelection(hrefVal) {
$('#layout_main').load(nextView);
globalCurrentHash = hrefVal;
}
On page ready, set up the listener to check the global var to see if Back Button is being pressed:
$(document).ready(function(){
$(window).on('hashchange', function(){
console.log( 'location.hash: ' + location.hash );
console.log( 'globalCurrentHash: ' + globalCurrentHash );
if (location.hash == globalCurrentHash) {
console.log( 'Going fwd' );
}
else {
console.log( 'Going Back' );
loadMenuSelection(location.hash);
}
});
});