Use CSS cursor: pointer
if I remember correctly.
Either in your CSS file:
.link_cursor
{
cursor: pointer;
}
Then just add the following HTML to any elements you want to have the link cursor: class="link_cursor"
(the preferred method.)
Or use inline CSS:
<a style="cursor: pointer;">
Don't ever use the setInterval
or setTimeout
functions for time measuring! They are unreliable, and it is very likely that the JS execution scheduling during a documents parsing and displaying is delayed.
Instead, use the Date
object to create a timestamp when you page began loading, and calculate the difference to the time when the page has been fully loaded:
<doctype html>
<html>
<head>
<script type="text/javascript">
var timerStart = Date.now();
</script>
<!-- do all the stuff you need to do -->
</head>
<body>
<!-- put everything you need in here -->
<script type="text/javascript">
$(document).ready(function() {
console.log("Time until DOMready: ", Date.now()-timerStart);
});
$(window).load(function() {
console.log("Time until everything loaded: ", Date.now()-timerStart);
});
</script>
</body>
</html>
I found this way not sure it works for all the CSS primitives
By setting the header property "Content-Type" to "text/html"
mimeMessage.setHeader("Content-Type", "text/html");
now I can do stuff like
mimeMessage.setHeader("Content-Type", "text/html");
mimeMessage.setText ("`<html><body><h1 style =\"color:blue;\">My first Header<h1></body></html>`")
Regards
One working example for me.
Controller:
public function tableView()
{
$sites = Site::all();
return view('main.table', compact('sites'));
}
View:
<script>
var sites = {!! json_encode($sites->toArray()) !!};
</script>
To prevent malicious / unintended behaviour, you can use JSON_HEX_TAG
as suggested by Jon in the comment that links to this SO answer
<script>
var sites = {!! json_encode($sites->toArray(), JSON_HEX_TAG) !!};
</script>
I just figured it out below:
$(".notice")
.fadeIn( function()
{
setTimeout( function()
{
$(".notice").fadeOut("fast");
}, 2000);
});
I will keep the post for other users!
After 48 hours of the still not being updated I removed the app from sale on Pricing and Availability.
Then I waited 1 hour.
Then I ticked All Territories Selected again.
After the app came available for download again the version number was updated.
As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.
I am facing problems with composer because it consumes all the available memory, and then, the process get killed ( actualy, the output message is "Killed")
So, I was looking for a solution to limit composer memory usage.
I tried ( from @Sven answers )
$ php -d memory_limit=512M /usr/local/bin/composer update
But it didn't work because
"Composer internally increases the memory_limit to 1.5G."
-> Thats from composer oficial website.
Then I found a command that works :
$ COMPOSER_MEMORY_LIMIT=512M php composer.phar update
Althought, in my case 512mb is not enough !
Source : https://www.agileana.com/blog/composer-memory-limit-troubleshooting/
actually , this has turned out to be couple of javascript changes in the code. calling of javascript method with ; at the end. placing script tags in body instead of head. and interestingly even change the text displayed (please "click") to something that is not an event. so Please rate etc.
turned debugger on safari, it didnot give much information or even errors at times.
Classes have an implicit strong reference to their ClassLoader instance, and vice versa. They are garbage collected as with Java objects. Without hitting the tools interface or similar, you can't remove individual classes.
As ever you can get memory leaks. Any strong reference to one of your classes or class loader will leak the whole thing. This occurs with the Sun implementations of ThreadLocal, java.sql.DriverManager and java.beans, for instance.
I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.
import matplotlib.pyplot as plt
from matplotlib import cm
from numpy import linspace
start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines)
colors = [ cm.jet(x) for x in cm_subsection ]
for i, color in enumerate(colors):
plt.axhline(i, color=color)
plt.ylabel('Line Number')
plt.show()
This results in 1000 uniquely-colored lines that span the entire cm.jet colormap as pictured below. If you run this script you'll find that you can zoom in on the individual lines.
Now say I want my 1000 line colors to just span the greenish portion between lines 400 to 600. I simply change my start and stop values to 0.4 and 0.6 and this results in using only 20% of the cm.jet color map between 0.4 and 0.6.
So in a one line summary you can create a list of rgba colors from a matplotlib.cm colormap accordingly:
colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]
In this case I use the commonly invoked map named jet but you can find the complete list of colormaps available in your matplotlib version by invoking:
>>> from matplotlib import cm
>>> dir(cm)
When you store something in an array , its size needs to be known (since array indexing relies on the size). Per the C++ standard It is unspecified whether or not a reference requires storage, as a result indexing an array of references would not be possible.
You need to combine multiple classes (col-*-offset-*
for left-margin and col-*-pull-*
to pull it right)
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-xs-3 col-xs-offset-9">_x000D_
I'm a right column_x000D_
</div>_x000D_
<div class="col-xs-3">_x000D_
We're_x000D_
</div>_x000D_
<div class="col-xs-3">_x000D_
four columns_x000D_
</div>_x000D_
<div class="col-xs-3">_x000D_
using the_x000D_
</div>_x000D_
<div class="col-xs-3">_x000D_
whole row_x000D_
</div>_x000D_
<div class="col-xs-3 col-xs-offset-9 col-xs-pull-9">_x000D_
I'm a left column_x000D_
</div>_x000D_
<div class="col-xs-3">_x000D_
We're_x000D_
</div>_x000D_
<div class="col-xs-3">_x000D_
four columns_x000D_
</div>_x000D_
<div class="col-xs-3">_x000D_
using the_x000D_
</div>_x000D_
<div class="col-xs-3">_x000D_
whole row_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
So you don't need to separate it manually into different rows.
If you are talking about changing the working directory for a java program that you launch from within eclipse, then there's a space for that in the run configuration. If you go to Run menu and select "Run Configurations..." then select your run configuration, then on the "Arguments" tab for a Java Application there is a place for you to edit the "Working directory". This alters the current directory that will be used for launching the java program.
See related question Default eclipse working directory if this is what you are meaning.
Add http:// in front of url
Incorrect
<a href="www.example.com">www.example.com</span></p>
Correct
<a href="http://www.example.com">www.example.com</span></p>
native mapkit is supported in Titanium
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
jQuery is just a set of helpers/libraries written in Javascript. You can still use all Javascript features, so you can call whatever functions, also from inside jQuery callbacks. So both possibilities should be okay.
You can create an unsigned char:
unsigned char c = 0xc5;
Printing it will give C5
and not ffffffc5
.
Only the chars bigger than 127 are printed with the ffffff
because they are negative (char is signed).
Or you can cast the char
while printing:
char c = 0xc5;
printf("%x", (unsigned char)c);
<style>_x000D_
.hideFullColumn tr > .hidecol_x000D_
{_x000D_
display:none;_x000D_
}_x000D_
</style>
_x000D_
use .hideFullColumn in table and .hidecol in th.You don't need to add class in td individually as it will be problem because index may not be in mind of each td.
Sure you know, but if its a constant then const MyVariable as Integer = 123
otherwise your out of luck; the variable must be assigned an initial value elsewhere.
You could:
public property get myIntegerThing() as integer
myIntegerThing= 123
end property
In a Class module then globally create it;
public cMyStuff as new MyStuffClass
So cMyStuff.myIntegerThing
is available immediately.
I'am trying to install SQL SERVER developer 2008 R2 alongside SQL SERVER 2005 EXPRESS,
i went to program features, clicked on unistall SQL SERVER 2005 EXPRESS, and only checked, WORKSTATION COMPONENTS, it unistalled: support files, sql mngmt studio
After that installation of sql 2008 r2 developer went ok....
Hopes this helps somebody
If your string will always be of that format, a regex is overkill:
>>> var g='{getThis}';
>>> g.substring(1,g.length-1)
"getThis"
substring(1
means to start one character in (just past the first {
) and ,g.length-1)
means to take characters until (but not including) the character at the string length minus one. This works because the position is zero-based, i.e. g.length-1
is the last position.
For readers other than the original poster: If it has to be a regex, use /{([^}]*)}/
if you want to allow empty strings, or /{([^}]+)}/
if you want to only match when there is at least one character between the curly braces. Breakdown:
/
: start the regex pattern
{
: a literal curly brace
(
: start capturing
[
: start defining a class of characters to capture
^}
: "anything other than }
"]
: OK, that's our whole class definition*
: any number of characters matching that class we just defined)
: done capturing}
: a literal curly brace must immediately follow what we captured/
: end the regex pattern@Component({
selector: 'my-app',
template: `
<div>
<input type="text" placeholder="Search..." [(ngModel)]="searchValue">
<button (click)="clearSearch()">Clear</button>
</div>
`,
})
export class App {
searchValue:string = '';
clearSearch() {
this.searchValue = null;
}
}
Plunker code: Plunker1
@Component({
selector: 'my-app',
template: `
<div>
<input type="text" placeholder="Search..." [value]="searchValue">
<button (click)="clearSearch()">Clear</button>
</div>
`,
})
export class App {
searchValue:string = '';
clearSearch() {
this.searchValue = null;
}
}
Plunker code: Plunker2
You need to install the php-pgsql package or whatever it's called for your platform. Which I don't think you said by the way.
On Ubuntu and Debian:
sudo apt-get install php5-pgsql
Project Properties -> Compiler Tab -> Advanced Compile Options button
Project Properties -> Application Tab
You should post a message from frame to parent, after loaded.
frame script:
$(document).ready(function() {
window.parent.postMessage("I'm loaded", "*");
});
And listen it in parent:
function listenMessage(msg) {
alert(msg);
}
if (window.addEventListener) {
window.addEventListener("message", listenMessage, false);
} else {
window.attachEvent("onmessage", listenMessage);
}
Use this link for more info: http://en.wikipedia.org/wiki/Web_Messaging
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
For Swift, just use closures: example.
In Objective-C:
@property (copy)void (^doStuff)(void);
It's that simple.
In your .h file:
// Here is a block as a property:
//
// Someone passes you a block. You "hold on to it",
// while you do other stuff. Later, you use the block.
//
// The property 'doStuff' will hold the incoming block.
@property (copy)void (^doStuff)(void);
// Here's a method in your class.
// When someone CALLS this method, they PASS IN a block of code,
// which they want to be performed after the method is finished.
-(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater;
// We will hold on to that block of code in "doStuff".
Here's your .m file:
-(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater
{
// Regarding the incoming block of code, save it for later:
self.doStuff = pleaseDoMeLater;
// Now do other processing, which could follow various paths,
// involve delays, and so on. Then after everything:
[self _alldone];
}
-(void)_alldone
{
NSLog(@"Processing finished, running the completion block.");
// Here's how to run the block:
if ( self.doStuff != nil )
self.doStuff();
}
With modern (2014+) systems, do what is shown here. It is that simple.
<graphics.h>
is very old library. It's better to use something that is new
Here are some 2D libraries (platform independent) for C/C++
Also there is a free very powerful 3D open source graphics library for C++
Similar answers:
Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview
app.directive("myDir", function($compile) {
return {
priority:1001, // compiles first
terminal:true, // prevent lower priority directives to compile after it
compile: function(el) {
el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
el.attr('ng-click', 'fxn()');
var fn = $compile(el);
return function(scope){
fn(scope);
};
}
};
});
ngClick
at all:A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview
app.directive("myDir", function($parse) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('fxn()');
return function (scope,elm){
elm.bind('click',function(){
exp(scope);
});
};
}
};
});
If you haven't install mysql_client
yet and using Docker
container instead:
sudo docker exec MySQL_CONTAINER_NAME /usr/bin/mysqldump --host=192.168.1.1 -u username --password=password db_name > dump.sql
If you have a seeder in your database, run php artisan migrate:fresh --seed
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});
}
the default encoding of a HTTP POST is ISO-8859-1.
else you have to look at the Content-Type header that will then look like
Content-Type: application/x-www-form-urlencoded ; charset=UTF-8
You can maybe declare your form with
<form enctype="application/x-www-form-urlencoded;charset=UTF-8">
or
<form accept-charset="UTF-8">
to force the encoding.
Some references :
None of the other answers dealt with the case of using .children()
or .find(">")
to only search for immediate children of a parent element. So, I created a jsPerf test to find out, using three different ways to distinguish children.
As it happens, even when using the extra ">" selector, .find()
is still a lot faster than .children()
; on my system, 10x so.
So, from my perspective, there does not appear to be much reason to use the filtering mechanism of .children()
at all.
These are the droids you're looking for. This is taken from validator.js which is the library you should really use to do this. But if you want to roll your own, who am I to stop you? If you want pure regex then you can just take out the length check. I think it's a good idea to test the length of the URL though if you really want to determine compliance with the spec.
function isURL(str) {
var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
var url = new RegExp(urlRegex, 'i');
return str.length < 2083 && url.test(str);
}
If you are using CentOS, then you need to use
yum install python34-devel.x86_64
yum groupinstall -y 'development tools'
pip3 install mysql-connector
pip install mysqlclient
simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
Sometimes the Sql Server service has not been started. This may generate the error. Go to Services and start Sql Server. This should make it work.
When you call the function in a static context, $this
simply doesn't exist.
You would have to use this::xyz()
instead.
To find out what context you're in when a function can be called both statically and in an object instance, a good approach is outlined in this question: How to tell whether I’m static or an object?
I had the same problem and the solutions described here worked well. But I wanted to support window size (and layout) changes. The result is a small library that solves all the calculation. Check it out here: https://github.com/SocialbitGmbH/BootstrapCarouselPageMerger
To make the script work, you have to add a new <div>
wrapper with the class .item-content
directly into your .item
<div>
. Example:
<div class="carousel slide multiple" id="very-cool-carousel" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="item active">
<div class="item-content">
First page
</div>
</div>
<div class="item active">
<div class="item-content">
Second page
</div>
</div>
</div>
</div>
Usage of this library:
socialbitBootstrapCarouselPageMerger.run('div.carousel');
To change the settings:
socialbitBootstrapCarouselPageMerger.settings.spaceCalculationFactor = 0.82;
Example:
As you can see, the carousel gets updated to show more controls when you resize the window. Check out the watchWindowSizeTimeout
setting to control the timeout for reacting to window size changes.
If you want to write a loop in Python which prints some integer no etc, then just copy and paste this code, it'll work a lot
# Display Value from 1 TO 3
for i in range(1,4):
print "",i,"value of loop"
# Loop for dictionary data type
mydata = {"Fahim":"Pakistan", "Vedon":"China", "Bill":"USA" }
for user, country in mydata.iteritems():
print user, "belongs to " ,country
One option would be to read the data from the registry. MSDN Article On The Topic: http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.localmachine(v=vs.71).aspx)
The processors, I believe can be located here, HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor
private void determineNumberOfProcessCores()
{
RegistryKey rk = Registry.LocalMachine;
String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DESCRIPTION").OpenSubKey("System").OpenSubKey("CentralProcessor").GetSubKeyNames();
textBox1.Text = "Total number of cores:" + subKeys.Length.ToString();
}
I am reasonably sure the registry entry will be there on most systems.
Though I would throw my $0.02 in.
You could achieve this with a simple for
loop:
var min = 12,
max = 100,
select = document.getElementById('selectElementId');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
JS Perf comparison of both mine and Sime Vidas' answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.
Edited in response to comment from OP:
[How] do [I] apply this to more than one element?
function populateSelect(target, min, max){
if (!target){
return false;
}
else {
var min = min || 0,
max = max || min + 100;
select = document.getElementById(target);
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
}
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);
// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');
// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);
And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement
in order to chain the populate()
function, as a method, to the DOM node:
HTMLSelectElement.prototype.populate = function (opts) {
var settings = {};
settings.min = 0;
settings.max = settings.min + 100;
for (var userOpt in opts) {
if (opts.hasOwnProperty(userOpt)) {
settings[userOpt] = opts[userOpt];
}
}
for (var i = settings.min; i <= settings.max; i++) {
this.appendChild(new Option(i, i));
}
};
document.getElementById('selectElementId').populate({
'min': 12,
'max': 40
});
References:
char = split_string_to_char(text)(index)
------
Function split_string_to_char(text) As String()
Dim chars() As String
For char_count = 1 To Len(text)
ReDim Preserve chars(char_count - 1)
chars(char_count - 1) = Mid(text, char_count, 1)
Next
split_string_to_char = chars
End Function
The other answers are generally correct. I should like to contribute the modern answer. The classes Date
, DateFormat
and SimpleDateFormat
used in most of the other answers, are long outdated and have caused trouble for many programmers over many years. Today we have so much better in java.time
, AKA JSR-310, the modern Java date & time API. Can you use this on Android yet? Most certainly! The modern classes have been backported to Android in the ThreeTenABP project. See this question: How to use ThreeTenABP in Android Project for all the details.
This snippet should get you started:
int year = 2017, month = 9, day = 28, hour = 22, minute = 45;
LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(dateTime.format(formatter));
When I set my computer’s preferred language to US English or UK English, this prints:
Sep 28, 2017 10:45:00 PM
When instead I set it to Danish, I get:
28-09-2017 22:45:00
So it does follow the configuration. I am unsure exactly to what detail it follows your device’s date and time settings, though, and this may vary from phone to phone.
The problem was with the QuickText plugin. After removing it, indent worked as normal.
You can use Java's StringBuilder
type for this. There's also StringBuffer
, but it contains extra thread safety logic that is often unnecessary.
DavidLn's answer has worked well for me in the past. But it doesn't capture all of setPristine's functionality, which tripped me up this time. Here is a fuller shim:
var form_set_pristine = function(form){
// 2013-12-20 DF TODO: remove this function on Angular 1.1.x+ upgrade
// function is included natively
if(form.$setPristine){
form.$setPristine();
} else {
form.$pristine = true;
form.$dirty = false;
angular.forEach(form, function (input, key) {
if (input.$pristine)
input.$pristine = true;
if (input.$dirty) {
input.$dirty = false;
}
});
}
};
In the launcher script you can force it, it permits to keep the same script and same launcher for both architecture
:: For 32 bits architecture, this line is sufficent (32bits is the only cscript available)
set CSCRIPT="cscript.exe"
:: Detect windows 64bits and use the expected cscript (SysWOW64 contains 32bits executable)
if exist "C:\Windows\SysWOW64\cscript.exe" set CSCRIPT="C:\Windows\SysWOW64\cscript.exe"
%CSCRIPT% yourscript.vbs
BTW, HTTP 1/1 specification (RFC2616) suggests no more than 2 connections per server.
Clients that use persistent connections SHOULD limit the number of simultaneous connections that they maintain to a given server. A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy. A proxy SHOULD use up to 2*N connections to another server or proxy, where N is the number of simultaneously active users. These guidelines are intended to improve HTTP response times and avoid congestion.
I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).
URL for accessing my app:
http://myapp.com/amazing_url?token=super_token
Then when the user loads the page:
http://myapp.com/amazing_url?token=super_token#/amazing_url
Then when the user navigates:
http://myapp.com/amazing_url?token=super_token#/another_url
With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.
So don't enable the HTML5 mode and then add this controller:
.config ($stateProvider)->
$stateProvider.state('home-loading', {
url: '/',
controller: 'homeController'
})
.controller 'homeController', ($state, $location)->
if window.location.pathname != '/'
$location.url(window.location.pathname+window.location.search).replace()
else
$state.go('home', {}, { location: 'replace' })
I wrote an easy wrapper that allows you to register styles and scrips in every partial view dynamically into the head tag.
It is based on the DynamicHeader jsakamoto put up, but it has some performance improvements & tweaks.
It is very easy to use, and versatile.
The usage:
@{
DynamicHeader.AddStyleSheet("/Content/Css/footer.css", ResourceType.Layout);
DynamicHeader.AddStyleSheet("/Content/Css/controls.css", ResourceType.Infrastructure);
DynamicHeader.AddScript("/Content/Js/Controls.js", ResourceType.Infrastructure);
DynamicHeader.AddStyleSheet("/Content/Css/homepage.css");
}
You can find the full code, explanations and examples inside: Add Styles & Scripts Dynamically to Head Tag
kennytm's links are dead and he doesn't provide an example so here's how you do substrings:
=MID(text, start_num, char_num)
Let's say cell A1
is Hello
.
=MID(A1, 2, 3)
Would return
ell
Because it says to start at character 2, e
, and to return 3 characters.
Apart from the <h:panelGroup>
component (which comes as a bit of a surprise to me), you could use a <f:verbatim>
tag with the escape parameter set to false
to generate any mark-up you want. For example:
<f:verbatim escape="true">
<div id="blah"></div>
</f:verbatim>
Bear in mind it's a little less elegant than the panelGroup
solution, as you have to generate this for both the start and end tags if you want to wrap any of your JSF code with the div
tag.
Alternatively, all the major UI Frameworks have a div
component tag, or you could write your own.
Just run this verbatim.
import nltk
nltk.download('tagsets')
nltk.help.upenn_tagset()
nltk.tag._POS_TAGGER
won't work. It will give AttributeError: module 'nltk.tag' has no attribute '_POS_TAGGER'. It's not available in NLTK 3 anymore.
I want to add for one more possibility. If you don't want to use TypeToken and want to convert json objects array to an ArrayList, then you can proceed like this:
If your json structure is like:
{
"results": [
{
"a": 100,
"b": "value1",
"c": true
},
{
"a": 200,
"b": "value2",
"c": false
},
{
"a": 300,
"b": "value3",
"c": true
}
]
}
and your class structure is like:
public class ClassName implements Parcelable {
public ArrayList<InnerClassName> results = new ArrayList<InnerClassName>();
public static class InnerClassName {
int a;
String b;
boolean c;
}
}
then you can parse it like:
Gson gson = new Gson();
final ClassName className = gson.fromJson(data, ClassName.class);
int currentTotal = className.results.size();
Now you can access each element of className object.
With debug turned off Django won't handle static files for you any more - your production web server (Apache or something) should take care of that.
Try this
SELECT t1.*
FROM
some_table t1,
(SELECT relevant_field
FROM some_table
GROUP BY relevant_field
HAVING COUNT (*) > 1) t2
WHERE
t1.relevant_field = t2.relevant_field;
You cannot have spaces around the =
sign.
When you write:
STR = "foo"
bash tries to run a command named STR
with 2 arguments (the strings =
and foo
)
When you write:
STR =foo
bash tries to run a command named STR
with 1 argument (the string =foo
)
When you write:
STR= foo
bash tries to run the command foo
with STR set to the empty string in its environment.
I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:
STR "=" "foo"
,STR "=foo"
,STR="" foo
.The relevant section of the sh language spec, section 2.9.1 states:
A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.
In that context, a word
is the command that bash is going to run. Any string containing =
(in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the =
is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo"
, STR
is not a variable assignment.
try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.
or else you may use state based programming where an event occurs at a particular state of the browser..
Nice solution by leocaseiro
<input class="ng-hide" id="input-file-id" multiple type="file" />
<label for="input-file-id" class="md-button md-raised md-primary">Choose Files</label>
View in codepen
I'm not aware of a tool that does this well but I've seen a variety of homegrown solutions. The common thread of these is to minimise the binary data under version control and maximise textual data to leverage the power of conventional scc systems. To do this:
If you prefer to use style='{'
, fmt="{asctime}.{msecs:0<3.0f}"
will 0-pad your microseconds to three places for consistency.
var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
Thay are removed.
Use float-left
instead of pull-left
.
And float-right
instead of pull-right
.
Check bootstrap Documentation here:
Added .float-{sm,md,lg,xl}-{left,right,none} classes for responsive floats and removed .pull-left and .pull-right since they’re redundant to .float-left and .float-right.
Cursors may also be used, although it is inefficient. The following stackoverflow post discusses the usage of cursors :
Let tell you a simple formula to find xpath of any element:
1- Open site in browser
2- Select element and right click on it
3- Click inspect element option
4- Right click on selected html
5- choose option to copy xpath Use it where ever you need it
This video link will be helpful for you. http://screencast.com/t/afXsaQXru
Note: For advance options of xpath you must know regex or pattern of your html.
On the comments:
sscanf(Abcd, "%f %s", &f,&s);
Gives an Error.
This is the right way:
sscanf(Abcd, "%f %s", &f,qPrintable(s));
I wanted to add more details about how the @Valid
works, especially in spring.
Everything you'd want to know about validation in spring is explained clearly and in detail in https://reflectoring.io/bean-validation-with-spring-boot/, but I'll copy the answer to how @Valid
works incase the link goes down.
The @Valid
annotation can be added to variables in a rest controller method to validate them. There are 3 types of variables that can be validated:
So now... how does spring "validate"? You can define constraints to the fields of a class by annotating them with certain annotations. Then, you pass an object of that class into a Validator which checks if the constraints are satisfied.
For example, suppose I had controller method like this:
@RestController
class ValidateRequestBodyController {
@PostMapping("/validateBody")
ResponseEntity<String> validateBody(@Valid @RequestBody Input input) {
return ResponseEntity.ok("valid");
}
}
So this is a POST request which takes in a response body, and we're mapping that response body to a class Input
.
Here's the class Input
:
class Input {
@Min(1)
@Max(10)
private int numberBetweenOneAndTen;
@Pattern(regexp = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$")
private String ipAddress;
// ...
}
The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen
is between 1 and 10 inclusive because of those min and max annotations. It'll also check to make sure the ip address passed in matches the regular expression in the annotation.
side note: the regular expression isn't perfect.. you could pass in 3 digit numbers that are greater than 255 and it would still match the regular expression.
Here's an example of validating a query variable and path variable:
@RestController
@Validated
class ValidateParametersController {
@GetMapping("/validatePathVariable/{id}")
ResponseEntity<String> validatePathVariable(
@PathVariable("id") @Min(5) int id) {
return ResponseEntity.ok("valid");
}
@GetMapping("/validateRequestParameter")
ResponseEntity<String> validateRequestParameter(
@RequestParam("param") @Min(5) int param) {
return ResponseEntity.ok("valid");
}
}
In this case, since the query variable and path variable are just integers instead of just complex classes, we put the constraint annotation @Min(5)
right on the parameter instead of using @Valid
.
Try adding this in your vhost config:
RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
I think you can achieve it by using the below code
Model::get(['ColumnName'])->toArray();
Some time we have more spaces in between quotes, then use this approach
a = " "
>>> bool(a)
True
>>> bool(a.strip())
False
if not a.strip():
print("String is empty")
else:
print("String is not empty")
Here is the most elegant form I could come up without using sun.*:
import java.io.*;
import javax.sound.sampled.*;
try {
File yourFile;
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
Clip clip;
stream = AudioSystem.getAudioInputStream(yourFile);
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
}
catch (Exception e) {
//whatevers
}
System.setProperty("https.protocols", "TLSv1.2");
worked in my case. Have you checked that within the application?
You can make it wait using $RANDOM, a default random number generator. In the below I am using 240 seconds. Hope that helps @
> WAIT_FOR_SECONDS=`/usr/bin/expr $RANDOM % 240` /bin/sleep
> $WAIT_FOR_SECONDS
You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)
select sone_field collate SQL_Latin1_General_CP850_CI_AI
from table_1
inner join table_2
on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
where whatever
app.use()
is intended for binding middleware to your application. The path
is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:
// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();
app.use('/subapp', require('./subapp'));
// ...
By specifying /
as a "mount" path, app.use()
will respond to any path that starts with /
, which are all of them and regardless of HTTP verb used:
GET /
PUT /foo
POST /foo/bar
app.get()
, on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET
HTTP verb:
GET /
And, the equivalent routing for your example of app.use()
would actually be:
app.all(/^\/.*/, function (req, res) {
res.send('Hello');
});
(Update: Attempting to better demonstrate the differences.)
The routing methods, including app.get()
, are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route')
.
Within each app.get()
is a call to app.use()
, so you can certainly do all of this with app.use()
directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.
Examples:
For simple, static routes:
app.get('/', function (req, res) {
// ...
});
vs.
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
// ...
});
With multiple handlers for the same route:
app.get('/', authorize('ADMIN'), function (req, res) {
// ...
});
vs.
const authorizeAdmin = authorize('ADMIN');
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
authorizeAdmin(req, res, function (err) {
if (err) return next(err);
// ...
});
});
With parameters:
app.get('/item/:id', function (req, res) {
let id = req.params.id;
// ...
});
vs.
const pathToRegExp = require('path-to-regexp');
function prepareParams(matches, pathKeys, previousParams) {
var params = previousParams || {};
// TODO: support repeating keys...
matches.slice(1).forEach(function (segment, index) {
let { name } = pathKeys[index];
params[name] = segment;
});
return params;
}
const itemIdKeys = [];
const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
app.use('/', function (req, res, next) {
if (req.method !== 'GET') return next();
var urlMatch = itemIdPattern.exec(req.url);
if (!urlMatch) return next();
if (itemIdKeys && itemIdKeys.length)
req.params = prepareParams(urlMatch, itemIdKeys, req.params);
let id = req.params.id;
// ...
});
Note: Express' implementation of these features are contained in its
Router
,Layer
, andRoute
.
With Named arguments:
@Html.ActionLink(linkText: "TestTab", actionName: "TestAction", controllerName: "TestController", routeValues: null, htmlAttributes: new { target = "_blank"})
I was facing the same issue, and it drove me up the wall. The issue ended up to be that the .idea folder was ALREADY commited into the repo previously, and so they were being tracked by git regardless of whether you ignored them or not. I would recommend the following, after closing RubyMine/IntelliJ or whatever IDE you are using:
mv .idea ../.idea_backup
rm .idea # in case you forgot to close your IDE
git rm -r .idea
git commit -m "Remove .idea from repo"
mv ../.idea_backup .idea
After than make sure to ignore .idea in your .gitignore
Although it is sufficient to ignore it in the repository's .gitignore, I would suggest that you ignore your IDE's dotfiles globally.
Otherwise you will have to add it to every .gitgnore for every project you work on. Also, if you collaborate with other people, then its best practice not to pollute the project's .gitignore with private configuation that are not specific to the source-code of the project.
// define
var foo = {
bar: ['foo', 'bar', 'baz']
};
// access
foo.bar[2]; // will give you 'baz'
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )
You can/should set your parameter to value to DBNull.Value;
if (variable == "")
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}
Or you can leave your server side set to null and not pass the param at all.
Get items when the date is between fromdate and toDate.
where convert(date, fromdate, 103 ) <= '2016-07-26' and convert(date, toDate, 103) >= '2016-07-26'
You will need to have root access to do this. If you aren't already the administrative user, login as the administrator. Then use 'sudo' to change the permissions:
sudo chmod go-w /usr/local/bin
Obviously, that will mean you can no longer install material in /usr/local/bin except via 'sudo', but you probably shouldn't be doing that anyway.
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
I got to thinking about a better way. It dawned on me that #if blocks are effectively comments in other configurations (assuming DEBUG
or RELEASE
; but true with any symbol)
public class Mytest
{
public DateTime DateAndTimeOfTransaction;
}
public void ProcessCommand(Mytest Command)
{
CheckMyCommandPreconditions(Command);
// do more stuff with Command...
}
[Conditional("DEBUG")]
private static void CheckMyCommandPreconditions(Mytest Command)
{
if (Command.DateAndTimeOfTransaction > DateTime.Now)
throw new InvalidOperationException("DateTime expected to be in the past");
}
You can use .resize()
to get every time the width/height actually changes, like this:
$(window).resize(function() {
//resize just happened, pixels changed
});
You can view a working demo here, it takes the new height/width values and updates them in the page for you to see. Remember the event doesn't really start or end, it just "happens" when a resize occurs...there's nothing to say another one won't happen.
Edit: By comments it seems you want something like a "on-end" event, the solution you found does this, with a few exceptions (you can't distinguish between a mouse-up and a pause in a cross-browser way, the same for an end vs a pause). You can create that event though, to make it a bit cleaner, like this:
$(window).resize(function() {
if(this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function() {
$(this).trigger('resizeEnd');
}, 500);
});
You could have this is a base file somewhere, whatever you want to do...then you can bind to that new resizeEnd
event you're triggering, like this:
$(window).bind('resizeEnd', function() {
//do something, window hasn't changed size in 500ms
});
I'd like to add something that hasn't been pointed out. Java doesn't take into account the values you have given the variables (2 and 3) in...
short a = 2; short b = 3; short c = a + b;
So as far as Java knows, you could done this...
short a = 32767; short b = 32767; short c = a + b;
Which would be outside the range of short, it autoboxes the result to an int becuase it's "possible" that the result will be more than a short but not more than an int. Int was chosen as a "default" because basically most people wont be hard coding values above 2,147,483,647 or below -2,147,483,648
I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"
Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...
I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.
#!/usr/local/bin/python2.7
marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list
#here we populate the dictionary with the marks for every subject
for subject in subjects:
marks[subject] = input("Enter the " + subject + " marks: ")
#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)
print ("The total is " + str(total) + " and the average is " + str(average))
Here you can test the code and experiment with it.
Ternary is the most clear way of doing this.
<div>{{ConditionVar ? 'varIsTrue' : 'varIsFalse'}}</div>
I know that there are accepted answer but still, I want to share my scenario that maybe help someone to solve their problem TOOLS
SCENARIO
i was loading the dataset which's in CSV format which was later to be shown on the View
i tried to use the bulk load but I's unable to load as BULK LOAD
was using
FIELDTERMINATOR = ','
and Excel cell was also using ,
however, I also couldn't use Flat file source
directly because I was using Code-First Approach
and doing that only made model in SSMS DB, not in the model from which I had to use the properties later.
SOLUTION
Add-Migration
in NuGet package console There are also these 'ways':
>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}
You can use white-space: nowrap;
to define this behaviour:
// HTML:
.nowrap {_x000D_
white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
<span class="nowrap">How do I wrap this line of text</span>_x000D_
<span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
</p>
_x000D_
// CSS:
.nowrap {
white-space: nowrap ;
}
Method One (Small Sites Only):
Serve encrypted / encoded data.
I Scape the web using python (urllib, requests, beautifulSoup etc...) and found many websites that serve encrypted / encoded data that is not decrypt-able in any programming language simply because the encryption method does not exist.
I achieved this in a PHP website by encrypting and minimizing the output (WARNING: this is not a good idea for large sites) the response was always jumbled content.
Example of minimizing output in PHP (How to minify php page html output?):
<?php
function sanitize_output($buffer) {
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s' // shorten multiple whitespace sequences
);
$replace = array('>', '<', '\\1');
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
ob_start("sanitize_output");
?>
Method Two:
If you can't stop them screw them over serve fake / useless data as a response.
Method Three:
block common scraping user agents, you'll see this in major / large websites as it is impossible to scrape them with "python3.4" as you User-Agent.
Method Four:
Make sure all the user headers are valid, I sometimes provide as many headers as possible to make my scraper seem like an authentic user, some of them are not even true or valid like en-FU :).
Here is a list of some of the headers I commonly provide.
headers = {
"Requested-URI": "/example",
"Request-Method": "GET",
"Remote-IP-Address": "656.787.909.121",
"Remote-IP-Port": "69696",
"Protocol-version": "HTTP/1.1",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip,deflate",
"Accept-Language": "en-FU,en;q=0.8",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Dnt": "1",
"Host": "http://example.com",
"Referer": "http://example.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"
}
@shrx I've succeeded to unpack the BSD.pkg (part of the Yosemite installer) by using "pbzx" command.
pbzx <pkg> | cpio -idmu
The "pbzx" command can be downloaded from the following link:
if you dont have apparmor or selinux issues, but still get errorcode 13's:
mysql must be able to access the full path. I.e. all folders must be mysql accessible, not just the one you intend in pointing to.
example, you try using this in your mysql configuration: tmp = /some/folder/on/disk
# will work, as user root:
mkdir -p /some/folder/on/disk
chown -R mysql:mysql /some
# will not work, also as user root:
mkdir -p /some/folder/on/disk
chown -R mysql:mysql /some/folder/on/disk
You can find answer in depth here.
But in general with float
you need to be aware and take care of the surrounding elements and inline-block
simple way to line elements.
Thanks
See This code :
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground )
{
//opened from a push notification when the app was on background
}
}
same as
-(void)application:(UIApplication *)application didReceiveLocalNotification (UILocalNotification *)notification
Absolute positioning is based on co-ordiantes of the display:
position:absolute;
top:0px;
left:0px;
^ places the element top left of the window.
Relative position is relative to where the element is placed:
position:relative;
top:1px;
left:1px;
^ places the element 1px down and 1px from the left of where it originally sat :)
Take a look at SimpleDateFormat
:
java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));
It's a shortened "N-tuple
" (like in quadruple
, quintuple
etc.)
It's a row of a rowset taken as a whole.
If you issue:
SELECT col1, col2
FROM mytable
, whole result will be a ROWSET
, and each pair of col1, col2
will be a tuple
.
Some databases can work with a tuple as a whole.
Like, you can do this:
SELECT col1, col2
FROM mytable
WHERE (col1, col2) =
(
SELECT col3, col4
FROM othertable
)
, which checks that a whole tuple
from one rowset
matches a whole tuple
from another rowset
.
.. the array I get is very little randomized. It generates a lot of blocks of successive numbers...
Sequences of random items often contain blocks of successive numbers, see the Gambler's Fallacy. For example:
.. we have just tossed four heads in a row .. Since the probability of a run of five successive heads is only 1/32 .. a person subject to the gambler's fallacy might believe that this next flip was less likely to be heads than to be tails. http://en.wikipedia.org/wiki/Gamblers_fallacy
Try applying this style to your div class="input-group"
:
text-align:center;
View it: Fiddle.
Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.
This is what your code sees
0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M
Try this
0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M
while(file.good())
{
getline(file, ID, ',');
cout << "ID: " << ID << " " ;
getline(file, nome, ',') ;
cout << "User: " << nome << " " ;
getline(file, idade, ',') ;
cout << "Idade: " << idade << " " ;
getline(file, genero) ; \\ diff
cout << "Sexo: " << genero;\\diff
}
Its very simple
function archiveRemove(any) {
var click = $(any);
var id = click.attr("id");
swal.fire({
title: 'Are you sure !',
text: "?????",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'yes!',
cancelButtonText: 'no'
}).then(function (success) {
if (success) {
$('a[id="' + id + '"]').parents(".archiveItem").submit();
}
})
}
Try adding JSON.stringify(result)
to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error
which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.
This warning is about unsafe use of strcpy. Try IOBname[ii]='\0';
instead.
This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.
wp_users
, add a key, like abc123 to the
user_activation
column. You could also use:
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
There was another question that was closed as being a duplicate of this one, but if you read it closely, it's subtly different. So in case someone (like me) actually wants to split a list into a given number of almost equally sized sublists, then read on.
I simply ported the algorithm described here to Java.
@Test
public void shouldPartitionListIntoAlmostEquallySizedSublists() {
List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f", "g");
int numberOfPartitions = 3;
List<List<String>> split = IntStream.range(0, numberOfPartitions).boxed()
.map(i -> list.subList(
partitionOffset(list.size(), numberOfPartitions, i),
partitionOffset(list.size(), numberOfPartitions, i + 1)))
.collect(toList());
assertThat(split, hasSize(numberOfPartitions));
assertEquals(list.size(), split.stream().flatMap(Collection::stream).count());
assertThat(split, hasItems(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e"), Arrays.asList("f", "g")));
}
private static int partitionOffset(int length, int numberOfPartitions, int partitionIndex) {
return partitionIndex * (length / numberOfPartitions) + Math.min(partitionIndex, length % numberOfPartitions);
}
I have changed it in the following steps:
1) please add this dependency on your pubspec.yaml page
dev_dependencies:
flutter_test:
sdk: flutter
flutter_launcher_icons: ^0.7.4
2) you have to upload an image/icon on your project which you want to see as a launcher icon. (i have created a folder name:image in my project then upload the logo.png in the image folder). Now you have to add the below codes and paste your image path on image_path: in pubspec.yaml page.
flutter_icons:
image_path: "images/logo.png"
android: true
ios: true
3) Go to terminal and execute this command:
flutter pub get
4) After executing the command then enter below command:
flutter pub run flutter_launcher_icons:main
5) Done
N.B: (of course add an updated dependency from
https://pub.dev/packages/flutter_launcher_icons#-installing-tab-
)
As GvS said, but I also find it useful to use strongly typed views so that I can write something like
@Html.Partial(MVC.Student.Index(), model)
without magic strings.
.NET XSLT implementation allows to write custom managed functions in the stylesheet. For lower-case() it can be:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:utils="urn:myExtension" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<msxsl:script implements-prefix="utils" language="C#">
<![CDATA[
public string ToLower(string stringValue)
{
string result = String.Empty;
if(!String.IsNullOrEmpty(stringValue))
{
result = stringValue.ToLower();
}
return result;
}
]]>
</msxsl:script>
<!-- using of our custom function -->
<lowercaseValue>
<xsl:value-of select="utils:ToLower($myParam)"/>
</lowercaseValue>
Assume, that can be slow, but still acceptable.
Do not forget to enable embedded scripts support for transform:
// Create the XsltSettings object with script enabled.
XsltSettings xsltSettings = new XsltSettings(false, true);
XslCompiledTransform xslt = new XslCompiledTransform();
// Load stylesheet
xslt.Load(xsltPath, xsltSettings, new XmlUrlResolver());
You should be able to do that with the Batch Task plugin.
An alternative can also be Post build task plugin.
You have to set setOnItemLongClickListener() in the ListView:
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Log.v("long clicked","pos: " + pos);
return true;
}
});
The XML for each item in the list (should you use a custom XML) must have android:longClickable="true"
as well (or you can use the convenience method lv.setLongClickable(true);
). This way you can have a list with only some items responding to longclick.
Hope this will help you.
A C++14 version of the answer provided by R. Martinho Fernandes would be:
#include <type_traits>
template <typename E>
constexpr auto to_underlying(E e) noexcept
{
return static_cast<std::underlying_type_t<E>>(e);
}
As with the previous answer, this will work with any kind of enum and underlying type. I have added the noexcept
keyword as it will never throw an exception.
Update
This also appears in Effective Modern C++ by Scott Meyers. See item 10 (it is detailed in the final pages of the item within my copy of the book).
This is the extension I use for calculating multiline UILabel heights, it's an adjusted snippet from a previous stack overflow post:
extension UILabel {
func estimatedHeight(forWidth: CGFloat, text: String, ofSize: CGFloat) -> CGFloat {
let size = CGSize(width: forWidth, height: CGFloat(MAXFLOAT))
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: ofSize)]
let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height
return ceil(rectangleHeight)
}
}
Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:
JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);
According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
return font.deriveFont(12f);
You forgot to add std::
namespace prefix to vector
class name.
The following method would help you in finding day of any specified date :
public static int getDayOfMonth(Date aDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(aDate);
return cal.get(Calendar.DAY_OF_MONTH);
}
Javascript provides more than one method to check the viewport width. As you noticed, innerWidth doesn't include the toolbar width, and toolbar widths will differ across systems. There is also the outerWidth option, which will include the toolbar width. The Mozilla Javascript API states:
Window.outerWidth gets the width of the outside of the browser window. It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles.
The state of javascript is such that one cannot rely on a specific meaning for outerWidth in every browser on every platform.
outerWidth
is not well supported on older mobile browsers, though it enjoys support across major desktop browsers and most newer smart phone browsers.
As ausi pointed out, matchMedia
would be a great choice as CSS is better standardised (matchMedia uses JS to read the viewport values detected by CSS). But even with accepted standards, retarded browsers still exist that ignore them (IE < 10 in this case, which makes matchMedia not very useful at least until XP dies).
In summary, if you are only developing for desktop browsers and newer mobile browsers, outerWidth should give you what you are looking for, with some caveats.
I've got some subprojects.
I solved this problem via adding xib file to Copy Bundle Resources build phase of main project.
I often hit this error and it's always when I run a stored procedure that I have been debugging in phpmyadmin or SQL Workbench (I am working in php connecting with mysqli).
The error results from the fact that the debugging involves inserting SELECT statements at strategic points in the code to tell me the state of variables, etc. Running a stored procedure that produces multiple results sets in these client environments is fine, but it produces the "Commands out of sync" error when called from php. The solution is always to comment-out or remove the debugging selects so the procedure has only one result set.
[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex]
will give you uitableviewcell. But I am not sure what exactly you are asking for! Because you have this code and still you asking how to get uitableviewcell. Some more information will help to answer you :)
ADD: Here is an alternate syntax that achieves the same thing without the cast.
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];
I think if you check your manifest first if you wrote android:hardwareAccelerated="false"
you should make it true
to having shadow for the card
Like this answer here
This worked for me.
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};
fetch(`${url}`, requestOptions)
.then((res) => {
return res.blob();
})
.then((blob) => {
const href = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.setAttribute('download', 'config.json'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch((err) => {
return Promise.reject({ Error: 'Something Went Wrong', err });
})
Visual Studio 2017 or 2019 is totally unthoughtful on this, because Visual Studio itself requires the output to be in json format, while Visual Studio's default format is "XmlFormat" (config.Formatters.XmlFormatter).
Visual Studio should do this automatically instead of giving developers so much trouble.
To correct this problem, go to the WebApiConfig.cs file, and add
var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter);
after "config.MapHttpAttributeRoutes();" in the Register(HttpConfiguration config) method. This would allow your project to produce json output.
If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:
powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"
It is better to use Bypass
...
You cannot do new T()
due to type erasure. The default constructor can only be
public Navigation() { this("", "", null); }
You can create other constructors to provide default values for trigger and description. You need an concrete object of T
.
called_from
must be null
. Add a test against that condition like
if (called_from != null && called_from.equalsIgnoreCase("add")) {
or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null
behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)
if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null
I wanted to comment out a lot of lines in some config file on a server that only had vi (no nano), so visual method was cumbersome as well Here's how i did that.
vi file
:set number!
or :set number
:35,77s/^/#/
Note: the numbers are inclusive, lines from 35 to 77, both included will be modified.
To uncomment/undo that, simply use :35,77s/^#//
If you want to add a text word as a comment after every line of code, you can also use:
:35,77s/$/#test/
(for languages like Python)
:35,77s/;$/;\/\/test/
(for languages like Java)
credits/references:
Solution: In order to increase your buffer history on iterm bash terminal you've got two options:
Go to iterm -> Preferences -> Profiles -> Terminal Tab -> Scrollback Buffer (section)
Option 1. select the checkbox Unlimited scrollback
Option 2. type the selected Scrollback lines
numbers you'd like your terminal buffer to cache (See image below)
Append the following script to the following file (on the SSRS Server)
C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js
function pageLoad() {
var element = document.getElementById("ctl31_ctl10");
if (element)
{
element.style.overflow = "visible";
}
}
Note: As azzlak noted, the div's name isn't always ctl31_ctl10
. For SQL 2012 tryctl32_ctl09
and for 2008 R2 try ctl31_ctl09
. If this solution doesn't work, look at the HTML from your browser to see if the script has worked properly changing the overflow:auto
property to overflow:visible
.
Insert into .aspx
page (or into a linked .css
file, if available) this style line
#reportViewer_ctl09 {
overflow:visible !important;
}
Chrome and Safari render overflow:auto
in different way respect to IE.
SSRS HTML is QuirksMode HTML and depends on IE 5.5 bugs. Non-IE browsers don't have the IE quirksmode and therefore render the HTML correctly
The HTML page produced by SSRS 2008 R2 reports contain a div
which has overflow:auto
style, and it turns report into an invisible report.
<div id="ctl31_ctl10" style="height:100%;width:100%;overflow:auto;position:relative;">
I can see reports on Chrome by manually changing overflow:auto
to overflow:visible
in the produced webpage using Chrome's Dev Tools (F12).
I love Tim's solution, it's easy and working.
But there is still a problem: any time the user change parameters (my reports use parameters!) AJAX refreshes the div, the overflow:auto tag is rewritten, and no script changes it.
This technote detail explains what is the problem:
This happens because in a page built with AJAX panels, only the AJAX panels change their state, without refreshing the whole page. Consequently, the
OnLoad
events you applied on the<body>
tag are only fired once: the first time your page loads. After that, changing any of the AJAX panels will not trigger these events anymore.
User einarq suggested this solution:
Another option is to rename your function to pageLoad. Any functions with this name will be called automatically by asp.net ajax if it exists on the page, also after each partial update. If you do this you can also remove the onload attribute from the body tag
So wrote the improved script that is shown in the solution.
Different languages do different things with different levels of efficiency.
The Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.
Here is the best: Multipart/mixed mime message with attachments and inline images
And image: https://www.qcode.co.uk/images/mime-nesting-structure.png
From: [email protected]
To: to@@qcode.co.uk
Subject: Example Email
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="MixedBoundaryString"
--MixedBoundaryString
Content-Type: multipart/related; boundary="RelatedBoundaryString"
--RelatedBoundaryString
Content-Type: multipart/alternative; boundary="AlternativeBoundaryString"
--AlternativeBoundaryString
Content-Type: text/plain;charset="utf-8"
Content-Transfer-Encoding: quoted-printable
This is the plain text part of the email.
--AlternativeBoundaryString
Content-Type: text/html;charset="utf-8"
Content-Transfer-Encoding: quoted-printable
<html>
<body>=0D
<img src=3D=22cid:masthead.png=40qcode.co.uk=22 width 800 height=3D80=
=5C>=0D
<p>This is the html part of the email.</p>=0D
<img src=3D=22cid:logo.png=40qcode.co.uk=22 width 200 height=3D60 =5C=
>=0D
</body>=0D
</html>=0D
--AlternativeBoundaryString--
--RelatedBoundaryString
Content-Type: image/jpgeg;name="logo.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="logo.png"
Content-ID: <[email protected]>
amtsb2hiaXVvbHJueXZzNXQ2XHVmdGd5d2VoYmFmaGpremxidTh2b2hydHVqd255aHVpbnRyZnhu
dWkgb2l1b3NydGhpdXRvZ2hqdWlyb2h5dWd0aXJlaHN1aWhndXNpaHhidnVqZmtkeG5qaG5iZ3Vy
...
...
a25qbW9nNXRwbF0nemVycHpvemlnc3k5aDZqcm9wdHo7amlodDhpOTA4N3U5Nnkwb2tqMm9sd3An
LGZ2cDBbZWRzcm85eWo1Zmtsc2xrZ3g=
--RelatedBoundaryString
Content-Type: image/jpgeg;name="masthead.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="masthead.png"
Content-ID: <[email protected]>
aXR4ZGh5Yjd1OHk3MzQ4eXFndzhpYW9wO2tibHB6c2tqOTgwNXE0aW9qYWJ6aXBqOTBpcjl2MC1t
dGlmOTA0cW05dGkwbWk0OXQwYVttaXZvcnBhXGtsbGo7emt2c2pkZnI7Z2lwb2F1amdpNTh1NDlh
...
...
eXN6dWdoeXhiNzhuZzdnaHQ3eW9zemlqb2FqZWt0cmZ1eXZnamhka3JmdDg3aXV2dWd5aGVidXdz
dhyuhehe76YTGSFGA=
--RelatedBoundaryString--
--MixedBoundaryString
Content-Type: application/pdf;name="Invoice_1.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="Invoice_1.pdf"
aGZqZGtsZ3poZHVpeWZoemd2dXNoamRibngganZodWpyYWRuIHVqO0hmSjtyRVVPIEZSO05SVURF
SEx1aWhudWpoZ3h1XGh1c2loZWRma25kamlsXHpodXZpZmhkcnVsaGpnZmtsaGVqZ2xod2plZmdq
...
...
a2psajY1ZWxqanNveHV5ZXJ3NTQzYXRnZnJhZXdhcmV0eXRia2xhanNueXVpNjRvNWllc3l1c2lw
dWg4NTA0
--MixedBoundaryString
Content-Type: application/pdf;name="SpecialOffer.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="SpecialOffer.pdf"
aXBvY21odWl0dnI1dWk4OXdzNHU5NTgwcDN3YTt1OTQwc3U4NTk1dTg0dTV5OGlncHE1dW4zOTgw
cS0zNHU4NTk0eWI4OTcwdjg5MHE4cHV0O3BvYTt6dWI7dWlvenZ1em9pdW51dDlvdTg5YnE4N3Z3
...
...
OTViOHk5cDV3dTh5bnB3dWZ2OHQ5dTh2cHVpO2p2Ymd1eTg5MGg3ajY4bjZ2ODl1ZGlvcjQ1amts
dfnhgjdfihn=
--MixedBoundaryString--
.
Schema multipart/related/alternative
Header
|From: email
|To: email
|MIME-Version: 1.0
|Content-Type: multipart/mixed; boundary="boundary1";
Message body
|multipart/mixed --boundary1
|--boundary1
| multipart/related --boundary2
| |--boundary2
| | multipart/alternative --boundary3
| | |--boundary3
| | |text/plain
| | |--boundary3
| | |text/html
| | |--boundary3--
| |--boundary2
| |Inline image
| |--boundary2
| |Inline image
| |--boundary2--
|--boundary1
|Attachment1
|--boundary1
|Attachment2
|--boundary1
|Attachment3
|--boundary1--
|
.
I think the following way you can do it,
typedef struct
{
int flag : 3;
} MyStruct;
If you are using Babel or such transpilers and using async/await you could do :
function onDrop() {
console.log("dropped");
}
async function dropAll( collections ) {
const drops = collections.map(col => conn.collection(col).drop(onDrop) );
await drops;
console.log("all dropped");
}
For a GUI approach I would take a look at Activity Monitor under Management and sort by CPU.
There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array
, then it becomes a generic object.
I am in the same boat as you do. I need to study for tech interviews, but memorizing a list is not really helpful. If you have 3-4 hours to spare, and want to do a deeper dive, I recommend checking out
mycodeschool
I’ve looked on Coursera and other resources such as blogs and textbooks,
but I find them either not comprehensive enough or at the other end of the spectrum, too dense with prerequisite computer science terminologies.
The dude in the video have a bunch of lectures on data structures. Don’t mind the silly drawings, or the slight accent at all. You need to understand not just which data structure to select, but some other points to consider when people think about data structures:
You can use the shortcode media API from instagram. If you use php you can use the following code to get the shortcode from the image's URL:
$matches = [];
preg_match('/instagram\.com\/p\/([^\/]*)/i', $url, $matches);
if (count($matches) > 1) {
$shortcode = $matches[1];
}
Then send a request to the API using your access token (Replace ACCESS-TOKEN
with your token)
$apiUrl = sprintf("https://api.instagram.com/v1/media/shortcode/%s?access_token=ACCESS-TOKEN", $shortcode);
Resurrecting this to post the DISTINCT FROM
option, which has been around since Postgres 8. The approach is similar to Brad Dre's answer. In your case, your select would be something like
SELECT *
FROM table_name
WHERE boolean_column IS DISTINCT FROM TRUE
Small edit to @seengee answer: In order to work, you need curly braces around the variable, otherwise you'll get an error.
header("Content-type: {$imginfo['mime']}");
I know you already accepted the other answer, but if you want to do this as a DataFrame, just use groupBy and agg. Assuming you had a DF already created (with columns named "col1", "col2", etc) you could do:
myDF.groupBy($"col1", $"col3", $"col4").agg($"col1", max($"col2"), $"col3", $"col4")
Note that in this case, I chose the Max of col2, but you could do avg, min, etc.
For reference and adding to answers citing mefa, it might worth to take a look on the implementation of mefa::rep.data.frame()
in case you don't want to include the whole package:
> data <- data.frame(a=letters[1:3], b=letters[4:6])
> data
a b
1 a d
2 b e
3 c f
> as.data.frame(lapply(data, rep, 2))
a b
1 a d
2 b e
3 c f
4 a d
5 b e
6 c f
You can use the Partial
mapped type as explained in the documentation:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
In your example, you'll have:
interface IX {
a: string;
b: any;
c: AnotherType;
}
let x: Partial<IX> = {
a: 'abc'
}
Simple & Best way:
onclick="parentNode.remove()"
Deletes the complete parent from html
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
Sure you can:
Option Explicit
'***** User defined type
Public Type MyType
MyInt As Integer
MyString As String
MyDoubleArr(2) As Double
End Type
'***** Testing MyType as single variable
Public Sub MyFirstSub()
Dim MyVar As MyType
MyVar.MyInt = 2
MyVar.MyString = "cool"
MyVar.MyDoubleArr(0) = 1
MyVar.MyDoubleArr(1) = 2
MyVar.MyDoubleArr(2) = 3
Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub
'***** Testing MyType as an array
Public Sub MySecondSub()
Dim MyArr(2) As MyType
Dim i As Integer
MyArr(0).MyInt = 31
MyArr(0).MyString = "VBA"
MyArr(0).MyDoubleArr(0) = 1
MyArr(0).MyDoubleArr(1) = 2
MyArr(0).MyDoubleArr(2) = 3
MyArr(1).MyInt = 32
MyArr(1).MyString = "is"
MyArr(1).MyDoubleArr(0) = 11
MyArr(1).MyDoubleArr(1) = 22
MyArr(1).MyDoubleArr(2) = 33
MyArr(2).MyInt = 33
MyArr(2).MyString = "cool"
MyArr(2).MyDoubleArr(0) = 111
MyArr(2).MyDoubleArr(1) = 222
MyArr(2).MyDoubleArr(2) = 333
For i = LBound(MyArr) To UBound(MyArr)
Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
Next
End Sub
something like this works for me:
file.awk:
BEGIN {
record=0
}
/^abc$/ {
record=1
}
/^mno$/ {
record=0;
print "s="s;
s=""
}
!/^abc|mno$/ {
if (record==1) {
s = s"\n"$0
}
}
using: awk -f file.awk data
...
edit: O_o fedorqui solution is way better/prettier than mine.
Thanks to Bobbin, mcgrailm, Tony, James Pasta and a few others who posted here. I had written my own function to add business days to a date, but modified it with some code I found here. This will handle the start date being on a weekend/holiday. This will also handle business hours. I added some comments and break up the code to make it easier to read.
<?php
function count_business_days($date, $days, $holidays) {
$date = strtotime($date);
for ($i = 1; $i <= intval($days); $i++) { //Loops each day count
//First, find the next available weekday because this might be a weekend/holiday
while (date('N', $date) >= 6 || in_array(date('Y-m-d', $date), $holidays)){
$date = strtotime(date('Y-m-d',$date).' +1 day');
}
//Now that we know we have a business day, add 1 day to it
$date = strtotime(date('Y-m-d',$date).' +1 day');
//If this day that was previously added falls on a weekend/holiday, then find the next business day
while (date('N', $date) >= 6 || in_array(date('Y-m-d', $date), $holidays)){
$date = strtotime(date('Y-m-d',$date).' +1 day');
}
}
return date('Y-m-d', $date);
}
//Also add in the code from Tony and James Pasta to handle holidays...
function getNationalAmericanHolidays($year) {
$bankHolidays = array(
'New Years Day' => $year . "-01-01",
'Martin Luther King Jr Birthday' => "". date("Y-m-d",strtotime("third Monday of January " . $year) ),
'Washingtons Birthday' => "". date("Y-m-d",strtotime("third Monday of February " . $year) ),
'Memorial Day' => "". date("Y-m-d",strtotime("last Monday of May " . $year) ),
'Independance Day' => $year . "-07-04",
'Labor Day' => "". date("Y-m-d",strtotime("first Monday of September " . $year) ),
'Columbus Day' => "". date("Y-m-d",strtotime("second Monday of October " . $year) ),
'Veterans Day' => $year . "-11-11",
'Thanksgiving Day' => "". date("Y-m-d",strtotime("fourth Thursday of November " . $year) ),
'Christmas Day' => $year . "-12-25"
);
return $bankHolidays;
}
//Now to call it... since we're working with business days, we should
//also be working with business hours so check if it's after 5 PM
//and go to the next day if necessary.
//Go to next day if after 5 pm (5 pm = 17)
if (date(G) >= 17) {
$start_date = date("Y-m-d", strtotime("+ 1 day")); //Tomorrow
} else {
$start_date = date("Y-m-d"); //Today
}
//Get the holidays for the current year and also for the next year
$this_year = getNationalAmericanHolidays(date('Y'));
$next_year = getNationalAmericanHolidays(date('Y', strtotime("+12 months")));
$holidays = array_merge($this_year, $next_year);
//The number of days to count
$days_count = 10;
echo count_business_days($start_date, $days_count, $holidays);
?>
try
java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main
If you are on windows, you should use ;
instead of :
This might be a dead horse, another way to return 1 row when no rows exist is to UNION another query and display results when non exist in the table.
SELECT S.Status, COUNT(s.id) AS StatusCount
FROM Sites S
WHERE S.Id = @SiteId
GROUP BY s.Status
UNION ALL --UNION BACK ON TABLE WITH NOT EXISTS
SELECT 'N/A' AS Status, 0 AS StatusCount
WHERE NOT EXISTS (SELECT 1
FROM Sites S
WHERE S.Id = @SiteId
)
The simplest technique is to use NSString *uuid = [[NSProcessInfo processInfo] globallyUniqueString]
. See the NSProcessInfo class reference.
Below code can be used to Remove New Line and Table Space in text column
Select replace(replace(TEXT,char(10),''),char(13),'')
It's Much Simplier!
Pure batch solution. No temp files. No long scripts.
@echo off
setlocal enabledelayedexpansion
set String=abcde12345
for /L %%x in (1,1,1000) do ( if "!String:~%%x!"=="" set Lenght=%%x & goto Result )
:Result
echo Lenght: !Lenght!
1000
is the maximum estimated string lenght. Change it based on your needs.
The most efficient way:
//Note destroys the original string by removing it's last char
// Do not pass in a string literal.
char * getAllButFirstAndLast(char *input)
{
int len = strlen(input);
if(len > 0)
input++;//Go past the first char
if(len > 1)
input[len - 2] = '\0';//Replace the last char with a null termination
return input;
}
//...
//Call it like so
char str[512];
strcpy(str, "hello world");
char *pMod = getAllButFirstAndLast(str);
The safest way:
void getAllButFirstAndLast(const char *input, char *output)
{
int len = strlen(input);
if(len > 0)
strcpy(output, ++input);
if(len > 1)
output[len - 2] = '\0';
}
//...
//Call it like so
char mod[512];
getAllButFirstAndLast("hello world", mod);
The second way is less efficient but it is safer because you can pass in string literals into input. You could also use strdup for the second way if you didn't want to implement it yourself.
If you want Selected.Value being worked you have to do following things:
1. Set DisplayMember
2. Set ValueMember
3. Set DataSource (not use Items.Add, Items.AddRange, DataBinding etc.)
The key point is Set DataSource!
You can use DATEPART(dw, GETDATE())
but be aware that the result will rely on SQL server setting @@DATEFIRST
value which is the first day of week setting (In Europe default value 7 which is Sunday).
If you want to change the first day of week to another value, you could use SET DATEFIRST
but this may affect everywhere in your query session which you do not want.
Alternative way is to explicitly specify the first day of week value as parameter and avoid depending on @@DATEFIRST
setting. You can use the following formula to achieve that when need it:
(DATEPART(dw, GETDATE()) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1
where @WeekStartDay
is the first day of the week you want for your system (from 1 to 7 which means from Monday to Sunday).
I have wrapped it into below function so we can reuse it easily:
CREATE FUNCTION [dbo].[GetDayInWeek](@InputDateTime DATETIME, @WeekStartDay INT)
RETURNS INT
AS
BEGIN
--Note: @WeekStartDay is number from [1 - 7] which is from Monday to Sunday
RETURN (DATEPART(dw, @InputDateTime) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1
END
Example usage:
GetDayInWeek('2019-02-04 00:00:00', 1)
It is equivalent to following (but independent to SQL server DATEFIRST setting):
SET DATEFIRST 1
DATEPART(dw, '2019-02-04 00:00:00')
Please note that increasing the Java heap size following an java.lang.OutOfMemoryError: Java heap space is quite often just a short term solution.
This means that even if you increase the default Java heap size from 512 MB to let's say 2048 MB, you may still get this error at some point if you are dealing with a memory leak. The main question to ask is why are you getting this OOM error at the first place? Is it really a Xmx value too low or just a symptom of another problem?
When developing a Java application, it is always crucial to understand its static and dynamic memory footprint requirement early on, this will help prevent complex OOM problems later on. Proper sizing of JVM Xms & Xmx settings can be achieved via proper application profiling and load testing.
These two commands should do it:
:set autoindent
:set cindent
For bonus points put them in a file named .vimrc located in your home directory on linux
You can insert into a table from a SELECT.
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
(SELECT id FROM state WHERE name = 'New York'),
(SELECT id FROM positions WHERE name = 'Sales Executive'),
(SELECT id FROM manager WHERE name = 'Barry Green')
FROM
dual
Or, similarly...
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
state.id,
positions.id,
manager.id
FROM
state
CROSS JOIN
positions
CROSS JOIN
manager
WHERE
state.name = 'New York'
AND positions.name = 'Sales Executive'
AND manager.name = 'Barry Green'
Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.
You could also grab the attributes with the getAttribute() method which will return the value of a specific HTML attribute.
var elem = document.getElementById('the-span');_x000D_
_x000D_
var typeId = elem.getAttribute('data-typeId');_x000D_
var type = elem.getAttribute('data-type');_x000D_
var points = elem.getAttribute('data-points');_x000D_
var important = elem.getAttribute('data-important');_x000D_
_x000D_
console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`_x000D_
);
_x000D_
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
_x000D_
I went through the solutions on the internet. Mostly solutions didn't work in the project I'm working on. Following solutions work fine for me.
Using onScrollChangeListener (works on API 23):
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
int bottom = (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollY;
if(scrollY==0){
//top detected
}
if(bottom==0){
//bottom detected
}
}
});
}
using scrollChangeListener on TreeObserver
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
int bottom = (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollView.getScrollY();
if(scrollView.getScrollY()==0){
//top detected
}
if(bottom==0) {
//bottom detected
}
}
});
Hope this solution helps :)
A simple one would be
\d{4}-\d{2}-\d{2}
but this does not restrict month to 1-12 and days from 1 to 31.
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
After tying different answers finally, @Kayvar answers's first four lines help me to solve the issue:
npm config set registry http://registry.npmjs.org/
npm config set proxy http://myusername:[email protected]:8080
npm config set https-proxy http://myusername:[email protected]:8080
npm config set strict-ssl false
Open the file for 'append' rather than 'write'.
with open('file.txt', 'a') as file:
file.write('input')
Assuming the parent has a fixed width, e.g #page { width: 1000px; }
and is centered #page { margin: auto; }
, you want the child to fit the width of browser viewport you could simply do:
#page {
margin: auto;
width: 1000px;
}
.fullwidth {
margin-left: calc(500px - 50vw); /* 500px is half of the parent's 1000px */
width: 100vw;
}
Try this expression...
string-join(//element3/(concat(element4/text(), '.', element5/text())), " ")
You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save().
Basically, a field declared as a FileField
, when accessed, gives you an instance of class FieldFile
, which gives you several methods to interact with the underlying file. So, what you need to do is:
self.license_file.save(new_name, new_contents)
where new_name
is the filename you wish assigned and new_contents
is the content of the file. Note that new_contents
must be an instance of either django.core.files.File
or django.core.files.base.ContentFile
(see given links to manual for the details).
The two choices boil down to:
from django.core.files.base import ContentFile, File
# Using File
with open('/path/to/file') as f:
self.license_file.save(new_name, File(f))
# Using ContentFile
self.license_file.save(new_name, ContentFile('A string with the file content'))
Or just put it on one line, as make
likes it:
if [ -a myApp ]; then rm myApp; fi;
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
driver = new ChromeDriver(options);
I have used it for Java with Chrome browser it is working nice
Add the css styling text-align: center
to the control.
Ideally you would do this through a css class assigned to the control, but if you must do it directly, here is an example:
<asp:TextBox ID="myTextBox" runat="server" style="text-align: center"></asp:TextBox>
You can also limit the filter to only part of the ip address.
E.G. To filter 123.*.*.*
you can use ip.addr == 123.0.0.0/8
. Similar effects can be achieved with /16
and /24
.
See WireShark man pages (filters) and look for Classless InterDomain Routing (CIDR) notation.
... the number after the slash represents the number of bits used to represent the network.
I have solved this problem with changing encoding in read.table argument from fileEncoding = "UTF-16" to fileEncoding = "UTF-8".
Node next = tmp.next;
while(tmp != null){
So what happens when tmp == null?
You almost got it, though.
Node before = null;
Node tmp = head;
while (tmp != null) {
Node next = tmp.next;
tmp.next = before;
before = tmp;
tmp = next;
}
head = before;
Or in nicer (?) naming:
Node reversedPart = null;
Node current = head;
while (current != null) {
Node next = current.next;
current.next = reversedPart;
reversedPart = current;
current = next;
}
head = reversedPart;
ASCII art:
<__<__<__ __ : reversedPart : head
(__)__ __ __
head : current: > > >
This is better method how insert item to array on some position.
function arrayInsert($array, $item, $position)
{
$begin = array_slice($array, 0, $position);
array_push($begin, $item);
$end = array_slice($array, $position);
$resultArray = array_merge($begin, $end);
return $resultArray;
}
Here is my combined solution for various PHP versions.
In my company we are working with different servers with various PHP versions, so I had to find solution working for all.
$phpVersion = substr(phpversion(), 0, 3)*1;
if($phpVersion >= 5.4) {
$encodedValue = json_encode($value, JSON_UNESCAPED_UNICODE);
} else {
$encodedValue = preg_replace('/\\\\u([a-f0-9]{4})/e', "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($value));
}
Credits should go to Marco Gasi & abu. The solution for PHP >= 5.4 is provided in the json_encode docs.
Try the following:
List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
List<string> test2 = new List<string> { "[email protected]", "[email protected]" };
var output = from goodEmails in test2
where !(from email in test2
from domain in test1
where email.EndsWith(domain)
select email).Contains(goodEmails)
select goodEmails;
This works with the test set provided (and looks correct).
In C# 8.0 and above, you can use the range operator ..
as in
var s = "header-THE_TARGET_STRING.7z";
var from = s.IndexOf("-") + "-".Length;
var to = s.IndexOf(".7z");
var versionString = s[from..to]; // THE_TARGET_STRING
See documentation for details.
I was looking for the same thing since the background of my select is the same as the arrow color. As previously mentioned, it is impossible yet to add anything using :before or :after on a select element. My solution was to create a wrapper element on which I added the following :before code.
.select-wrapper {
position: relative;
}
.select-wrapper:before {
content: '\f0d7';
font-family: FontAwesome;
color: #fff;
display: inline-block;
position: absolute;
right: 20px;
top: 15px;
pointer-events: none;
}
And this my select
select {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
width: 100%;
padding: 10px 20px;
background: #000;
color: #fff;
border: none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
select::-ms-expand {
display: none;
}
I have used FontAwesome.io for my new arrow, but you can use whatever else you want. Obviously this is not a perfect solution, but depending on your needs it might be enough.
value = (round(value*100)) / 100.0;
$this->db->count_all_results
is part of an Active Record query (preparing the query, to only return the number, not the actual results).
$query->num_rows()
is performed on a resultset object (after returning results from the DB).
The native option is missing so I'll add it for the next guy/gall that looks for it.
Starting on Django 1.7.x there is a built-in DjangoJSONEncoder
that you can get it from django.core.serializers.json
.
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.forms.models import model_to_dict
model_instance = YourModel.object.first()
model_dict = model_to_dict(model_instance)
json.dumps(model_dict, cls=DjangoJSONEncoder)
Presto!
If you're using Windows, the unix-style default path of ssh-keygen is at fault.
In Line 2 it says Enter file in which to save the key (/c/Users/Eva/.ssh/id_rsa):
.
That full filename in the parantheses is the default, obviously Windows cannot access a file like that. If you type the Windows equivalent (c:\Users\Eva\.ssh\id_rsa
), it should work.
Before running this, you also need to create the folder. You can do this by running mkdir c:\Users\Eva\.ssh
, or by created the folder ".ssh." from File Explorer (note the second dot at the end, which will get removed automatically, and is required to create a folder that has a dot at the beginning).
c:\Users\Administrator\.ssh>ssh-keygen -t rsa -C "[email protected]"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/Administrator/.ssh/id_rsa): C:\Users\Administrator\.ssh\id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\Administrator\.ssh\id_rsa.
Your public key has been saved in C:\Users\Administrator\.ssh\id_rsa.pub.
The key fingerprint is:
... [email protected]
The key's randomart image is:...`
I know this is an old thread, but I thought the answer might help others.
React Router v3
With React Router v3, you can get query-string from this.props.location.search
(?qs1=naisarg&qs2=parmar). For example, with let params = queryString.parse(this.props.location.search)
, would give { qs1 : 'naisarg', qs2 : 'parmar'}
React Router v4
With React Router v4, the this.props.location.query
does not exist anymore. You need to use this.props.location.search
instead and parse the query parameters either by yourself or using an existing package such as query-string
.
Example
Here is a minimal example using React Router v4 and the query-string
library.
import { withRouter } from 'react-router-dom';
import queryString from 'query-string';
class ActivateAccount extends Component{
someFunction(){
let params = queryString.parse(this.props.location.search)
...
}
...
}
export default withRouter(ActivateAccount);
Rational
The React Router's team rational for removing the query
property is:
There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right".
[...]
The approach being taken for 4.0 is to strip out all the "batteries included" kind of features and get back to just basic routing. If you need query string parsing or async loading or Redux integration or something else very specific, then you can add that in with a library specifically for your use case. Less cruft is packed in that you don't need and you can customize things to your specific preferences and needs.
You can find the full discussion on GitHub.
Like this:
which lshw
To see all of the commands that match in your path:
which -a lshw
put this line in xml
android:inputType="number|numberDecimal"
You have several options:
string[] items = { "Item1", "Item2", "Item3", "Item4" };
string[] items = new string[]
{
"Item1", "Item2", "Item3", "Item4"
};
string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...
Open Chrome Dev Tools or equivalent and run require('React').version
in the console.
That works on websites like Facebook as well to find out what version they are using.
Using the info from this blogpost:
Like others have said, res:\\ is a pointer to your resources. To check and make sure your resource names are correct you can use a decompiler like DotPeek by JetBrains to open up your .dll file and see your Resources files.
Or you could open up the watch window while you're debugging and paste in this code to get an array of the resource names in the currently executing assembly.
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames()
That being said, the format of your metadata paths should be something like:
{my-assembly-name}/{possibly-a-namespace}.{class-name}.{csdl or ssdl or msl}
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}