Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.
[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.
No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.
To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active
public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
try
{
//check the domain first
if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
{
//only now check the url itself
var request = System.Net.WebRequest.Create(aUrl);
request.Method = "HEAD";
request.Timeout = aTimeoutSeconds * 1000;
var response = (HttpWebResponse)request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
}
return false;
}
private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
try
{
using (TcpClient client = new TcpClient())
{
var result = client.BeginConnect(aDomain, 80, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));
if (!success)
{
return false;
}
// we have connected
client.EndConnect(result);
return true;
}
}
catch
{
}
return false;
}
hash_map is a non-standard extension. unordered_map is part of std::tr1, and will be moved into the std namespace for C++0x. http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29
With this method you can set font size, font style and Header background also. there are have 2 method for this
First Method
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.backgroundView.backgroundColor = [UIColor darkGrayColor];
header.textLabel.font=[UIFont fontWithName:@"Open Sans-Regular" size:12];
[header.textLabel setTextColor:[UIColor whiteColor]];
}
Second Method
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
// myLabel.frame = CGRectMake(20, 8, 320, 20);
myLabel.font = [UIFont fontWithName:@"Open Sans-Regular" size:12];
myLabel.text = [NSString stringWithFormat:@" %@",[self tableView:FilterSearchTable titleForHeaderInSection:section]];
myLabel.backgroundColor=[UIColor blueColor];
myLabel.textColor=[UIColor whiteColor];
UIView *headerView = [[UIView alloc] init];
[headerView addSubview:myLabel];
return headerView;
}
You should specify where Eclipse should find your JDK in the file eclipse.ini. Specifically, the following parameter (note that it is 2 separate lines in the ini file):
-vm
C:\Java\JDK\1.8\bin\javaw.exe
or wherever your javaw.exe happens to be.
Note: The format of the ini file is very particular; make sure to consult https://wiki.eclipse.org/Eclipse.ini to ensure you get it exactly right
Add this to the pre-built:
(if exist "$(TargetDir)*old.exe" del "$(TargetDir)*old.exe") & (if exist "$(TargetDir)*.exe" ren "$(TargetDir)*.exe" *.old.exe)
It may also be the case that the library containing the class in question is not properly signed with a strong name.
As an additional note, there is no need for the for loop because of R's vectorization.
This:
P <- 243.51
t <- 31 / 365
n <- 365
for (r in seq(0.15, 0.22, by = 0.01))
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
}
is equivalent to:
P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
Because r
is a vector, the expression above containing it is performed for all values of the vector.
import pdb
pdb.debug()
This is used to debug the script. Should be useful to break also.
attr_accessor
is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname
and you can use this field in your View, or model, if you wanted, but mostly in your View.
Let's consider the following example
class Address
attr_reader :street
attr_writer :street
def initialize
@street = ""
end
end
Here we have used attr_reader
(readable attribute) and attr_writer
(writable attribute) for accessing purpose. But we can achieve the same functionality using attr_accessor
. In short, attr_accessor provides access to both getter and setter methods.
So modified code is as below
class Address
attr_accessor :street
def initialize
@street = ""
end
end
attr_accessible
allows you to list all the columns you want to allow Mass Assignment. The opposite of this is attr_protected
which means this field I do NOT want anyone to be allowed to Mass Assign to. More than likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.
Simply:
BASEDIR=$(readlink -f $0 | xargs dirname)
Fancy operators are not needed.
Please see the GridFS docs for details on storing such binary data.
Support for your specific language should be linked to at the bottom of the screen.
To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.
To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.
var rotated = false;
document.getElementById('button').onclick = function() {
var div = document.getElementById('div'),
deg = rotated ? 0 : 66;
div.style.webkitTransform = 'rotate('+deg+'deg)';
div.style.mozTransform = 'rotate('+deg+'deg)';
div.style.msTransform = 'rotate('+deg+'deg)';
div.style.oTransform = 'rotate('+deg+'deg)';
div.style.transform = 'rotate('+deg+'deg)';
rotated = !rotated;
}
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
To add some animation to the rotation all we have to do is add CSS transitions
div {
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript
document.getElementById('button').onclick = function() {
document.getElementById('div').classList.toggle('rotated');
}
document.getElementById('button').onclick = function() {_x000D_
document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
-webkit-transform : rotate(66deg); _x000D_
-moz-transform : rotate(66deg); _x000D_
-ms-transform : rotate(66deg); _x000D_
-o-transform : rotate(66deg); _x000D_
transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
[Source] From what I've found, it looks like by default, it's only possible to do production and development configs (no staging or other environments) – is that right?
Right now, I've been using a environment.js file that can be used to detect expo release channels and change the variables returned based on that, but for building, I need to update the non- DEV variable returned to be either staging or prod:
import { Constants } from 'expo';
import { Platform } from 'react-native';
const localhost = Platform.OS === 'ios' ? 'http://localhost:4000/' : 'http://10.0.2.2:4000/';
const ENV = {
dev: {
apiUrl: localhost,
},
staging: {
apiUrl: 'https://your-staging-api-url-here.com/'
},
prod: {
apiUrl: 'https://your-prod-api-url-here.com/'
},
}
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
// What is __DEV__ ?
// This variable is set to true when react-native is running in Dev mode.
// __DEV__ is true when run locally, but false when published.
if (__DEV__) {
return ENV.dev;
} else {
// When publishing to production, change this to `ENV.prod` before running an `expo build`
return ENV.staging;
}
}
export default getEnvVars;
Alternatives
does anyone have experience using react-native-dotenv for projects built with expo? I'd love to hear your thoughts
If using Angular Material Design, you can use the datepicker component there and this will work in Firefox, IE etc.
https://material.angularjs.org/latest/demo/datepicker
Fair warning though - personal experience is that there are problems with this, and seemingly it is being re-worked at present. See here:
Create "topN" query on "clientip" and then histogram with count on "clientip" and set "topN" query as source. Then you will see count of different ips per time.
That's definitely the best way for any array whose length is a signed integral type. For arrays whose lengths are an unsigned integral type (e.g. an std::vector
in C++), then you need to modify the end condition slightly:
for(size_t i = myArray.size() - 1; i != (size_t)-1; i--)
// blah
If you just said i >= 0
, this is always true for an unsigned integer, so the loop will be an infinite loop.
There are two ways to go about this:
I recommend the first option initially, due to its ease of implementation. Once you mature in your build processes, switch over to the second.
Poll the repository to see if changes occurred. This might "skip" a commit if two commits come in within the same polling interval. Description of how to do so here, note the fourth screenshot where you configure on the job a "build trigger" based on polling the repository (with a crontab-like configuration).
Configure your repository to have a post-commit hook which notifies Jenkins that a build needs to start. Description of how to do so here, in the section "post-commit hooks"
The SVN Tag feature is not part of the polling, it is part of promoting the current "head" of the source code to a tag, to snapshot a build. This allows you to refer to Jenkins buid #32 as SVN tag /tags/build-32 (or something similar).
Everything is possible only if there is enough time to research :)
What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B. even ui:repeat do not have id I put and it appeared in the DOM tree
<ui:repeat id="peopleRepeat"
value="#{myBean.people}"
var="person" varStatus="status">
Than the ids in the html were something like:
myForm:peopleRepeat:0:personType
myForm:peopleRepeat:1:personType
Than in the view I got one method like:
<p:ajax event="change"
listener="#{myBean.onPersonTypeChange(person, status.index)}"/>
And its implementation was in the bean like:
String componentId = "myForm:peopleRepeat" + idx + "personType";
PrimeFaces.current().ajax().update(componentId);
So this way I updated the element from the bean with no issues. PF version 6.2
Good luck and happy coding :)
A simplified version, I had a similar issue to this when using the Google Maps JS SDK.
My solution was to extract the div
and ViewChild
into it's own child component which when used in the parent component was able to be hid/displayed using an *ngIf
.
Before
HomePageComponent
Template
<div *ngIf="showMap">
<div #map id="map" class="map-container"></div>
</div>
HomePageComponent
Component
@ViewChild('map') public mapElement: ElementRef;
public ionViewDidLoad() {
this.loadMap();
});
private loadMap() {
const latLng = new google.maps.LatLng(-1234, 4567);
const mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
public toggleMap() {
this.showMap = !this.showMap;
}
After
MapComponent
Template
<div>
<div #map id="map" class="map-container"></div>
</div>
MapComponent
Component
@ViewChild('map') public mapElement: ElementRef;
public ngOnInit() {
this.loadMap();
});
private loadMap() {
const latLng = new google.maps.LatLng(-1234, 4567);
const mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
HomePageComponent
Template
<map *ngIf="showMap"></map>
HomePageComponent
Component
public toggleMap() {
this.showMap = !this.showMap;
}
If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:
#! /bin/bash
logfile="/var/oscamlog/oscam1check.log"
case "$(pidof oscam1 | wc -w)" in
0) echo "oscam1 not running, restarting oscam1: $(date)" >> $logfile
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
;;
2) echo "oscam1 running, all OK: $(date)" >> $logfile
;;
*) echo "multiple instances of oscam1 running. Stopping & restarting oscam1: $(date)" >> $logfile
kill $(pidof oscam1 | awk '{ $1=""; print $0}')
;;
esac
It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like
root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript
Just an FYI
For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.
The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval]
(string or int) which then allows you to refer to an existing record.
Imagine that this is your Json response
{"Visit":{"VisitId":8,"Description":"visit8"}}
This is how you parse the response and access the values
Ext.Ajax.request({
headers: {
'Content-Type': 'application/json'
},
url: 'api/fullvisit/getfullvisit/' + visitId,
method: 'GET',
dataType: 'json',
success: function (response, request) {
obj = JSON.parse(response.responseText);
alert(obj.Visit.VisitId);
}
});
This will alert the VisitId field
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=gmailpassword
[email protected]
need authenticate username and password of mail then only once can successfully send mail from localhost
All libraries like stdio.h
and stdlib.h
have their implementation in libc.so
or libc.a
and get linked by the linker by default. The libraries for libc.so
are automatically linked while compiling and is included in the executable file.
But math.h
has its implementations in libm.so
or libm.a
which is seperate from libc.so
and it does not get linked by default and you have to manually link it while compiling your program
in gcc
by using -lm
flag.
The gnu gcc team designed it to be seperate from the other header files, while the other header files get linked by default but math.h file doesn't.
Here read the item no 14.3, you could read it all if you wish:
Reason why math.h is needs to be linked
Look at this article: why we have to link math.h in gcc?
Have a look at the usage:
using the library
// set notification audio
builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR
builder.setDefaults(Notification.DEFAULT_SOUND);
a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.
if you want real difference
select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);
if you want absolute difference
select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));
Note Slipstream's response, that base64.b64encode
and base64.b64decode
need bytes-like object, not string.
>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
This is an old school approach, but if you're performing an iterative update or insert operation in SQL, something that runs for a long time, it's a good idea to periodically (programmatically) call "checkpoint". Calling "checkpoint" causes SQL to write to disk all of those memory-only changes (dirty pages, they're called) and items stored in the transaction log. This has the effect of cleaning out your transaction log periodically, thus preventing problems like the one described.
Using the sibling selector is the general solution for styling other elements when hovering over a given one, but it works only if the other elements follow the given one in the DOM. What can we do when the other elements should actually be before the hovered one? Say we want to implement a signal bar rating widget like the one below:
This can actually be done easily using the CSS flexbox model, by setting flex-direction
to reverse
, so that the elements are displayed in the opposite order from the one they're in the DOM. The screenshot above is from such a widget, implemented with pure CSS.
Flexbox is very well supported by 95% of modern browsers.
.rating {_x000D_
display: flex;_x000D_
flex-direction: row-reverse;_x000D_
width: 9rem;_x000D_
}_x000D_
.rating div {_x000D_
flex: 1;_x000D_
align-self: flex-end;_x000D_
background-color: black;_x000D_
border: 0.1rem solid white;_x000D_
}_x000D_
.rating div:hover {_x000D_
background-color: lightblue;_x000D_
}_x000D_
.rating div[data-rating="1"] {_x000D_
height: 5rem;_x000D_
}_x000D_
.rating div[data-rating="2"] {_x000D_
height: 4rem;_x000D_
}_x000D_
.rating div[data-rating="3"] {_x000D_
height: 3rem;_x000D_
}_x000D_
.rating div[data-rating="4"] {_x000D_
height: 2rem;_x000D_
}_x000D_
.rating div[data-rating="5"] {_x000D_
height: 1rem;_x000D_
}_x000D_
.rating div:hover ~ div {_x000D_
background-color: lightblue;_x000D_
}
_x000D_
<div class="rating">_x000D_
<div data-rating="1"></div>_x000D_
<div data-rating="2"></div>_x000D_
<div data-rating="3"></div>_x000D_
<div data-rating="4"></div>_x000D_
<div data-rating="5"></div>_x000D_
</div>
_x000D_
Your empList
is object type but you are trying to push strings
Try this
this.empList.push({this.name,this.empoloyeeID});
That's because Bootstrap by default sets the width of the legend
element to 100%. You can fix this by changing your legend.scheduler-border
to also use:
legend.scheduler-border {
width:inherit; /* Or auto */
padding:0 10px; /* To give a bit of padding on the left and right */
border-bottom:none;
}
You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.
You may also want to add margin-bottom:0;
to it as well to reduce the gap between the legend and the divider.
A better solution is to use &
"dev": "npm run start-watch & npm run wp-server"
Simplest form that worked for me.
import traceback
try:
print(4/0)
except ZeroDivisionError:
print(traceback.format_exc())
Output
Traceback (most recent call last):
File "/path/to/file.py", line 51, in <module>
print(4/0)
ZeroDivisionError: division by zero
Process finished with exit code 0
I'm having the same problem with Wampserver. It’s worked for me:
You must change this file: "C:\wamp\bin\mysql[mysql_version]\my.ini" For example: "C:\wamp\bin\mysql[mysql5.6.12]\my.ini"
And change default port 3306 to 80. (Lines 20 & 27, in both)
port = 3306 To port = 80
I hope this is helpful.
Use filter
, or if the number of dictionaries in exampleSet
is too high, use ifilter
of the itertools
module. It would return an iterator, instead of filling up your system's memory with the entire list at once:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
Container(
width: 48.0,
height: 48.0,
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.fill,
image: NetworkImage("path to your image")
)
)),
Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.
To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)
The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:
* ASP.NET * Advanced Windows Communication Foundation (WCF) functionality * .NET Framework Data Provider for Oracle * MSBuild for compiling
You can't, and you shouldn't.
Every other approach / alternative will only cause really bad user engagement.
That's my opinion.
you can use raiserror
. Read more details here
--from MSDN
BEGIN TRY
-- RAISERROR with severity 11-19 will cause execution to
-- jump to the CATCH block.
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
EDIT
If you are using SQL Server 2012+ you can use throw
clause. Here are the details.
I think, jogojapan gave an very good and exhaustive answer. You definitively should take a look at it before reading my post. However, I'd like to add the following:
unordered_map
separately, instead of using the equality comparison operator (operator==
). This might be helpful, for example, if you want to use the latter for comparing all members of two Node
objects to each other, but only some specific members as key of an unordered_map
.All in all, for your Node
class, the code could be written as follows:
using h = std::hash<int>;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);
Notes:
Here's an update as of Nov 2014. I find that setting method='curl'
did the trick for me (while method='auto'
, does not).
For example:
# does not work
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip')
# does not work. this appears to be the default anyway
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip', method='auto')
# works!
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip', method='curl')
No, you never call the base class destructor, it is always called automatically like others have pointed out but here is proof of concept with results:
class base {
public:
base() { cout << __FUNCTION__ << endl; }
~base() { cout << __FUNCTION__ << endl; }
};
class derived : public base {
public:
derived() { cout << __FUNCTION__ << endl; }
~derived() { cout << __FUNCTION__ << endl; } // adding call to base::~base() here results in double call to base destructor
};
int main()
{
cout << "case 1, declared as local variable on stack" << endl << endl;
{
derived d1;
}
cout << endl << endl;
cout << "case 2, created using new, assigned to derive class" << endl << endl;
derived * d2 = new derived;
delete d2;
cout << endl << endl;
cout << "case 3, created with new, assigned to base class" << endl << endl;
base * d3 = new derived;
delete d3;
cout << endl;
return 0;
}
The output is:
case 1, declared as local variable on stack
base::base
derived::derived
derived::~derived
base::~base
case 2, created using new, assigned to derive class
base::base
derived::derived
derived::~derived
base::~base
case 3, created with new, assigned to base class
base::base
derived::derived
base::~base
Press any key to continue . . .
If you set the base class destructor as virtual which one should, then case 3 results would be same as case 1 & 2.
The value
attribute on submit
-type <input>
elements controls the text displayed.
<input type="submit" class="like" value="Like" />
In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.
The ===
is not for checking string equalit , to do so you can use the Regxp functions for example
if (x.match(y) === null) {
// x and y are not equal
}
there is also the test
function
Solved by using "http://jcenter.bintray.com/" instead of "https://jcenter.bintray.com/".
repositories {
jcenter( { url "http://jcenter.bintray.com/" } )
}
Xcode 8.2.1 • Swift 3.0.2
Locale.availableIdentifiers
Locale.isoRegionCodes
Locale.isoCurrencyCodes
Locale.isoLanguageCodes
Locale.commonISOCurrencyCodes
Locale.current.regionCode // "US"
Locale.current.languageCode // "en"
Locale.current.currencyCode // "USD"
Locale.current.currencySymbol // "$"
Locale.current.groupingSeparator // ","
Locale.current.decimalSeparator // "."
Locale.current.usesMetricSystem // false
Locale.windowsLocaleCode(fromIdentifier: "pt_BR") // 1,046
Locale.identifier(fromWindowsLocaleCode: 1046) ?? "" // "pt_BR"
Locale.windowsLocaleCode(fromIdentifier: Locale.current.identifier) // 1,033 Note: I am in Brasil but I use "en_US" format with all my devices
Locale.windowsLocaleCode(fromIdentifier: "en_US") // 1,033
Locale.identifier(fromWindowsLocaleCode: 1033) ?? "" // "en_US"
Locale(identifier: "en_US_POSIX").localizedString(forLanguageCode: "pt") // "Portuguese"
Locale(identifier: "en_US_POSIX").localizedString(forRegionCode: "br") // "Brazil"
Locale(identifier: "en_US_POSIX").localizedString(forIdentifier: "pt_BR") // "Portuguese (Brazil)"
TimeZone.current.localizedName(for: .standard, locale: .current) ?? "" // "Brasilia Standard Time"
TimeZone.current.localizedName(for: .shortStandard, locale: .current) ?? "" // "GMT-3
TimeZone.current.localizedName(for: .daylightSaving, locale: .current) ?? "" // "Brasilia Summer Time"
TimeZone.current.localizedName(for: .shortDaylightSaving, locale: .current) ?? "" // "GMT-2"
TimeZone.current.localizedName(for: .generic, locale: .current) ?? "" // "Brasilia Time"
TimeZone.current.localizedName(for: .shortGeneric, locale: .current) ?? "" // "Sao Paulo Time"
var timeZone: String {
return TimeZone.current.localizedName(for: TimeZone.current.isDaylightSavingTime() ?
.daylightSaving :
.standard,
locale: .current) ?? "" }
timeZone // "Brasilia Summer Time"
In IIS 10, we use a similar solution to Drew's approach, i.e.:
using System;
using System.Web;
namespace Common.Web.Modules.Http
{
/// <summary>
/// Sets custom headers in all requests (e.g. "Server" header) or simply remove some.
/// </summary>
public class CustomHeaderModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}
public void Dispose() { }
/// <summary>
/// Event handler that implements the desired behavior for the PreSendRequestHeaders event,
/// that occurs just before ASP.NET sends HTTP headers to the client.
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OnPreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Set("Server", "MyServer");
}
}
}
And obviously add a reference to that dll in your project(s) and also the module in the config(s) you want:
<system.webServer>_x000D_
<modules>_x000D_
<!--Use http module to remove/customize IIS "Server" header-->_x000D_
<add name="CustomHeaderModule" type="Common.Web.Modules.Http.CustomHeaderModule" />_x000D_
</modules>_x000D_
</system.webServer>
_x000D_
IMPORTANT NOTE1: This solution needs an application pool set as integrated;
IMPORTANT NOTE2: All responses within the web app will be affected by this (css and js included);
You can validate group checkbox and radio button without extra js code, see below example.
Your JS should be look like:
$("#formid").validate();
You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]
<fieldset class="col-md-12">
<legend>Days</legend>
<div class="form-row">
<div class="col-12 col-md-12 form-group">
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="2">Tuesday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="3">Wednesday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="4">Thursday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="5">Friday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="6">Saturday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="7">Sunday
</label>
<label for="daysgroup[]" class="error">Your error message will be display here.</label>
</div>
</div>
</fieldset>
You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.
eg. group radio button:
<fieldset class="col-md-12">
<legend>Gender</legend>
<div class="form-row">
<div class="col-12 col-md-12 form-group">
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
</label>
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="w">woman
</label>
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="o">other
</label>
<label for="gendergroup[]" class="error">Your error message will be display here.</label>
</div>
</div>
</fieldset>
You can check working example here.
abs()
is for integers only. For floating point, use fabs()
(or one of the fabs()
line with the correct precision for whatever a actually is)
Maybe you can add a step to the generate-sources phase that moves the folder?
You can use Kotlin, the Super (cede of) Java for JVM, it has a nice way of interpolating strings like those of ES5, Ruby and Python.
class Client(val firstName: String, val lastName: String) {
val fullName = "$firstName $lastName"
}
Here's a simple way
for (i in 1:10) {
skip_to_next <- FALSE
# Note that print(b) fails since b doesn't exist
tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b)
with any code you want. You can also wrap many lines of code in {
and }
if you have more than one line of code inside the tryCatch
You simply select dates that are higher than the current time minus 1 day.
SELECT * FROM news WHERE date >= now() - INTERVAL 1 DAY;
Because a 32-bit floating-point number - such as 1.024 - is not 1.024. In a computer, 1.024 is an interval: from (1.024-e) to (1.024+e), where "e" represents an error. Some people fail to realize this and also believe that * in a*a stands for multiplication of arbitrary-precision numbers without there being any errors attached to those numbers. The reason why some people fail to realize this is perhaps the math computations they exercised in elementary schools: working only with ideal numbers without errors attached, and believing that it is OK to simply ignore "e" while performing multiplication. They do not see the "e" implicit in "float a=1.2", "a*a*a" and similar C codes.
Should majority of programmers recognize (and be able to execute on) the idea that C expression a*a*a*a*a*a is not actually working with ideal numbers, the GCC compiler would then be FREE to optimize "a*a*a*a*a*a" into say "t=(a*a); t*t*t" which requires a smaller number of multiplications. But unfortunately, the GCC compiler does not know whether the programmer writing the code thinks that "a" is a number with or without an error. And so GCC will only do what the source code looks like - because that is what GCC sees with its "naked eye".
... once you know what kind of programmer you are, you can use the "-ffast-math" switch to tell GCC that "Hey, GCC, I know what I am doing!". This will allow GCC to convert a*a*a*a*a*a into a different piece of text - it looks different from a*a*a*a*a*a - but still computes a number within the error interval of a*a*a*a*a*a. This is OK, since you already know you are working with intervals, not ideal numbers.
Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)
select state, count(*) from pg_stat_activity where pid <> pg_backend_pid() group by 1 order by 1;
I found this page when I was trying to set the backgroundImage
attribute of a div, but hadn't wrapped the backgroundImage
value with url()
. This worked fine:
for (var i=0; i<20; i++) {
// add a wrapper around an image element
var wrapper = document.createElement('div');
wrapper.className = 'image-cell';
// add the image element
var img = document.createElement('div');
img.className = 'image';
img.style.backgroundImage = 'url(http://via.placeholder.com/350x150)';
// add the image to its container; add both to the body
wrapper.appendChild(img);
document.body.appendChild(wrapper);
}
for single line comment add # at starting of a line
for multiple line comments add ' (single quote) from where you want to start & add ' (again single quote) at the point where you want to end the comment line.
uint8
, uint16
, uint32
, and uint64
are probably Microsoft-specific types.
As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>
: uint8_t
, uint16_t
, uint32_t
, and uint64_t
. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>
, at least as of Visual Studio 2010, but older code may use uint8
et al.
The predefined types char
, short
, int
et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char
is at least 8 bits, short
and int
are at least 16, long
is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int
is 16, 32, or 64 bits.
char
is almost always exactly 8 bits, but it's permitted to be wider. And plain char
may be either signed or unsigned.
uint8_t
is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char
, though it might be a typedef for plain char
if plain char
happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t
will not be defined at all.
Similarly, each uintN_t
type is an unsigned type that's exactly N bits wide.
In addition, <stdint.h>
defines corresponding signed intN_t
types, as well as int_fastN_t
and int_leastN_t
types that are at least the specified width.
The [u]intN_t
types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t
types are required to use a 2's-complement representation.
Although uint32_t
might be the same as unsigned int
, for example, you shouldn't assume that. Use unsigned int
when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t
when you need an unsigned integer type that's exactly 32 bits wide.
(And no, uint64
or uint64_t
is not the same as double
; double
is a floating-point type.)
According to the create table statement, the default charset of the table is already utf8mb4. It seems that you have a wrong connection charset.
In Java, set the datasource url like this: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8.
"?useUnicode=true&characterEncoding=utf-8" is necessary for using utf8mb4.
It works for my application.
Based on the answer: https://unix.stackexchange.com/a/111627
###############################################################################
# Summary: Returns the value of a variable given it's name as a string.
# Required Positional Argument:
# variable_name - The name of the variable to return the value of
# Returns: The value if variable exists; otherwise, empty string ("").
###############################################################################
get_value_of()
{
variable_name=$1
variable_value=""
if set | grep -q "^$variable_name="; then
eval variable_value="\$$variable_name"
fi
echo "$variable_value"
}
test=123
get_value_of test
# 123
test="\$(echo \"something nasty\")"
get_value_of test
# $(echo "something nasty")
You don't need to use linq since List<T>
provides the methods to do this:
int index = lst.FindLastIndex(c => c.Number == textBox6.Text);
if(index != -1)
{
lst[index] = new Class1() { ... };
}
Have you considered simply using System.Drawing namespace? For example:
System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue);
float hue = color.GetHue();
float saturation = color.GetSaturation();
float lightness = color.GetBrightness();
Note that it's not exactly what you've asked for (see differences between HSL and HSV and the Color class does not have a conversion back from HSL/HSV but the latter is reasonably easy to add.
navigate to the url http://jmeter.apache.org/download_jmeter.cgi-->download apache-jmeter-2.11.zip, which is under binaries.
this error is occurring since Apache jmeter.jar is missing in bin folder
StringUtils.isBlank()
checks that each character of the string is a whitespace character (or that the string is empty or that it's null). This is totally different than just checking if the string is empty.
From the linked documentation:
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true StringUtils.isBlank("") = true StringUtils.isBlank(" ") = true StringUtils.isBlank("bob") = false StringUtils.isBlank(" bob ") = false
For comparison StringUtils.isEmpty:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
Warning: In java.lang.String.isBlank() and java.lang.String.isEmpty() work the same except they don't return true
for null
.
java.lang.String.isBlank()
(since Java 11)
If you are using latest versions of Angular (2/5/6) :
In your component.ts
//x.component.ts
prefs = false;
hidePrefs(){
this.prefs = true;
}
Ajax call error handler will be triggered if the call itself fails.
You are probably trying to get the error from server in case login credentials do not go through. In that case, you need to inspect the server response json object and display appropriate message.
e.preventDefault();
$.ajax(
{
type: 'POST',
url: requestURI,
data: $(formLogin).serialize(),
dataType: 'json',
success: function(result){
if(result.hasError == true)
{
if(result.error_code == 'AUTH_FAILURE')
{
//wrong password
console.log('Recieved authentication error');
$('#login_errors_auth').fadeIn();
}
else
{
//generic error here
$('#login_errors_unknown').fadeIn();
}
}
}
});
Here, "result" is the json object returned form the server which could have a structure like:
$return = array(
'hasError' => !$validPassword,
'error_code' => 'AUTH_FAILURE'
);
die(jsonEncode($return));
I recommend parsecsv-for-php to get around a number any issues with nested newlines and quotes.
df[df['ids'].str.contains('ball', na = False)] # valid for (at least) pandas version 0.17.1
Step-by-step explanation (from inner to outer):
df['ids']
selects the ids
column of the data frame (technically, the object df['ids']
is of type pandas.Series
)df['ids'].str
allows us to apply vectorized string methods (e.g., lower
, contains
) to the Seriesdf['ids'].str.contains('ball')
checks each element of the Series as to whether the element value has the string 'ball' as a substring. The result is a Series of Booleans indicating True
or False
about the existence of a 'ball' substring.df[df['ids'].str.contains('ball')]
applies the Boolean 'mask' to the dataframe and returns a view containing appropriate records.na = False
removes NA / NaN values from consideration; otherwise a ValueError may be returned.Try:
<c:if test = "${ansokanInfo.PSystem == 'NAT'}">
JSP/Servlet 2.4 (I think that's the version number) doesn't support method calls in EL and only support properties. The latest servlet containers do support method calls (ie Tomcat 7).
You'll have to set it to zero. Zero means the script can run forever. Add the following at the start of your script:
ini_set('max_execution_time', 0);
Refer to the PHP documentation of max_execution_time
Note that:
set_time_limit(0);
will have the same effect.
I think maven is not installed properly. check with mvn --v
or
Please check maven home path in env variables or you have created this project before the installation of maven
run from CMD & %path%=set to mysql/bin
mysql_upgrade -u user -ppassword
While Raviteja Vutukuri's answer works and is quick to put together, it's not particularly flexible for varying the filters and doesn't help too much if you're looking to do something programmatically. So I put together my own query:
SELECT
PRIVILEGE,
OBJ_OWNER,
OBJ_NAME,
USERNAME,
LISTAGG(GRANT_TARGET, ',') WITHIN GROUP (ORDER BY GRANT_TARGET) AS GRANT_SOURCES, -- Lists the sources of the permission
MAX(ADMIN_OR_GRANT_OPT) AS ADMIN_OR_GRANT_OPT, -- MAX acts as a Boolean OR by picking 'YES' over 'NO'
MAX(HIERARCHY_OPT) AS HIERARCHY_OPT -- MAX acts as a Boolean OR by picking 'YES' over 'NO'
FROM (
-- Gets all roles a user has, even inherited ones
WITH ALL_ROLES_FOR_USER AS (
SELECT DISTINCT CONNECT_BY_ROOT GRANTEE AS GRANTED_USER, GRANTED_ROLE
FROM DBA_ROLE_PRIVS
CONNECT BY GRANTEE = PRIOR GRANTED_ROLE
)
SELECT
PRIVILEGE,
OBJ_OWNER,
OBJ_NAME,
USERNAME,
REPLACE(GRANT_TARGET, USERNAME, 'Direct to user') AS GRANT_TARGET,
ADMIN_OR_GRANT_OPT,
HIERARCHY_OPT
FROM (
-- System privileges granted directly to users
SELECT PRIVILEGE, NULL AS OBJ_OWNER, NULL AS OBJ_NAME, GRANTEE AS USERNAME, GRANTEE AS GRANT_TARGET, ADMIN_OPTION AS ADMIN_OR_GRANT_OPT, NULL AS HIERARCHY_OPT
FROM DBA_SYS_PRIVS
WHERE GRANTEE IN (SELECT USERNAME FROM DBA_USERS)
UNION ALL
-- System privileges granted users through roles
SELECT PRIVILEGE, NULL AS OBJ_OWNER, NULL AS OBJ_NAME, ALL_ROLES_FOR_USER.GRANTED_USER AS USERNAME, GRANTEE AS GRANT_TARGET, ADMIN_OPTION AS ADMIN_OR_GRANT_OPT, NULL AS HIERARCHY_OPT
FROM DBA_SYS_PRIVS
JOIN ALL_ROLES_FOR_USER ON ALL_ROLES_FOR_USER.GRANTED_ROLE = DBA_SYS_PRIVS.GRANTEE
UNION ALL
-- Object privileges granted directly to users
SELECT PRIVILEGE, OWNER AS OBJ_OWNER, TABLE_NAME AS OBJ_NAME, GRANTEE AS USERNAME, GRANTEE AS GRANT_TARGET, GRANTABLE, HIERARCHY
FROM DBA_TAB_PRIVS
WHERE GRANTEE IN (SELECT USERNAME FROM DBA_USERS)
UNION ALL
-- Object privileges granted users through roles
SELECT PRIVILEGE, OWNER AS OBJ_OWNER, TABLE_NAME AS OBJ_NAME, GRANTEE AS USERNAME, ALL_ROLES_FOR_USER.GRANTED_ROLE AS GRANT_TARGET, GRANTABLE, HIERARCHY
FROM DBA_TAB_PRIVS
JOIN ALL_ROLES_FOR_USER ON ALL_ROLES_FOR_USER.GRANTED_ROLE = DBA_TAB_PRIVS.GRANTEE
) ALL_USER_PRIVS
-- Adjust your filter here
WHERE USERNAME = 'USER_NAME'
) DISTINCT_USER_PRIVS
GROUP BY
PRIVILEGE,
OBJ_OWNER,
OBJ_NAME,
USERNAME
;
Advantages:
WHERE
clause.DBMS_OUTPUT
or something (compared to Pete Finnigan's linked script). This makes it useful for programmatic use and for exporting.GRANT
.Then the problem came back. I uninstalled both Microsoft.CodeDom.Providers.DotNetCompilerPlatform
and
Uninstall-package Microsoft.Net.Compilers
but no help. Then installed - no help. Cleaned project and built no help. Restarted server no help.Then I noticed the project needed not the latest one which is currently 1.0.5 but 1.0.3 as that was the error could not load the 1.0.3 version. So I installed that dll version instead and now it works.
The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!
Two notes from experience which might be helpful:
You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.
If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.
In addition to @fyrye's very helpful answer this is an okayish workaround for the mentioned bug (this one), that DatePeriod substracts one hour when entering summertime, but doesn't add one hour when leaving summertime (and thus Europe/Berlin's March has its correct 743 hours but October has 744 instead of 745 hours):
function getMonthHours(string $year, string $month, \DateTimeZone $timezone): int
{
// or whatever start and end \DateTimeInterface objects you like
$start = new \DateTimeImmutable($year . '-' . $month . '-01 00:00:00', $timezone);
$end = new \DateTimeImmutable((new \DateTimeImmutable($year . '-' . $month . '-01 23:59:59', $timezone))->format('Y-m-t H:i:s'), $timezone);
// count the hours just utilizing \DatePeriod, \DateInterval and iterator_count, hell yeah!
$hours = iterator_count(new \DatePeriod($start, new \DateInterval('PT1H'), $end));
// find transitions and check, if there is one that leads to a positive offset
// that isn't added by \DatePeriod
// this is the workaround for https://bugs.php.net/bug.php?id=75685
$transitions = $timezone->getTransitions((int)$start->format('U'), (int)$end->format('U'));
if (2 === count($transitions) && $transitions[0]['offset'] - $transitions[1]['offset'] > 0) {
$hours += (round(($transitions[0]['offset'] - $transitions[1]['offset'])/3600));
}
return $hours;
}
$myTimezoneWithDST = new \DateTimeZone('Europe/Berlin');
var_dump(getMonthHours('2020', '01', $myTimezoneWithDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithDST)); // 743
var_dump(getMonthHours('2020', '10', $myTimezoneWithDST)); // 745, finally!
$myTimezoneWithoutDST = new \DateTimeZone('UTC');
var_dump(getMonthHours('2020', '01', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '10', $myTimezoneWithoutDST)); // 744
P.S. If you check a (longer) timespan, which leads to more than those two transitions, my workaround won't touch the counted hours to reduce the potential of funny side effects. In such cases, a more complicated solution must be implemented. One could iterate over all found transitions and compare the current with the last and check if it is one with DST true->false.
You can use the createRef to change the state of the child component from the parent component. Here are all the steps.
Create a method to change the state in the child component.
2 - Create a reference for the child component in parent component using React.createRef().
3 - Attach reference with the child component using ref={}.
4 - Call the child component method using this.yor-reference.current.method.
Parent component
class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
render() {
return (
<div>
<button onClick={this.changeChild.current.toggleMenu()}>
Toggle Menu from Parent
</button>
<ChildComponent ref={this.changeChild} />
</div>
);
}
}
Child Component
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
open: false;
}
}
toggleMenu=() => {
this.setState({
open: !this.state.open
});
}
render() {
return (
<Drawer open={this.state.open}/>
);
}
}
See I did what I thought was the obvious thing was:
string filePath = ConfigurationManager.AppSettings.GetValues("ClientsFilePath").ToString();
While that compiles it always returns null.
This however (from above) works:
string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];
The docs give a fair indicator of what's required., however requests
allow us to skip a few steps:
You only need to install the security
package extras (thanks @admdrew for pointing it out)
$ pip install requests[security]
or, install them directly:
$ pip install pyopenssl ndg-httpsclient pyasn1
Requests will then automatically inject pyopenssl
into urllib3
If you're on ubuntu, you may run into trouble installing pyopenssl
, you'll need these dependencies:
$ apt-get install libffi-dev libssl-dev
There is a better answer to this problem, though I could just break this down step-by-step.
You will need to fetch and checkout the latest upstream changes like so, e.g.:
git fetch upstream
git checkout upstream/master -b revert/john/foo_and_bar
Taking a look at the commit log, you should find something similar to this:
commit b76a5f1f5d3b323679e466a1a1d5f93c8828b269 Merge: 9271e6e a507888 Author: Tim Tom <[email protected]> Date: Mon Apr 29 06:12:38 2013 -0700 Merge pull request #123 from john/foo_and_bar Add foo and bar commit a507888e9fcc9e08b658c0b25414d1aeb1eef45e Author: John Doe <[email protected]> Date: Mon Apr 29 12:13:29 2013 +0000 Add bar commit 470ee0f407198057d5cb1d6427bb8371eab6157e Author: John Doe <[email protected]> Date: Mon Apr 29 10:29:10 2013 +0000 Add foo
Now you want to revert the entire pull request with the ability to unrevert later. To do so, you will need to take the ID of the merge commit.
In the above example the merge commit is the top one where it says "Merged pull request #123...".
Do this to revert the both changes ("Add bar" and "Add foo") and you will end up with in one commit reverting the entire pull request which you can unrevert later on and keep the history of changes clean:
git revert -m 1 b76a5f1f5d3b323679e466a1a1d5f93c8828b269
As rebenvp said I used:
g++ *.cpp -o output
And then do this for output:
./output
But a better solution is to use make
file. Read here to know more about make
files.
Also make sure that you have added the required .h
files in the .cpp
files.
@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Not really sure what you mean by no "function"
Obviously, change ECHO
to SET
to set the variables rather thon ECHOing them...
See for
documentation for a full list.
ceztko's test case (for reference)
@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Comment : please see comments.
Are there best practices with regards to the organisation of packages in Java and what goes in them?
Not really no. There are lots of ideas, and lots opinions, but real "best practice" is to use your common sense!
(Please read No best Practices for a perspective on "best practices" and the people who promote them.)
However, there is one principal that probably has broad acceptance. Your package structure should reflect your application's (informal) module structure, and you should aim to minimize (or ideally entirely avoid) any cyclic dependencies between modules.
(Cyclic dependencies between classes in a package / module are just fine, but inter-package cycles tend to make it hard understand your application's architecture, and can be a barrier to code reuse. In particular, if you use Maven you will find that cyclic inter-package / inter-module dependencies mean that the whole interconnected mess has to be one Maven artifact.)
I should also add that there is one widely accepted best practice for package names. And that is that your package names should start with your organization's domain name in reverse order. If you follow this rule, you reduce the likelihood of problems caused by your (full) class names clashing with other peoples'.
var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();
Write table names you want, and initialize the select to get the result of fields.
Expanding on Mark's suggestions...
Method 3
Implement "deep" change detection on the model. The advantages primarily involve the avoidance of incorporating user interface aspects into the component; this also catches programmatic changes made to the model. That said, it would require extra work to implement such things as debouncing as suggested by Thierry, and this will also catch your own programmatic changes, so use with caution.
export class App implements DoCheck {
person = { first: "Sally", last: "Jones" };
oldPerson = { ...this.person }; // ES6 shallow clone. Use lodash or something for deep cloning
ngDoCheck() {
// Simple shallow property comparison - use fancy recursive deep comparison for more complex needs
for (let prop in this.person) {
if (this.oldPerson[prop] !== this.person[prop]) {
console.log(`person.${prop} changed: ${this.person[prop]}`);
this.oldPerson[prop] = this.person[prop];
}
}
}
With the parentheses:
setTimeout("alertMsg()", 3000); // It work, here it treat as a function
Without the quotes and the parentheses:
setTimeout(alertMsg, 3000); // It also work, here it treat as a function
And the third is only using quotes:
setTimeout("alertMsg", 3000); // It not work, here it treat as a string
function alertMsg1() {_x000D_
alert("message 1");_x000D_
}_x000D_
function alertMsg2() {_x000D_
alert("message 2");_x000D_
}_x000D_
function alertMsg3() {_x000D_
alert("message 3");_x000D_
}_x000D_
function alertMsg4() {_x000D_
alert("message 4");_x000D_
}_x000D_
_x000D_
// this work after 2 second_x000D_
setTimeout(alertMsg1, 2000);_x000D_
_x000D_
// This work immediately_x000D_
setTimeout(alertMsg2(), 4000);_x000D_
_x000D_
// this fail_x000D_
setTimeout('alertMsg3', 6000);_x000D_
_x000D_
// this work after 8second_x000D_
setTimeout('alertMsg4()', 8000);
_x000D_
In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.
I've found what I think is an easier way. If you put an Iframe in the page, you can redirect the exit of the action there and make it show up. You can do nothing, of course. In that case, you can set the iframe display to none.
<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
<input type="submit" value="Skicka Tips">
<input type="hidden" name="ad_id" value="2">
</form>
var value_input = $("input[name*='xxxx']").val();
Just wanted to add an answer here, since Koltin has some convenience methods to do this, which are a lot less ugly than adding and removing a onGlobalLayoutListener
:
view.doOnLayout {
it.measuredWidth
it.measuredHeight
}
You can see more of the convinience methods here.
URL url = Test.class.getResource(args[0]); // reading demo file path from
// same location where class
File input=null;
try {
input = new File(url.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This may be helpful
def digits_to_number(digits):
return reduce(lambda x,y : x+y, map(str,digits))
print digits_to_number([1,2,3,4,5])
The OP's questions about canonical form and how it can improve performance of the equals
method can both be answered by extending the example provided in Effective Java.
Consider the following class:
public final class CaseInsensitiveString {
private final String s;
public CaseInsensitiveString(String s) {
this.s = Objects.requireNonNull(s);
}
@Override
public boolean equals(Object o) {
return o instanceof CaseInsensitiveString && ((CaseInsensitiveString) o).s.equalsIgnoreCase(s);
}
}
The equals
method in this example has added cost by using String
's equalsIgnoreCase
method. As mentioned in the text
you may want to store a canonical form of the field so the equals method can do a cheap exact comparison on canonical forms rather than a more costly nonstandard comparison.
What does Joshua Bloch mean when he says canonical form? Well, I think Dónal's concise answer is very appropriate. We can store the underlying String
field in the CaseInsensitiveString
example in a standard way, perhaps the uppercase form of the String
. Now, you can reference this canonical form of the CaseInsensitiveString
, its uppercase variant, and perform cheap evaluations in your equals
and hashcode
methods.
Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:
$('.collapse').on('show.bs.collapse', function () {
$('.collapse.in').collapse('hide');
});
I modified his example to do this here: http://jsfiddle.net/QLfMU/116/
Here's a nice article that shows many ways of hiding files from search engines:
JavaScript isn't a good way not to index a page; it won't prevent users from linking directly to your files (and thus revealing it to crawlers), and as Rob mentioned, wouldn't work for all users.
An easy fix is to add the rel="nofollow"
attribute, though again, it's not complete without robots.txt.
<a href="uploads/file.doc" rel="nofollow">Download Here</a>
This post helped me: http://code.google.com/p/android/issues/detail?id=8431
I do the following in Mint 15 through 17, also works on ubuntu server 12.04 and above:
sudo vi /etc/bash.bashrc
scroll to the bottom, and add:
export LD_LIBRARY_PATH=.
All users have the environment variable added.
DON'T DO THIS IN PRODUCTION
The answer given by @ravi-luthra technically works but it has some issues!
In my case, I was just trying to recover disk space. The lib/docker/overlay
folder was taking 30GB of space and I only run a few containers regularly. Looks like docker has some issue with data leakage and some of the temporary data are not cleared when the container stops.
So I went ahead and deleted all the contents of lib/docker/overlay
folder. After that, My docker instance became un-useable. When I tried to run or build any container, It gave me this error:
failed to create rwlayer: symlink ../04578d9f8e428b693174c6eb9a80111c907724cc22129761ce14a4c8cb4f1d7c/diff /var/lib/docker/overlay2/l/C3F33OLORAASNIYB3ZDATH2HJ7: no such file or directory
Then with some trial and error, I solved this issue by running
(WARNING: This will delete all your data inside docker volumes)
docker system prune --volumes -a
So It is not recommended to do such dirty clean ups unless you completely understand how the system works.
$(document).on('keypress','#typeyourid',function(e){
if($(e.target).prop('value').length>=10){
if(e.keyCode!=32)
{return false}
}})
Advantage is this works with type="number"
Object.create(Constructor.prototype)
is the part of new Constructor
new Constructor
implementation// 1. define constructor function
function myConstructor(name, age) {
this.name = name;
this.age = age;
}
myConstructor.prototype.greet = function(){
console.log(this.name, this.age)
};
// 2. new operator implementation
let newOperatorWithConstructor = function(name, age) {
const newInstance = new Object(); // empty object
Object.setPrototypeOf(newInstance, myConstructor.prototype); // set prototype
const bindedConstructor = myConstructor.bind(newInstance); // this binding
bindedConstructor(name, age); // execute binded constructor function
return newInstance; // return instance
};
// 3. produce new instance
const instance = new myConstructor("jun", 28);
const instance2 = newOperatorWithConstructor("jun", 28);
console.log(instance);
console.log(instance2);
new Constructor
implementation contains Object.create
method newOperatorWithConstructor = function(name, age) {
const newInstance = Object.create(myConstructor.prototype); // empty object, prototype chaining
const bindedConstructor = myConstructor.bind(newInstance); // this binding
bindedConstructor(name, age); // execute binded constructor function
return newInstance; // return instance
};
console.log(newOperatorWithConstructor("jun", 28));
I would suggest you try this jQuery plugin print element
It can let you just print the element you selected.
for a in someList:
list.append(splitColon.split(a))
You can rewrite the above as:
newlist = [splitColon.split(a) for a in someList]
document.getElementById('newSkill').options[document.getElementById('newSkill').selectedIndex].value
Should work
Below can be 2 reasons for this issue:
Backup taken on SQL 2012 and Restore Headeronly was done in SQL 2008 R2
Backup media is corrupted.
If we run below command, we can find actual error always:
restore headeronly
from disk = 'C:\Users\Public\Database.bak'
Give complete location of your database file in the quot
Hope it helps
Found the port esp32 was connected to by -
ls /dev/*
You would get a long list and you can find the port you need
This can also happen if you have a solution containing the project open in Visual Studio, then use your source control software to change to an older commit that does not contain that project. Normally, this would be obvious as all the project files would disappear as well. But, if it's a new project with very few or no files at all, it could be puzzling to see that just this one file, AssemblyInfo.cs
, is missing. And, it's more likely you'd be messing about with an AssemblyInfo.cs
when a project is new, so might miss that another file or two is also missing.
The cure is to do any of the following:
AssemblyInfo.cs
and any other missing files from another commit, taking care to manage and save your .csproj
file so the referenced files don't vanish from the project—perhaps by adding and removing a random .cs
file to cause changes to need to be saved (since visual studio thinks the .csproj file has been saved when it hasn't).AssemblyInfo.cs
file manually. Just copy another project, and change the details, especially the GUID so it matches the one from the .sln
file.The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %
, like this:
@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF
I was using salesforce apex classes with Eclipse Neon 3.3 for Java.
I found an option "define folding region" on right click in the editor, I selected the block of code i wanted to collapse and selected this property for that code. Now I am seeing + and - symbol to expand and collapse that block of code
You can use this :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from sysobjects where type='u'";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
"<password>");
}
}
I found an article about how to move svn repositories from a hosting service to another, and how to do local backups:
Define where you will store your repositories:
mkdir ~/repo
MYREPO=/home/me/someplace ## you should use full path here
svnadmin create $MYREPO
Create a hook file and make it executable:
echo '#!/bin/sh' > $MYREPO/hooks/pre-revprop-change
chmod +x $MYREPO/hooks/pre-revprop-change
Now we can start importing the repository with svnsync
, that will initialize a destination repository for synchronization from another repository:
svnsync init file://$MYREPO http://your.svn.repo.here/
And the finishing touch to transfer all pending revisions to the destination from the source with which it was initialized:
svnsync sync file://$MYREPO
There now you have a local svn repository in the ~/repo
directory.
Source:
Here are two methods:
<script type="text/javascript">
var s="http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu
=true&pcode=1235";
var st=s.substring(0, s.indexOf("?"));
alert(st);
alert(s.replace(/\?.*/,''));
</script>
In case if someone returns with the same question for Android platform, you cannot use the inbuilt remove()
method if you are targeting for Android API-18 or less. The remove()
method is added on API level 19. Thus, the best possible thing to do is to extend the JSONArray
to create a compatible override for the remove()
method.
public class MJSONArray extends JSONArray {
@Override
public Object remove(int index) {
JSONArray output = new JSONArray();
int len = this.length();
for (int i = 0; i < len; i++) {
if (i != index) {
try {
output.put(this.get(i));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
return output;
//return this; If you need the input array in case of a failed attempt to remove an item.
}
}
EDIT As Daniel pointed out, handling an error silently is bad style. Code improved.
Yes, add the -Force
parameter.
copy-item $from $to -Recurse -Force
I think it would be easier using this CLR Stored procedure SQL-APIConsumer:
exec [dbo].[APICaller_POST]
@URL = 'http://localhost:5000/api/auth/login'
,@BodyJson = '{"Username":"gdiaz","Password":"password"}'
It has multiple procedures that allows you calling API that required a parameters and even passing multiples headers and tokens authentications.
Python String rindex() Method
Description
Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].
Syntax
Following is the syntax for rindex() method -
str.rindex(str, beg=0 end=len(string))
Parameters
str - This specifies the string to be searched.
beg - This is the starting index, by default its 0
len - This is ending index, by default its equal to the length of the string.
Return Value
This method returns last index if found otherwise raises an exception if str is not found.
Example
The following example shows the usage of rindex() method.
Live Demo
str1 = "this is string example....wow!!!";
str2 = "is";
print str1.rindex(str2)
print str1.index(str2)
When we run above program, it produces following result -
5
2
numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)
This would work, if your are trying to Sum up a list.
Use this for example:
cv2.namedWindow('finalImg', cv2.WINDOW_NORMAL)
cv2.imshow("finalImg",finalImg)
Here's just an outline of the idea:
In a BST, the left subtree of node T
contains only elements smaller than the value stored in T
. If k
is smaller than the number of elements in the left subtree, the k
th smallest element must belong to the left subtree. Otherwise, if k
is larger, then the k
th smallest element is in the right subtree.
We can augment the BST to have each node in it store the number of elements in its left subtree (assume that the left subtree of a given node includes that node). With this piece of information, it is simple to traverse the tree by repeatedly asking for the number of elements in the left subtree, to decide whether to do recurse into the left or right subtree.
Now, suppose we are at node T:
T
.k
th smallest. So, we reduce the problem to finding the k - num_elements(left subtree of T)
smallest element of the right subtree. k
th smallest is somewhere in the left subtree, so we reduce the problem to finding the k
th smallest element in the left subtree.Complexity analysis:
This takes O(depth of node)
time, which is O(log n)
in the worst case on a balanced BST, or O(log n)
on average for a random BST.
A BST requires O(n)
storage, and it takes another O(n)
to store the information about the number of elements. All BST operations take O(depth of node)
time, and it takes O(depth of node)
extra time to maintain the "number of elements" information for insertion, deletion or rotation of nodes. Therefore, storing information about the number of elements in the left subtree keeps the space and time complexity of a BST.
Actually openssl
command is a better tool than curl
for checking and debugging SSL. Here is an example with openssl
:
openssl s_client -showcerts -connect stackoverflow.com:443 < /dev/null
and < /dev/null
is for adding EOL to the STDIN
otherwise it hangs on the Terminal.
But if you liked, you can wrap some useful openssl
commands with curl
(as I did with curly) and make it more human readable like so:
# check if SSL is valid
>>> curly --ssl valid -d stackoverflow.com
Verify return code: 0 (ok)
issuer=C = US
O = Let's Encrypt
CN = R3
subject=CN = *.stackexchange.com
option: ssl
action: valid
status: OK
# check how many days it will be valid
>>> curly --ssl date -d stackoverflow.com
Verify return code: 0 (ok)
from: Tue Feb 9 16:13:16 UTC 2021
till: Mon May 10 16:13:16 UTC 2021
days total: 89
days passed: 8
days left: 81
option: ssl
action: date
status: OK
# check which names it supports
curly --ssl name -d stackoverflow.com
*.askubuntu.com
*.blogoverflow.com
*.mathoverflow.net
*.meta.stackexchange.com
*.meta.stackoverflow.com
*.serverfault.com
*.sstatic.net
*.stackexchange.com
*.stackoverflow.com
*.stackoverflow.email
*.superuser.com
askubuntu.com
blogoverflow.com
mathoverflow.net
openid.stackauth.com
serverfault.com
sstatic.net
stackapps.com
stackauth.com
stackexchange.com
stackoverflow.blog
stackoverflow.com
stackoverflow.email
stacksnippets.net
superuser.com
option: ssl
action: name
status: OK
# check the CERT of the SSL
>>> curly --ssl cert -d stackoverflow.com
-----BEGIN CERTIFICATE-----
MIIG9DCCBdygAwIBAgISBOh5mcfyJFrMPr3vuAuikAYwMA0GCSqGSIb3DQEBCwUA
MDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD
EwJSMzAeFw0yMTAyMDkxNjEzMTZaFw0yMTA1MTAxNjEzMTZaMB4xHDAaBgNVBAMM
Eyouc3RhY2tleGNoYW5nZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQDRDObYpjCvb2smnCP+UUpkKdSr6nVsIN8vkI6YlJfC4xC72bY2v38lE2xB
LCaL9MzKhsINrQZRIUivnEHuDOZyJ3Xwmxq3wY0qUKo2c963U7ZJpsIFsj37L1Ac
Qp4pubyyKPxTeFAzKbpfwhNml633Ao78Cy/l/sYjNFhMPoBN4LYBX7/WJNIfc3UZ
niMfh230NE2dwoXGqA0MnkPQyFKlIwHcmMb+ZI5T8TziYq0WQiYUY3ssOEu1CI5n
wh0+BTAwpx7XBUe5Z+B9SrFp8BUDYWcWuVEIh2btYvo763mrr+lmm8PP23XKkE4f
287Iwlfg/IqxxIxKv9smFoPkyZcFAgMBAAGjggQWMIIEEjAOBgNVHQ8BAf8EBAMC
BaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAw
HQYDVR0OBBYEFMnjX41T+J1bbLgG9TjR/4CvHLv/MB8GA1UdIwQYMBaAFBQusxe3
WFbLrlAJQOYfr52LFMLGMFUGCCsGAQUFBwEBBEkwRzAhBggrBgEFBQcwAYYVaHR0
cDovL3IzLm8ubGVuY3Iub3JnMCIGCCsGAQUFBzAChhZodHRwOi8vcjMuaS5sZW5j
ci5vcmcvMIIB5AYDVR0RBIIB2zCCAdeCDyouYXNrdWJ1bnR1LmNvbYISKi5ibG9n
b3ZlcmZsb3cuY29tghIqLm1hdGhvdmVyZmxvdy5uZXSCGCoubWV0YS5zdGFja2V4
Y2hhbmdlLmNvbYIYKi5tZXRhLnN0YWNrb3ZlcmZsb3cuY29tghEqLnNlcnZlcmZh
dWx0LmNvbYINKi5zc3RhdGljLm5ldIITKi5zdGFja2V4Y2hhbmdlLmNvbYITKi5z
dGFja292ZXJmbG93LmNvbYIVKi5zdGFja292ZXJmbG93LmVtYWlsgg8qLnN1cGVy
dXNlci5jb22CDWFza3VidW50dS5jb22CEGJsb2dvdmVyZmxvdy5jb22CEG1hdGhv
dmVyZmxvdy5uZXSCFG9wZW5pZC5zdGFja2F1dGguY29tgg9zZXJ2ZXJmYXVsdC5j
b22CC3NzdGF0aWMubmV0gg1zdGFja2FwcHMuY29tgg1zdGFja2F1dGguY29tghFz
dGFja2V4Y2hhbmdlLmNvbYISc3RhY2tvdmVyZmxvdy5ibG9nghFzdGFja292ZXJm
bG93LmNvbYITc3RhY2tvdmVyZmxvdy5lbWFpbIIRc3RhY2tzbmlwcGV0cy5uZXSC
DXN1cGVydXNlci5jb20wTAYDVR0gBEUwQzAIBgZngQwBAgEwNwYLKwYBBAGC3xMB
AQEwKDAmBggrBgEFBQcCARYaaHR0cDovL2Nwcy5sZXRzZW5jcnlwdC5vcmcwggEE
BgorBgEEAdZ5AgQCBIH1BIHyAPAAdgBElGUusO7Or8RAB9io/ijA2uaCvtjLMbU/
0zOWtbaBqAAAAXeHyHI8AAAEAwBHMEUCIQDnzDcCrmCPdfgcb/ojY0WJV1rCj+uE
hCiQi0+4fBP9lgIgSI5mwEqBmVcQwRfKikUzhkH0w6K/6wq0e/1zJA0j5a4AdgD2
XJQv0XcwIhRUGAgwlFaO400TGTO/3wwvIAvMTvFk4wAAAXeHyHIoAAAEAwBHMEUC
IHd0ZLB3j0b31Sh/D3RIfF8C31NxIRSG6m/BFSCGlxSWAiEAvYlgPjrPcBZpX4Xm
SdkF39KbVicTGnFOSAqDpRB3IJwwDQYJKoZIhvcNAQELBQADggEBABZ+2WXyP4w/
A+jJtBgKTZQsA5VhUCabAFDEZdnlWWcV3WYrz4iuJjp5v6kL4MNzAvAVzyCTqD1T
m7EUn/usz59m02mZF82+ELLW6Mqix8krYZTpYt7Hu3Znf6HxiK3QrjEIVlwSGkjV
XMCzOHdALreTkB+UJaL6bEs1sB+9h20zSnZAKrPokGL/XwgxUclXIQXr1uDAShJB
Ts0yjoSY9D687W9sjhq+BIjNYIWg1n9NJ7HM48FWBCDmV3NlCR0Zh1Yx15pXCUhb
UqWd6RzoSLmIfdOxgfi9uRSUe0QTZ9o/Fs4YoMi5K50tfRycLKW+BoYDgde37As5
0pCUFwVVH2E=
-----END CERTIFICATE-----
option: ssl
action: cert
status: OK
I had the same issue on OSX Mavericks, it turned out that Sophos anti-virus was blocking certain requests, once I uninstalled it the issue went away.
If you think that it might be caused by an extension one easy way to try and test this is to open chrome with the '--disable-extensions
flag to see if it fixes the problem. If that doesn't fix it consider looking beyond the browser to see if any other application might be causing the problem, specifically security apps which can affect requests.
Yes, a table have one or many foreign keys and each foreign keys hava a different parent table.
Hibernate, because it:
A few points on why (and when) to use ORM:
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
Here is an example why duck typing is evil without knowing when it is dangerous. For instance: Here is the Python code (possibly omitting proper indenting), note that this situation is avoidable by taking care of isinstance and issubclassof functions to make sure that when you really need a duck, you don't get a bomb.
class Bomb:
def __init__(self):
""
def talk(self):
self.explode()
def explode(self):
print "BOOM!, The bomb explodes."
class Duck:
def __init__(self):
""
def talk(self):
print "I am a duck, I will not blow up if you ask me to talk."
class Kid:
kids_duck = None
def __init__(self):
print "Kid comes around a corner and asks you for money so he could buy a duck."
def takeDuck(self, duck):
self.kids_duck = duck
print "The kid accepts the duck, and happily skips along"
def doYourThing(self):
print "The kid tries to get the duck to talk"
self.kids_duck.talk()
myKid = Kid()
myBomb = Bomb()
myKid.takeDuck(myBomb)
myKid.doYourThing()
I think what you are looking for is iter_swap
which you can find also in <algorithm>
.
all you need to do is just pass two iterators each pointing at one of the elements you want to exchange.
since you have the position of the two elements, you can do something like this:
// assuming your vector is called v
iter_swap(v.begin() + position, v.begin() + next_position);
// position, next_position are the indices of the elements you want to swap
Here is complete demo code to understand client side and server side process. you can copy paste it and just replace google site key and google secret key.
<?php
if(!empty($_REQUEST))
{
// echo '<pre>'; print_r($_REQUEST); die('END');
$post = [
'secret' => 'Your Secret key',
'response' => $_REQUEST['g-recaptcha-response'],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
echo '<pre>'; print_r($server_output); die('ss');
}
?>
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var site_key = 'Your Site key';
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : site_key,
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : site_key
});
grecaptcha.render('example3', {
'sitekey' : site_key,
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- The g-recaptcha-response string displays in an alert message upon submit. -->
<form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
<div id="example1"></div>
<br>
<input type="submit" value="getResponse">
</form>
<br>
<!-- Resets reCAPTCHA widgetId2 upon submit. -->
<form action="javascript:grecaptcha.reset(widgetId2);">
<div id="example2"></div>
<br>
<input type="submit" value="reset">
</form>
<br>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
order
from base
arrange
from dplyr
setorder
and setorderv
from data.table
arrange
from plyr
sort
from taRifx
orderBy
from doBy
sortData
from Deducer
Most of the time you should use the dplyr
or data.table
solutions, unless having no-dependencies is important, in which case use base::order
.
I recently added sort.data.frame to a CRAN package, making it class compatible as discussed here: Best way to create generic/method consistency for sort.data.frame?
Therefore, given the data.frame dd, you can sort as follows:
dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
z = c(1, 1, 1, 2))
library(taRifx)
sort(dd, f= ~ -z + b )
If you are one of the original authors of this function, please contact me. Discussion as to public domaininess is here: https://chat.stackoverflow.com/transcript/message/1094290#1094290
You can also use the arrange()
function from plyr
as Hadley pointed out in the above thread:
library(plyr)
arrange(dd,desc(z),b)
Benchmarks: Note that I loaded each package in a new R session since there were a lot of conflicts. In particular loading the doBy package causes sort
to return "The following object(s) are masked from 'x (position 17)': b, x, y, z", and loading the Deducer package overwrites sort.data.frame
from Kevin Wright or the taRifx package.
#Load each time
dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
z = c(1, 1, 1, 2))
library(microbenchmark)
# Reload R between benchmarks
microbenchmark(dd[with(dd, order(-z, b)), ] ,
dd[order(-dd$z, dd$b),],
times=1000
)
Median times:
dd[with(dd, order(-z, b)), ]
778
dd[order(-dd$z, dd$b),]
788
library(taRifx)
microbenchmark(sort(dd, f= ~-z+b ),times=1000)
Median time: 1,567
library(plyr)
microbenchmark(arrange(dd,desc(z),b),times=1000)
Median time: 862
library(doBy)
microbenchmark(orderBy(~-z+b, data=dd),times=1000)
Median time: 1,694
Note that doBy takes a good bit of time to load the package.
library(Deducer)
microbenchmark(sortData(dd,c("z","b"),increasing= c(FALSE,TRUE)),times=1000)
Couldn't make Deducer load. Needs JGR console.
esort <- function(x, sortvar, ...) {
attach(x)
x <- x[with(x,order(sortvar,...)),]
return(x)
detach(x)
}
microbenchmark(esort(dd, -z, b),times=1000)
Doesn't appear to be compatible with microbenchmark due to the attach/detach.
m <- microbenchmark(
arrange(dd,desc(z),b),
sort(dd, f= ~-z+b ),
dd[with(dd, order(-z, b)), ] ,
dd[order(-dd$z, dd$b),],
times=1000
)
uq <- function(x) { fivenum(x)[4]}
lq <- function(x) { fivenum(x)[2]}
y_min <- 0 # min(by(m$time,m$expr,lq))
y_max <- max(by(m$time,m$expr,uq)) * 1.05
p <- ggplot(m,aes(x=expr,y=time)) + coord_cartesian(ylim = c( y_min , y_max ))
p + stat_summary(fun.y=median,fun.ymin = lq, fun.ymax = uq, aes(fill=expr))
(lines extend from lower quartile to upper quartile, dot is the median)
Given these results and weighing simplicity vs. speed, I'd have to give the nod to arrange
in the plyr
package. It has a simple syntax and yet is almost as speedy as the base R commands with their convoluted machinations. Typically brilliant Hadley Wickham work. My only gripe with it is that it breaks the standard R nomenclature where sorting objects get called by sort(object)
, but I understand why Hadley did it that way due to issues discussed in the question linked above.
Here's a simple example of how to load JSON data into an Angular model.
I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.
http://www.iNorthwind.com/Service1.svc/getAllCustomers
It returns some JSON data which looks like this:
{
"GetAllCustomersResult" :
[
{
"CompanyName": "Alfreds Futterkiste",
"CustomerID": "ALFKI"
},
{
"CompanyName": "Ana Trujillo Emparedados y helados",
"CustomerID": "ANATR"
},
{
"CompanyName": "Antonio Moreno Taquería",
"CustomerID": "ANTON"
}
]
}
..and I want to populate a drop down list with this data, to look like this...
I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.
How would I do it ?
My Angular controller would look like this:
function MikesAngularController($scope, $http) {
$scope.listOfCustomers = null;
$http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
.success(function (data) {
$scope.listOfCustomers = data.GetAllCustomersResult;
})
.error(function (data, status, headers, config) {
// Do some error handling here
});
}
... which fills a "listOfCustomers" variable with this set of JSON data.
Then, in my HTML page, I'd use this:
<div ng-controller='MikesAngularController'>
<span>Please select a customer:</span>
<select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>
And that's it. We can now see a list of our JSON data on a web page, ready to be used.
The key to this is in the "ng-options" tag:
customer.CustomerID as customer.CompanyName for customer in listOfCustomers
It's a strange syntax to get your head around !
When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.
The full script for this example can be found here:
Mike
This might be a simple solution to achieve this:
INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
FROM dual
WHERE NOT EXISTS (SELECT 1
FROM funds
WHERE ID = 23
AND date = DATE('2013-02-12'));
p.s. alternatively (if ID
a primary key):
INSERT INTO funds (ID, date, price)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need
see this Fiddle.
I've investigated Slauma's answer (which is awesome, thanks for the idea man), and I've reduced batch size until I've hit optimal speed. Looking at the Slauma's results:
It is visible that there is speed increase when moving from 1 to 10, and from 10 to 100, but from 100 to 1000 inserting speed is falling down again.
So I've focused on what's happening when you reduce batch size to value somewhere in between 10 and 100, and here are my results (I'm using different row contents, so my times are of different value):
Quantity | Batch size | Interval
1000 1 3
10000 1 34
100000 1 368
1000 5 1
10000 5 12
100000 5 133
1000 10 1
10000 10 11
100000 10 101
1000 20 1
10000 20 9
100000 20 92
1000 27 0
10000 27 9
100000 27 92
1000 30 0
10000 30 9
100000 30 92
1000 35 1
10000 35 9
100000 35 94
1000 50 1
10000 50 10
100000 50 106
1000 100 1
10000 100 14
100000 100 141
Based on my results, actual optimum is around value of 30 for batch size. It's less than both 10 and 100. Problem is, I have no idea why is 30 optimal, nor could have I found any logical explanation for it.
So the doctors here that are saying "You say that hurts? Then don't do that!" are probably right. But if you really want to, here's one way of passing arguments to a unittest test:
import sys
import unittest
class MyTest(unittest.TestCase):
USERNAME = "jemima"
PASSWORD = "password"
def test_logins_or_something(self):
print('username : {}'.format(self.USERNAME))
print('password : {}'.format(self.PASSWORD))
if __name__ == "__main__":
if len(sys.argv) > 1:
MyTest.USERNAME = sys.argv.pop()
MyTest.PASSWORD = sys.argv.pop()
unittest.main()
that will let you run with:
python mytests.py ausername apassword
You need the argv.pop
s so your command line params don't mess with unittest's own...
[update] The other thing you might want to look into is using environment variables:
import os
import unittest
class MyTest(unittest.TestCase):
USERNAME = "jemima"
PASSWORD = "password"
def test_logins_or_something(self):
print('username : {}'.format(self.USERNAME))
print('password : {}'.format(self.PASSWORD))
if __name__ == "__main__":
MyTest.USERNAME = os.environ.get('TEST_USERNAME', MyTest.USERNAME)
MyTest.PASSWORD = os.environ.get('TEST_PASSWORD', MyTest.PASSWORD)
unittest.main()
That will let you run with:
TEST_USERNAME=ausername TEST_PASSWORD=apassword python mytests.py
and it has the advantage that you're not messing with unittest's own argument parsing. downside is it won't work quite like that on Windows...
You could use regular expressions to replace the '\n' or '\n\r' characters with '<br />'.
you have this:
var h1 = document.createElement("h1");
h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE...
so this text will display in a new line";
you can replace your characters like this:
h1.innerHTML = h1.innerHTML.replace(/\n\r?/g, '<br />');
check the javascript reference for the String and Regex objects:
UPLOAD IMAGES WITH PROGRESS BAR
Thought I'd extend upon user3451783's answer and provide one with an HTML5 progress bar. I found that it was very annoying uploading photos without knowing if anything was happening at all.
HTML
<progress></progress>
<div id="summernote"></div>
JS
// initialise editor
$('#summernote').summernote({
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
});
// send the file
function sendFile(file, editor, welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
data: data,
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
return myXhr;
},
url: root + '/assets/scripts/php/app/uploadEditorImages.php',
cache: false,
contentType: false,
processData: false,
success: function(url) {
editor.insertImage(welEditable, url);
}
});
}
// update progress bar
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded, max:e.total});
// reset progress on complete
if (e.loaded == e.total) {
$('progress').attr('value','0.0');
}
}
}
In my efforts to learn object-oriented programming alongside learning statistics, I made this, maybe you'll find it useful:
samplesCourse = [9, 10, 10, 11, 13, 15, 16, 19, 19, 21, 23, 28, 30, 33, 34, 36, 44, 45, 47, 60]
class sampleSet:
def __init__(self, sampleList):
self.sampleList = sampleList
self.interList = list(sampleList) # interList is sampleList alias; alias used to maintain integrity of original sampleList
def find_median(self):
self.median = 0
if len(self.sampleList) % 2 == 0:
# find median for even-numbered sample list length
self.medL = self.interList[int(len(self.interList)/2)-1]
self.medU = self.interList[int(len(self.interList)/2)]
self.median = (self.medL + self.medU)/2
else:
# find median for odd-numbered sample list length
self.median = self.interList[int((len(self.interList)-1)/2)]
return self.median
def find_1stQuartile(self, median):
self.lower50List = []
self.Q1 = 0
# break out lower 50 percentile from sampleList
if len(self.interList) % 2 == 0:
self.lower50List = self.interList[:int(len(self.interList)/2)]
else:
# drop median to make list ready to divide into 50 percentiles
self.interList.pop(interList.index(self.median))
self.lower50List = self.interList[:int(len(self.interList)/2)]
# find 1st quartile (median of lower 50 percentiles)
if len(self.lower50List) % 2 == 0:
self.Q1L = self.lower50List[int(len(self.lower50List)/2)-1]
self.Q1U = self.lower50List[int(len(self.lower50List)/2)]
self.Q1 = (self.Q1L + self.Q1U)/2
else:
self.Q1 = self.lower50List[int((len(self.lower50List)-1)/2)]
return self.Q1
def find_3rdQuartile(self, median):
self.upper50List = []
self.Q3 = 0
# break out upper 50 percentile from sampleList
if len(self.sampleList) % 2 == 0:
self.upper50List = self.interList[int(len(self.interList)/2):]
else:
self.interList.pop(interList.index(self.median))
self.upper50List = self.interList[int(len(self.interList)/2):]
# find 3rd quartile (median of upper 50 percentiles)
if len(self.upper50List) % 2 == 0:
self.Q3L = self.upper50List[int(len(self.upper50List)/2)-1]
self.Q3U = self.upper50List[int(len(self.upper50List)/2)]
self.Q3 = (self.Q3L + self.Q3U)/2
else:
self.Q3 = self.upper50List[int((len(self.upper50List)-1)/2)]
return self.Q3
def find_InterQuartileRange(self, Q1, Q3):
self.IQR = self.Q3 - self.Q1
return self.IQR
def find_UpperFence(self, Q3, IQR):
self.fence = self.Q3 + 1.5 * self.IQR
return self.fence
samples = sampleSet(samplesCourse)
median = samples.find_median()
firstQ = samples.find_1stQuartile(median)
thirdQ = samples.find_3rdQuartile(median)
iqr = samples.find_InterQuartileRange(firstQ, thirdQ)
fence = samples.find_UpperFence(thirdQ, iqr)
print("Median is: ", median)
print("1st quartile is: ", firstQ)
print("3rd quartile is: ", thirdQ)
print("IQR is: ", iqr)
print("Upper fence is: ", fence)
Yes, you can do this use this below code it may help you.
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
display : block;_x000D_
padding : 10px;_x000D_
text-align : center;_x000D_
border: 5px solid #000;_x000D_
margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
<div class="childDiv1">_x000D_
First Div Child_x000D_
</div>_x000D_
<div class="childDiv2">_x000D_
Second Div Child_x000D_
</div>_x000D_
<div class="childDiv3">_x000D_
Third Div Child_x000D_
</div>_x000D_
<div class="childDiv4">_x000D_
Fourth Div Child_x000D_
</div>_x000D_
</div>
_x000D_
You can add button in toolbar
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:title="title">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="16dp"
android:background="@color/transparent"
android:drawableRight="@drawable/ic_your_icon"
android:drawableTint="@drawable/btn_selector"
android:text="@string/sort_by_credit"
android:textColor="@drawable/btn_selector"
/>
</android.support.v7.widget.Toolbar>
create file btn_selector.xml in drawable
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:color="@color/white"
/>
<item
android:color="@color/white_30_opacity"
/>
java:
private boolean isSelect = false;
OnClickListener for button:
private void myClick() {
if (!isSelect) {
//**your code**//
isSelect = true;
} else {//**your code**//
isSelect = false;
}
sort.setSelected(isSelect);
}
the & is the default value for DEFINE, which allows you to use substitution variables. I like to turn it off using
SET DEFINE OFF
then you won't have to worry about escaping or CHR(38).
Why all this complicatedness?
sh 'env'
does what you need (under *nix)
This might sound really simplistic...
But this will center the div inside the div, exactly in the center in relation to left and right margin or parent container, but you can adjust percentage symmetrically on left and right.
margin-right: 10%;
margin-left: 10%;
Then you can adjust % to make it as wide as you want it.
Try:
<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>
and then in your controller
@car = Car.find(params[:car])
which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id
hope it helps! happy coding
more than a year later, but if you see it or anyone does, i could use the points ;D
The canvas spec doesn't give us a method for measuring the height of a string. However, you can set the size of your text in pixels and you can usually figure out what the vertical bounds are relatively easily.
If you need something more precise then you could throw text onto the canvas and then get pixel data and figure out how many pixels are used vertically. This would be relatively simple, but not very efficient. You could do something like this (it works, but draws some text onto your canvas that you would want to remove):
function measureTextHeight(ctx, left, top, width, height) {
// Draw the text in the specified area
ctx.save();
ctx.translate(left, top + Math.round(height * 0.8));
ctx.mozDrawText('gM'); // This seems like tall text... Doesn't it?
ctx.restore();
// Get the pixel data from the canvas
var data = ctx.getImageData(left, top, width, height).data,
first = false,
last = false,
r = height,
c = 0;
// Find the last line with a non-white pixel
while(!last && r) {
r--;
for(c = 0; c < width; c++) {
if(data[r * width * 4 + c * 4 + 3]) {
last = r;
break;
}
}
}
// Find the first line with a non-white pixel
while(r) {
r--;
for(c = 0; c < width; c++) {
if(data[r * width * 4 + c * 4 + 3]) {
first = r;
break;
}
}
// If we've got it then return the height
if(first != r) return last - first;
}
// We screwed something up... What do you expect from free code?
return 0;
}
// Set the font
context.mozTextStyle = '32px Arial';
// Specify a context and a rect that is safe to draw in when calling measureTextHeight
var height = measureTextHeight(context, 0, 0, 50, 50);
console.log(height);
For Bespin they do fake a height by measuring the width of a lowercase 'm'... I don't know how this is used, and I would not recommend this method. Here is the relevant Bespin method:
var fixCanvas = function(ctx) {
// upgrade Firefox 3.0.x text rendering to HTML 5 standard
if (!ctx.fillText && ctx.mozDrawText) {
ctx.fillText = function(textToDraw, x, y, maxWidth) {
ctx.translate(x, y);
ctx.mozTextStyle = ctx.font;
ctx.mozDrawText(textToDraw);
ctx.translate(-x, -y);
}
}
if (!ctx.measureText && ctx.mozMeasureText) {
ctx.measureText = function(text) {
ctx.mozTextStyle = ctx.font;
var width = ctx.mozMeasureText(text);
return { width: width };
}
}
if (ctx.measureText && !ctx.html5MeasureText) {
ctx.html5MeasureText = ctx.measureText;
ctx.measureText = function(text) {
var textMetrics = ctx.html5MeasureText(text);
// fake it 'til you make it
textMetrics.ascent = ctx.html5MeasureText("m").width;
return textMetrics;
}
}
// for other browsers
if (!ctx.fillText) {
ctx.fillText = function() {}
}
if (!ctx.measureText) {
ctx.measureText = function() { return 10; }
}
};
You were almost there:
You just need to append the li
to ul
and voila!
So just add
ul.appendChild(li);
to the end of your function so the end function will be like this:
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
ul.appendChild(li);
}
Look at my code, but be aware. I use async/await, because latest Chrome beta can read any es6 code, which gets by TypeScript with compilation. So, you must replace asyns/await by .then()
.
Input change handler:
/**
* @param fileInput
*/
public psdTemplateSelectionHandler (fileInput: any){
let FileList: FileList = fileInput.target.files;
for (let i = 0, length = FileList.length; i < length; i++) {
this.psdTemplates.push(FileList.item(i));
}
this.progressBarVisibility = true;
}
Submit handler:
public async psdTemplateUploadHandler (): Promise<any> {
let result: any;
if (!this.psdTemplates.length) {
return;
}
this.isSubmitted = true;
this.fileUploadService.getObserver()
.subscribe(progress => {
this.uploadProgress = progress;
});
try {
result = await this.fileUploadService.upload(this.uploadRoute, this.psdTemplates);
} catch (error) {
document.write(error)
}
if (!result['images']) {
return;
}
this.saveUploadedTemplatesData(result['images']);
this.redirectService.redirect(this.redirectRoute);
}
FileUploadService. That service also stored uploading progress in progress$ property, and in other places, you can subscribe on it and get new value every 500ms.
import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
@Injectable()
export class FileUploadService {
/**
* @param Observable<number>
*/
private progress$: Observable<number>;
/**
* @type {number}
*/
private progress: number = 0;
private progressObserver: any;
constructor () {
this.progress$ = new Observable(observer => {
this.progressObserver = observer
});
}
/**
* @returns {Observable<number>}
*/
public getObserver (): Observable<number> {
return this.progress$;
}
/**
* Upload files through XMLHttpRequest
*
* @param url
* @param files
* @returns {Promise<T>}
*/
public upload (url: string, files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
FileUploadService.setUploadUpdateInterval(500);
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
/**
* Set interval for frequency with which Observable inside Promise will share data with subscribers.
*
* @param interval
*/
private static setUploadUpdateInterval (interval: number): void {
setInterval(() => {}, interval);
}
}
You must know the source encoding.
string someText = "The quick brown fox jumps over the lazy dog.";
byte[] bytes = Encoding.Unicode.GetBytes(someText);
char[] chars = Encoding.Unicode.GetChars(bytes);
Yes. There is a simple way to remove everything in iPython. In iPython console, just type:
%reset
Then system will ask you to confirm. Press y. If you don't want to see this prompt, simply type:
%reset -f
This should work..
You can't call free
on the pointers returned from strsep
. Those are not individually allocated strings, but just pointers into the string s
that you've already allocated. When you're done with s
altogether, you should free it, but you do not have to do that with the return values of strsep
.
Try below steps:
It worked for me.
These are the steps necessary to use OpenCV with Android Studio 1.2:
sdk/java
in the directory you extracted beforeopencv
compileSdkVersion
and buildToolsVersion
to versions you have on your machineAdd compile project(':opencv')
to your app build.gradle
dependencies {
...
compile project(':opencv')
}
Press Sync Project with Gradle Files
Starting from this @Kartik Patel example , I have changed a little maybe now is more clear about static variable
public class Variable
{
public static string StaticName = "Sophia ";
public string nonStName = "Jenna ";
public void test()
{
StaticName = StaticName + " Lauren";
Console.WriteLine(" static ={0}",StaticName);
nonStName = nonStName + "Bean ";
Console.WriteLine(" NeStatic neSt={0}", nonStName);
}
}
class Program
{
static void Main(string[] args)
{
Variable var = new Variable();
var.test();
Variable var1 = new Variable();
var1.test();
Variable var2 = new Variable();
var2.test();
Console.ReadKey();
}
}
Output
static =Sophia Lauren
NeStatic neSt=Jenna Bean
static =Sophia Lauren Lauren
NeStatic neSt=Jenna Bean
static =Sophia Lauren Lauren Lauren
NeStatic neSt=Jenna Bean
Class Variable VS Instance Variable in C#
Static Class Members C# OR Class Variable
class A
{
// Class variable or " static member variable" are declared with
//the "static " keyword
public static int i=20;
public int j=10; //Instance variable
public static string s1="static class variable"; //Class variable
public string s2="instance variable"; // instance variable
}
class Program
{
static void Main(string[] args)
{
A obj1 = new A();
// obj1 instance variables
Console.WriteLine("obj1 instance variables ");
Console.WriteLine(A.i);
Console.WriteLine(obj1.j);
Console.WriteLine(obj1.s2);
Console.WriteLine(A.s1);
A obj2 = new A();
// obj2 instance variables
Console.WriteLine("obj2 instance variables ");
Console.WriteLine(A.i);
Console.WriteLine(obj2.j);
Console.WriteLine(obj2.s2);
Console.WriteLine(A.s1);
Console.ReadKey();
}
}
}
https://en.wikipedia.org/wiki/Class_variable
https://en.wikipedia.org/wiki/Instance_variable
Faced the same Exception in different use case.
Use Case : Try to read data from DB with DTO projection.
Solution: Use get method instead of load.
Generic Operation
public class HibernateTemplate {
public static Object loadObject(Class<?> cls, Serializable s) {
Object o = null;
Transaction tx = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
o = session.load(cls, s); /*change load to get*/
tx.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
}
return o;
}
}
Persistence Class
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id")
private int customerId;
@Column(name = "Name")
private String customerName;
@Column(name = "City")
private String city;
//constructors , setters and getters
}
CustomerDAO interface
public interface CustomerDAO
{
public CustomerTO getCustomerById(int cid);
}
Entity Transfer Object Class
public class CustomerTO {
private int customerId;
private String customerName;
private String city;
//constructors , setters and getters
}
Factory Class
public class DAOFactory {
static CustomerDAO customerDAO;
static {
customerDAO = new HibernateCustomerDAO();
}
public static CustomerDAO getCustomerDAO() {
return customerDAO;
}
}
Entity specific DAO
public class HibernateCustomerDAO implements CustomerDAO {
@Override
public CustomerTO getCustomerById(int cid) {
Customer cust = (Customer) HibernateTemplate.loadObject(Customer.class, cid);
CustomerTO cto = new CustomerTO(cust.getCustomerId(), cust.getCustomerName(), cust.getCity());
return cto;
}
}
Retrieving data: Test Class
CustomerDAO cdao = DAOFactory.getCustomerDAO();
CustomerTO c1 = cdao.getCustomerById(2);
System.out.println("CustomerName -> " + c1.getCustomerName() + " ,CustomerCity -> " + c1.getCity());
Present Data
Query and output generated by Hibernate System
Hibernate: select customer0_.Id as Id1_0_0_, customer0_.City as City2_0_0_, customer0_.Name as Name3_0_0_ from CustomerLab31 customer0_ where customer0_.Id=?
CustomerName -> Cody ,CustomerCity -> LA
The direct answer to this question is:
if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
rows.RemoveAt(rows.Count - 1);
}
However... in the specific case of this question, it makes more sense not to add the row in the first place:
Row row = new Row();
//...
if (!row.cell[0].Equals("Something"))
{
rows.Add(row);
}
TBH, I'd go a step further by testing "Something"
against user.""
, and not even instantiating a Row
unless the condition is satisfied, but seeing as user.""
won't compile, I'll leave that as an exercise for the reader.
Use stdint.h
for specific sizes of integer data types, and also use appropriate suffixes for integer literal constants, e.g.:
#include <stdint.h>
int64_t i2 = 0x0000444400004444LL;
A union query can only have one master ORDER BY
clause, IIRC. To get this, in each query making up the greater UNION
query, add a field that will be the one field you sort by for the UNION
's ORDER BY
.
For instance, you might have something like
SELECT field1, field2, '1' AS union_sort
UNION SELECT field1, field2, '2' AS union_sort
UNION SELECT field1, field2, '3' AS union_sort
ORDER BY union_sort
That union_sort
field can be anything you may want to sort by. In this example, it just happens to put results from the first table first, second table second, etc.
$scope.rtGo = function(){
$window.sessionStorage.removeItem('message');
$window.sessionStorage.removeItem('status');
}
It is posible. My android device version is 4.0.4 and android.os.Build.VERSION.SDK_INT is 15
I have 3 spinners
Spinner c_fruit=(Spinner) findViewById(R.id.fruits);
Spinner c_vegetable=(Spinner) findViewById(R.id.vegetables);
Spinner c_beverage=(Spinner) findViewById(R.id.beverages);
And also I have a Async-Tack class.
Here is my spinner loading code
RequestSend reqs_fruit = new RequestSend(this);
reqs_fruit.where="Get_fruit_List";
reqs_fruit.title="Loading fruit";
reqs_fruit.execute();
RequestSend reqs_vegetable = new RequestSend(this);
reqs_vegetable.where="Get_vegetable_List";
reqs_vegetable.title="Loading vegetable";
reqs_vegetable.execute();
RequestSend reqs_beverage = new RequestSend(this);
reqs_beverage.where="Get_beverage_List";
reqs_beverage.title="Loading beverage";
reqs_beverage.execute();
This is working perfectly. One by one my spinners loaded. I didn't user executeOnExecutor.
Here is my Async-task class
public class RequestSend extends AsyncTask<String, String, String > {
private ProgressDialog dialog = null;
public Spinner spin;
public String where;
public String title;
Context con;
Activity activity;
String[] items;
public RequestSend(Context activityContext) {
con = activityContext;
dialog = new ProgressDialog(activityContext);
this.activity = activityContext;
}
@Override
protected void onPostExecute(String result) {
try {
ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
} catch (NullPointerException e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
}
protected void onPreExecute() {
super.onPreExecute();
dialog.setTitle(title);
dialog.setMessage("Wait...");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected String doInBackground(String... Strings) {
try {
Send_Request();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void Send_Request() throws JSONException {
try {
String DataSendingTo = "http://www.example.com/AppRequest/" + where;
//HttpClient
HttpClient httpClient = new DefaultHttpClient();
//Post header
HttpPost httpPost = new HttpPost(DataSendingTo);
//Adding data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("authorized","001"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line) ;
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
items = new String[finalResult.length()];
// looping through All details and store in public String array
for(int i = 0; i < finalResult.length(); i++) {
JSONObject c = finalResult.getJSONObject(i);
items[i]=c.getString("data_name");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
As slight improvement to @MONTYHS answer, iterating through a tup of fieldnames:
import csv
import json
csvfilename = 'filename.csv'
jsonfilename = csvfilename.split('.')[0] + '.json'
csvfile = open(csvfilename, 'r')
jsonfile = open(jsonfilename, 'w')
reader = csv.DictReader(csvfile)
fieldnames = ('FirstName', 'LastName', 'IDNumber', 'Message')
output = []
for each in reader:
row = {}
for field in fieldnames:
row[field] = each[field]
output.append(row)
json.dump(output, jsonfile, indent=2, sort_keys=True)
Downgrading the iOS development Target from 12.1
to 12
fix the issue for me as I don't have a dev team configured.
If possible, check out SSIS (SQL Server Integration Services). I am just getting my feet wet with this toolkit, but already am looping over 40+ servers and preparing to wreak all kinds of havoc ;)
If none of the above solutions work for any reason, like my case, try this:
<script type="text/javascript">
$(function()
{
$('[name="my_checkbox"]').change(function()
{
if ($(this).is(':checked')) {
// Do something...
alert('You can rock now...');
};
});
});
</script>
@SETLOCAL ENABLEDELAYEDEXPANSION
@REM Use WMIC to retrieve date and time
@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF NOT "%%~F"=="" (
SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
set YEAR=!SortDate:~0,4!
set MON=!SortDate:~4,2!
set DAY=!SortDate:~6,2!
@REM Add 1000000 so as to force a prepended 0 if hours less than 10
SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E
set HOUR=!SortTime:~1,2!
set MIN=!SortTime:~3,2!
set SEC=!SortTime:~5,2!
)
)
@echo on
@echo DATE=%DATE%, TIME=%TIME%
@echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC!
@echo YR=!YEAR! MON=!MON! DAY=!DAY!
@echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!'
Output:
DATE=2015-05-20, TIME= 1:30:38.59
HOUR=01 MIN=30 SEC=38
YR=2015 MON=05 DAY=20
DATECODE= '201505200130'
Also works with the style tag:
<span class="glyphicon glyphicon-ok" style="color:#00FF00;"></span>
<span class="glyphicon glyphicon-remove" style="color:#FF0000;"></span>
It's important to point out to readers stumbling upon this question when researching the subject in a broader fashion that the accepted answer's procedure is not required in the case you just want to split your project into files. It's only needed when you need multiple implementations of single classes. If your implementation per class is one, just one header file for each is enough.
Hence, from the accepted answer's example only this part is needed:
#ifndef MYHEADER_H
#define MYHEADER_H
//Class goes here, full declaration AND implementation
#endif
The #ifndef etc. preprocessor definitions allow it to be used multiple times.
PS. The topic becomes clearer once you realize C/C++ is 'dumb' and #include is merely a way to say "dump this text at this spot".
you can use COUNT(DISTINCT ip)
, this will only count distinct values
const Console = prop => (
console[Object.keys(prop)[0]](...Object.values(prop))
,null // ? React components must return something
)
// Some component with JSX and a logger inside
const App = () =>
<div>
<p>imagine this is some component</p>
<Console log='foo' />
<p>imagine another component</p>
<Console warn='bar' />
</div>
// Render
ReactDOM.render(
<App />,
document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
To convert any object or object list into JSON, we have to use the function JsonConvert.SerializeObject.
The below code demonstrates the use of JSON in an ASP.NET environment:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace JSONFromCS
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e1)
{
List<Employee> eList = new List<Employee>();
Employee e = new Employee();
e.Name = "Minal";
e.Age = 24;
eList.Add(e);
e = new Employee();
e.Name = "Santosh";
e.Age = 24;
eList.Add(e);
string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);
string script = "var employeeList = {\"Employee\": " + ans+"};";
script += "for(i = 0;i<employeeList.Employee.length;i++)";
script += "{";
script += "alert ('Name : ='+employeeList.Employee[i].Name+'
Age : = '+employeeList.Employee[i].Age);";
script += "}";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
}
}
public class Employee
{
public string Name;
public int Age;
}
}
After running this program, you will get two alerts
In the above example, we have created a list of Employee object and passed it to function "JsonConvert.SerializeObject". This function (JSON library) will convert the object list into JSON format. The actual format of JSON can be viewed in the below code snippet:
{ "Maths" : [ {"Name" : "Minal", // First element
"Marks" : 84,
"age" : 23 },
{
"Name" : "Santosh", // Second element
"Marks" : 91,
"age" : 24 }
],
"Science" : [
{
"Name" : "Sahoo", // First Element
"Marks" : 74,
"age" : 27 },
{
"Name" : "Santosh", // Second Element
"Marks" : 78,
"age" : 41 }
]
}
Syntax:
{} - acts as 'containers'
[] - holds arrays
: - Names and values are separated by a colon
, - Array elements are separated by commas
This code is meant for intermediate programmers, who want to use C# 2.0 to create JSON and use in ASPX pages.
You can create JSON from JavaScript end, but what would you do to convert the list of object into equivalent JSON string from C#. That's why I have written this article.
In C# 3.5, there is an inbuilt class used to create JSON named JavaScriptSerializer.
The following code demonstrates how to use that class to convert into JSON in C#3.5.
JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);
So, try to create a List of arrays with Questions and then serialize this list into JSON
check two things
pip2 --version
and
pip3 --version
because the default pip may be anyone of this so it is always better to check both.
The following will work independent of your database privileges:
select * from all_triggers
where table_name = 'YOUR_TABLE'
The following alternate options may or may not work depending on your assigned database privileges:
select * from DBA_TRIGGERS
or
select * from USER_TRIGGERS
One way is to put all the nested loops into a function and return from the inner most loop incase of a need to break out of all loops.
function()
{
for(int i=0; i<1000; i++)
{
for(int j=0; j<1000;j++)
{
if (condition)
return;
}
}
}
Try:
adb shell ip addr show rmnet0
It will return something like that:
3: rmnet0: <UP,LOWER_UP> mtu 1500 qdisc htb state UNKNOWN qlen 1000
link/[530]
inet 172.22.1.100/29 scope global rmnet0
inet6 fc01:abab:cdcd:efe0:8099:af3f:2af2:8bc/64 scope global dynamic
valid_lft forever preferred_lft forever
inet6 fe80::8099:af3f:2af2:8bc/64 scope link
valid_lft forever preferred_lft forever
This part is your IPV4 assigned by the operator
inet 172.22.1.100
This part is your IPV6 assigned by the operator
inet6 fc01:abab:cdcd:efe0:8099:af3f:2af2:8bc
Check if there is any zombie process using "top" command.
docker ps | grep <<container name>>
Get the container id.
ps -ef | grep <<container id>>
ps -ef|grep defunct | grep java
And kill the container by Parent PID .
It took me a while, but I discovered that including the following was what made it possible to change the navbar color:
.navbar{
background-image: none;
}
I had a similar requirement (twitter style text field). Used onkeyup
and onchange
. onchange
actually takes care of mouse paste operations during lost focus from the field.
[Update] In HTML5 or later, use oninput
to get real time character modification updates, as explained in other answers above.
Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.
Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
Configure log4j.properties
log4j.rootLogger=TRACE, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
Java example
public class Slf4jExample {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
final String message = "Hello logging!";
logger.trace(message);
logger.debug(message);
logger.info(message);
logger.warn(message);
logger.error(message);
}
}
Third match in google for "C++ slicing" gives me this Wikipedia article http://en.wikipedia.org/wiki/Object_slicing and this (heated, but the first few posts define the problem) : http://bytes.com/forum/thread163565.html
So it's when you assign an object of a subclass to the super class. The superclass knows nothing of the additional information in the subclass, and hasn't got room to store it, so the additional information gets "sliced off".
If those links don't give enough info for a "good answer" please edit your question to let us know what more you're looking for.
The type of pointer to non-static member function is different from pointer to ordinary function.
Type is void(*)(int)
if it’s an ordinary or static member function.
Type is void(CLoggersInfra::*)(int)
if it’s a non-static member function.
So you cannot pass a pointer to a non-static member function if it is expecting an ordinary function pointer.
Furthermore, a non-static member function has an implicit/hidden parameter to the object. The this
pointer is implicitly passed as an argument to the member function call. So the member functions can be invoked only by providing an object.
If the API Init
cannot be changed, a wrapper function (ordinary function or a class static member function) that invokes the member can be used. In the worst case, the object would be a global for the wrapper function to access.
CLoggersInfra* pLoggerInfra;
RedundencyManagerCallBackWrapper(int val)
{
pLoggerInfra->RedundencyManagerCallBack(val);
}
m_cRedundencyManager->Init(RedundencyManagerCallBackWrapper);
If the API Init
can be changed, there are many alternatives - Object non-static member function pointer, Function Object, std::function
or Interface Function.
See the post on callbacks for the different variations with C++ working examples.
This question is already resolved, but...
...also consider the solution suggested by Wouter in his original comment. The ability to handle missing data, including dropna()
, is built into pandas explicitly. Aside from potentially improved performance over doing it manually, these functions also come with a variety of options which may be useful.
In [24]: df = pd.DataFrame(np.random.randn(10,3))
In [25]: df.iloc[::2,0] = np.nan; df.iloc[::4,1] = np.nan; df.iloc[::3,2] = np.nan;
In [26]: df
Out[26]:
0 1 2
0 NaN NaN NaN
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
4 NaN NaN 0.050742
5 -1.250970 0.030561 -2.678622
6 NaN 1.036043 NaN
7 0.049896 -0.308003 0.823295
8 NaN NaN 0.637482
9 -0.310130 0.078891 NaN
In [27]: df.dropna() #drop all rows that have any NaN values
Out[27]:
0 1 2
1 2.677677 -1.466923 -0.750366
5 -1.250970 0.030561 -2.678622
7 0.049896 -0.308003 0.823295
In [28]: df.dropna(how='all') #drop only if ALL columns are NaN
Out[28]:
0 1 2
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
4 NaN NaN 0.050742
5 -1.250970 0.030561 -2.678622
6 NaN 1.036043 NaN
7 0.049896 -0.308003 0.823295
8 NaN NaN 0.637482
9 -0.310130 0.078891 NaN
In [29]: df.dropna(thresh=2) #Drop row if it does not have at least two values that are **not** NaN
Out[29]:
0 1 2
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
5 -1.250970 0.030561 -2.678622
7 0.049896 -0.308003 0.823295
9 -0.310130 0.078891 NaN
In [30]: df.dropna(subset=[1]) #Drop only if NaN in specific column (as asked in the question)
Out[30]:
0 1 2
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
5 -1.250970 0.030561 -2.678622
6 NaN 1.036043 NaN
7 0.049896 -0.308003 0.823295
9 -0.310130 0.078891 NaN
There are also other options (See docs at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html), including dropping columns instead of rows.
Pretty handy!
But here's the rub, sometimes you can't or don't want to wait. For example I want to use the new support for RubyMotion which includes RubyMotion project structure support, setup of rake files, setup of configurations that are hooked to iOS Simulator etc.
RubyMine has all of these now, IDEA does not. So I would have to generate a RubyMotion project outside of IDEA, then setup an IDEA project and hook up to that source folder etc and God knows what else.
What JetBrains should do is have a licensing model that would allow me, with the purchase of IDEA to use any of other IDEs, as opposed to just relying on IDEAs plugins.
I would be willing to pay more for that i.e. say 50 bucks more for said flexibility.
The funny thing is, I was originally a RubyMine customer that upgraded to IDEA, because I did want that polyglot setup. Now I'm contemplating paying for the upgrade of RubyMine, just because I need to do RubyMotion now. Also there are other potential areas where this out of sync issue might bite me again . For example torque box workflow / deployment support.
JetBrains has good IDEs but I guess I'm a bit annoyed.
Per Microsoft in powershell:
Get-ChildItem "hklm:SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\" | Get-ItemPropertyValue -Name Release | % { $_ -ge 394802 }
See the table at this link to get the DWORD value to search for specific versions:
This is bit tricky
Now a days most of website new techniques to save websites from scraping
1st Technique
Ctrl+U this will show you Page Source
2nd Technique
This one is small hack if the website has ajax like functionality.
Just Hover the mouse key on inspect element untill whole screen becomes just right click then and copy element
That's it you are good to go.
There is a very simple mental mapping in response that was a bit hard to find in the other answers:
done
implements tap
as in bluebird Promises
then
implements then
as in ES6 Promises
That single last line worked perfectly @GSerg.
The other function was what I had been working on but I don't like having to resort to UDF's unless absolutely necessary.
I had been trying a combination of excel and vba and had got this to work - but its clunky compared with your answer.
strArea = Sheets("Oper St Report CC").Range("cc_rev").CurrentRegion.Address
cc_rev_rows = "=ROWS(" & strArea & ")"
Range("cc_rev_count").Formula = cc_rev_rows
With jQuery:
jQuery('#myDivID').css("background-color");
With prototype:
$('myDivID').getStyle('backgroundColor');
With pure JS:
document.getElementById("myDivID").style.backgroundColor
So you want to generate date in format YYYYMMDD_hhmmss
.
As %date%
and %time%
formats are locale dependant you might need more robust ways to get a formatted date.
Here's one option:
@if (@X)==(@Y) @end /*
@cscript //E:JScript //nologo "%~f0"
@exit /b %errorlevel%
@end*/
var todayDate = new Date();
todayDate = "" +
todayDate.getFullYear() +
("0" + (todayDate.getMonth() + 1)).slice(-2) +
("0" + todayDate.getDate()).slice(-2) +
"_" +
("0" + todayDate.getHours()).slice(-2) +
("0" + todayDate.getMinutes()).slice(-2) +
("0" + todayDate.getSeconds()).slice(-2) ;
WScript.Echo(todayDate);
and if you save the script as jsdate.bat
you can assign it as a value :
for /f %%a in ('jsdate.bat') do @set "fdate=%%a"
echo %fdate%
or directly from command prompt:
for /f %a in ('jsdate.bat') do @set "fdate=%a"
Or you can use powershell which probably is the way that requires the less code:
for /f %%# in ('powershell Get-Date -Format "yyyyMMdd_HHmmss"') do set "fdate=%%#"
you can always use new stdClass()
. Example code:
$object = new stdClass();
$object->property = 'Here we go';
var_dump($object);
/*
outputs:
object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/
Also as of PHP 5.4 you can get same output with:
$object = (object) ['property' => 'Here we go'];
Try using cURL instead. cURL implements a cookie jar, while file_get_contents doesn't.
Just test and get the result.
// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
// return: http://localhost/myproject/
echo $protocol.$hostName.$pathInfo['dirname']."/";
The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int
int g[] = {9,8};
int (*j) = g;
could also be rewritten as
int g[] = {9,8};
int *j = g;
which could also be rewritten as
int g[] = {9,8};
int *j = &g[0];
a pointer-to-an-array would look like
int g[] = {9,8};
int (*j)[2] = &g;
//Dereference 'j' and access array element zero
int n = (*j)[0];
There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations
Use the force, read the source (excerpt from the Priority
and Level
class compiled, TRACE level was introduced in version 1.2.12):
public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT = 30000;
public final static int INFO_INT = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000;
public final static int ALL_INT = Integer.MIN_VALUE;
or the log4j API for the Level
class, which makes it quite clear.
When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger
object (based on configuration) and compares it with the LogEvent
's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent
's level is greater or equal to the Logger
's level, the LogEvent
is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.
//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {
// Call your function here
DispatchQueue.main.async {
// Update UI
self.tableView.reloadData()
}
}
//To call or execute function after some time
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
//Here call your function
}
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()
})
This worked for me.
npm uninstall -g create-react-app
npx create-react-app my-app
For those who using Mamp or Mamp pro:
Open MAMP Pro
Click on “Hosts”
Click on “Extended” (UPDATE: Only if you are using MAMP Pro 3.0.6)
Check “Indexes”
Click “Save”
That’s it! Reload your localhost starting page and it should work properly.
One line solution
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true\false
if substring exists\does'nt exist
Needs ES6 support
Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.
One more way to do it.
Add commit on the top of temporary commit and then do:
git rebase -i
To merge two commits into one (command will open text file with explicit instructions, edit it).
you can also use Recursion
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.