Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.
How about Embarcadero Rapid SQL Really good but kind of expensive.
function UpdateClick(btn) {
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i]);
if (Page_Validators[i].isvalid == false)
return false;
}
btn.disabled = 'false';
btn.value = 'Please Wait...';
return true;
}
Using react hooks, you can now call useState()
in your function component.
useState()
will return an array of 2 things:
Updating the value by its setter will force your function component to re-render,
just like forceUpdate
does:
import React, { useState } from 'react';
//create your forceUpdate hook
function useForceUpdate(){
const [value, setValue] = useState(0); // integer state
return () => setValue(value => value + 1); // update the state to force render
}
function MyComponent() {
// call your hook here
const forceUpdate = useForceUpdate();
return (
<div>
{/*Clicking on the button will force to re-render like force update does */}
<button onClick={forceUpdate}>
Click to re-render
</button>
</div>
);
}
The component above uses a custom hook function (useForceUpdate
) which uses the react state hook useState
. It increments the component's state's value and thus tells React to re-render the component.
In an old version of this answer, the snippet used a boolean value, and toggled it in forceUpdate()
. Now that I've edited my answer, the snippet use a number rather than a boolean.
Why ? (you would ask me)
Because once it happened to me that my forceUpdate()
was called twice subsequently from 2 different events, and thus it was reseting the boolean value at its original state, and the component never rendered.
This is because in the useState
's setter (setValue
here), React
compare the previous state with the new one, and render only if the state is different.
This might be of some help: http://www.webmasterworld.com/forum83/200.htm
A relevant quote:
Most attempts to accomplish this were made by assigning the property and value: div{height:100%} - this alone will not work. The reason is that without a parent defined height, the div{height:100%;} has nothing to factor 100% percent of, and will default to a value of div{height:auto;} - auto is an "as needed value" which is governed by the actual content, so that the div{height:100%} will a=only extend as far as the content demands.
The solution to the problem is found by assigning a height value to the parent container, in this case, the body element. Writing your body stlye to include height 100% supplies the needed value.
html, body { margin:0; padding:0; height:100%; }
You can use Perl for that:
perl -ane 'print "$F[1] $F[0]\n"' < file.txt
The advantage of running perl is that (if you know Perl) you can do much more computation on F than rearranging columns.
Best way to compare undefined or null or 0 with ES5 and ES6 standards
if ((Boolean(some_variable_1) && Boolean(some_variable_2)) === false) {
// do something
}
Handle the Worksheet_Change
event or the Workbook_SheetChange
event.
The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.
GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL
. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.
I have an easier solution (that I used myself recently, for a host of lazy reasons). Add this method to the class you are working in:
public static void DumbDebug(string message)
{
File.WriteAllText(@"C:\AdHocConsole\" + message + ".txt", "this is really dumb. I wish Microsoft had more obvious solutions to its solutions problems.");
}
Then...open up the directory AdHocConsole, and order by created time. Make sure when you add your 'print statements'. They are distinct though, else there will be juggling.
another way to get exactly the output mentioned in the question:
envtext= "printenv".execute().text
envtext.split('\n').each
{ envvar=it.split("=")
println envvar[0]+" is "+envvar[1]
}
This can easily be extended to build a map with a subset of env vars matching a criteria:
envdict=[:]
envtext= "printenv".execute().text
envtext.split('\n').each
{ envvar=it.split("=")
if (envvar[0].startsWith("GERRIT_"))
envdict.put(envvar[0],envvar[1])
}
envdict.each{println it.key+" is "+it.value}
http://momentjs.com/docs/#/displaying/unix-timestamp/
You get the number of unix seconds, not milliseconds!
You you need to multiply it with 1000 or using valueOf()
and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.
moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()
The for
attribute is called htmlFor
for consistency with the DOM property API. If you're using the development build of React, you should have seen a warning in your console about this.
Suggest the following simplification: capture return value from Workbooks.Add
instead of subscripting Windows()
afterward, as follows:
Set wkb = Workbooks.Add
wkb.SaveAs ...
wkb.Activate ' instead of Windows(expression).Activate
General Philosophy Advice:
Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.
Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.
Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection
During and within macros do not rely on these built-in names, instead capture return values, e.g.
Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate
Also, try to use qualified expressions, e.g.
wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"
or
Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"
Use qualified expressions, e.g.
newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar"
These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.
Also please note that you'll likely find that you don't need to .Activate
nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate
could simply be eliminated instead of even being replaced by wkb.Activate
.
(Also note: I think the .Select statements you show are not contributing and can be omitted.)
(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)
You can do this using a combination of the Element.scrollHeight
and Element.clientHeight
attributes.
According to MDN:
The Element.scrollHeight read-only attribute is a measurement of the height of an element's content, including content not visible on the screen due to overflow. The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar. It includes the element padding but not its margin.
And:
The Element.clientHeight read-only property returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin.
clientHeight can be calculated as CSS height + CSS padding - height of horizontal scrollbar (if present).
Therefore, the element will display a scrollbar if the scroll height is greater than the client height, so the answer to your question is:
function scrollbarVisible(element) {
return element.scrollHeight > element.clientHeight;
}
RIGHT ( character_expression , integer_expression )
SELECT RIGHT(column, 4) FROM ...
Also a list of other string functions.
Adding one more obnoxious alternative to the list:
perl -pe'$.<=1||last' file
# or
perl -pe'$.<=1||last' < file
# or
cat file | perl -pe'$.<=1||last'
Similar to several answers like Alex V's and NDavis, but none of them are quite the same.
When already in the branch in question
Using:
git diff master...
Which combines several features:
Update:
This should probably be git diff master
, but also this shows the diff, not the commits as the question specified.
Set the background color of the src to none and allow transparencey.
[WITHIN SCR PAGE STYLE]
<style type="text/css">
body
{
background:none transparent;
}
</style>
[IFRAME]
<iframe src="#" allowtransparency="true">Error, iFrame failed to load.</iframe>
NOTE: I code my CSS a little different to how everyone else does.
KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.
UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.
Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.
PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.
Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.
FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).
Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.
All of these indexes may have more than one column in them.
With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)
Do you only want to disassemble your actual main? If so try this:
(gdb) info line main
(gdb) disas STARTADDRESS ENDADDRESS
Like so:
USER@MACHINE /cygdrive/c/prog/dsa
$ gcc-3.exe -g main.c
USER@MACHINE /cygdrive/c/prog/dsa
$ gdb a.exe
GNU gdb 6.8.0.20080328-cvs (cygwin-special)
...
(gdb) info line main
Line 3 of "main.c" starts at address 0x401050 <main> and ends at 0x401075 <main+
(gdb) disas 0x401050 0x401075
Dump of assembler code from 0x401050 to 0x401075:
0x00401050 <main+0>: push %ebp
0x00401051 <main+1>: mov %esp,%ebp
0x00401053 <main+3>: sub $0x18,%esp
0x00401056 <main+6>: and $0xfffffff0,%esp
0x00401059 <main+9>: mov $0x0,%eax
0x0040105e <main+14>: add $0xf,%eax
0x00401061 <main+17>: add $0xf,%eax
0x00401064 <main+20>: shr $0x4,%eax
0x00401067 <main+23>: shl $0x4,%eax
0x0040106a <main+26>: mov %eax,-0xc(%ebp)
0x0040106d <main+29>: mov -0xc(%ebp),%eax
0x00401070 <main+32>: call 0x4010c4 <_alloca>
End of assembler dump.
I don't see your system interrupt call however. (its been a while since I last tried to make a system call in assembly. INT 21h though, last I recall
Make sure your \n
is in "\n"
for it to work.
(Tested in Chrome while playing videos on YouTube, but should work anywhere--especially useful for speeding up online training videos).
For anyone wanting to add these as "bookmarklets" (bookmarks) to your browser, use these browser bookmark names and URLs, and add each of the following bookmarks to the top of your browser:
Name: 0.5x
URL:
javascript:
document.querySelector('video').playbackRate = 0.5;
Name: 1.0x
URL:
javascript:
document.querySelector('video').playbackRate = 1.0;
Name: 1.5x
URL:
javascript:
document.querySelector('video').playbackRate = 1.5;
Name: 2.0x
URL:
javascript:
document.querySelector('video').playbackRate = 2.0;
AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.
We need to add angular-cookies.min.js file to use cookie feature.
Here is some method of AngularJS Cookie.
get(key); // This method returns the value of given cookie key.
getObject(key); //This method returns the deserialized value of given cookie key.
getAll(); //This method returns a key value object with all the cookies.
put(key, value, [options]); //This method sets a value for given cookie key.
remove(key, [options]); //This method remove given cookie.
Example
Html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>
JavaScript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);
I have Taken reference from http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php.
<label for="profileImage">
<a style="cursor: pointer;"><em class="fa fa-upload"></em> Change Profile
Image</a></label>
<input type="file" name="profileImage" id="profileImage" style="display: none;">
// this will give all the forms on the page.
$('form')
// If you know the name of form then.
$('form[name="myFormName"]')
// If you don't know know the name but the position (starts with 0)
$('form:eq(1)') // 2nd form will be fetched.
Currently the method to add the listener to the map would be
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
And not
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
Interestingly, if the break tag is written in full-form as follows:
<br></br>
then the CSS line-height:145% works. If the break tag is written as:
<br> or
<br/>
then it doesn't work, at least in Chrome, IE and firefox. Weird!
In swift 4 : by overriding method
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name : "Main", bundle: nil)
let next vc = storyboard.instantiateViewController(withIdentifier: "nextvcIdentifier") as! NextViewController
self.navigationController?.pushViewController(prayerVC, animated: true)
}
As Jeffrey Said, you are not checking the value of check()
. In addition, your check()
function is not returning anything. Note the difference:
def check():
with open('example.txt') as f:
datafile = f.readlines()
found = False # This isn't really necessary
for line in datafile:
if blabla in line:
# found = True # Not necessary
return True
return False # Because you finished the search without finding
Then you can test the output of check()
:
if check():
print('True')
else:
print('False')
Did a quick google. Seems that to find the file size you do this,
long size = f.length();
The differences between the three methods you posted can be found here
getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.
You should really use Angular UI for that needs. Check it out: Angular UI Dialog
In a nutshell, with Angular UI dialog, you can pass variable from a controller to the dialog controller using resolve
. Here's your "from" controller:
var d = $dialog.dialog({
backdrop: true,
keyboard: true,
backdropClick: true,
templateUrl: '<url_of_your_template>',
controller: 'MyDialogCtrl',
// Interesting stuff here.
resolve: {
username: 'foo'
}
});
d.open();
And in your dialog controller:
angular.module('mymodule')
.controller('MyDialogCtrl', function ($scope, username) {
// Here, username is 'foo'
$scope.username = username;
}
EDIT: Since the new version of the ui-dialog, the resolve entry becomes:
resolve: { username: function () { return 'foo'; } }
SELECT TIMESTAMPDIFF(HOUR,NOW(),'2013-05-15 10:23:23')
calculates difference in hour.(for days--> you have to define day replacing hour
SELECT DATEDIFF('2012-2-2','2012-2-1')
SELECT TO_DAYS ('2012-2-2')-TO_DAYS('2012-2-1')
Actually, it is as simple as setting major
and minor
separately:
In [9]: plot([23, 456, 676, 89, 906, 34, 2345])
Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>]
In [10]: yscale('log')
In [11]: grid(b=True, which='major', color='b', linestyle='-')
In [12]: grid(b=True, which='minor', color='r', linestyle='--')
The gotcha with minor grids is that you have to have minor tick marks turned on too. In the above code this is done by yscale('log')
, but it can also be done with plt.minorticks_on()
.
What is a race condition?
The situation when the process is critically dependent on the sequence or timing of other events.
For example, Processor A and processor B both needs identical resource for their execution.
How do you detect them?
There are tools to detect race condition automatically:
How do you handle them?
Race condition can be handled by Mutex or Semaphores. They act as a lock allows a process to acquire a resource based on certain requirements to prevent race condition.
How do you prevent them from occurring?
There are various ways to prevent race condition, such as Critical Section Avoidance.
If you are using a new domain name, and you have done all the above and you are still getting the same error, check to see if you clear the DNS cache on your PC. Clear your DNS for more details.
Windows® 8
To clear your DNS cache if you use Windows 8, perform the following steps:
On your keyboard, press Win+X to open the WinX Menu.
Right-click Command Prompt and select Run as Administrator.
Run the following command:
ipconfig /flushdns
If the command succeeds, the system returns the following message:
Windows IP configuration successfully flushed the DNS Resolver Cache.
Windows® 7
To clear your DNS cache if you use Windows 7, perform the following steps:
Click Start.
Enter cmd in the Start menu search text box.
Right-click Command Prompt and select Run as Administrator.
Run the following command:
ipconfig /flushdns
If the command succeeds, the system returns the following message: Windows IP configuration successfully flushed the DNS Resolver Cache.
Simple way to initiate the message on startup:
bot.on('ready', () => {
bot.user.setStatus('available')
bot.user.setPresence({
game: {
name: 'with depression',
type: "STREAMING",
url: "https://www.twitch.tv/monstercat"
}
});
});
You can also just declare it elsewhere after startup, to change the message as needed:
bot.user.setPresence({ game: { name: 'with depression', type: "streaming", url: "https://www.twitch.tv/monstercat"}});
HTML5 Boilerplate has a nice pre-made code for console problems fixing:
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
As @plus- pointed in comments, latest version is available on their GitHub page
You can use below code
$.when( Typer() ).done(function() {
playBGM();
});
Unfortunately typescript does not support multiple inheritance. Therefore there is no completely trivial answer, you will probably have to restructure your program
Here are a few suggestions:
If this additional class contains behaviour that many of your subclasses share, it makes sense to insert it into the class hierarchy, somewhere at the top. Maybe you could derive the common superclass of Sprite, Texture, Layer, ... from this class ? This would be a good choice, if you can find a good spot in the type hirarchy. But I would not recommend to just insert this class at a random point. Inheritance expresses an "Is a - relationship" e.g. a dog is an animal, a texture is an instance of this class. You would have to ask yourself, if this really models the relationship between the objects in your code. A logical inheritance tree is very valuable
If the additional class does not fit logically into the type hierarchy, you could use aggregation. That means that you add an instance variable of the type of this class to a common superclass of Sprite, Texture, Layer, ... Then you can access the variable with its getter/setter in all subclasses. This models a "Has a - relationship".
You could also convert your class into an interface. Then you could extend the interface with all your classes but would have to implement the methods correctly in each class. This means some code redundancy but in this case not much.
You have to decide for yourself which approach you like best. Personally I would recommend to convert the class to an interface.
One tip: Typescript offers properties, which are syntactic sugar for getters and setters. You might want to take a look at this: http://blogs.microsoft.co.il/gilf/2013/01/22/creating-properties-in-typescript/
SQL is implemented as if a query was executed in the following order:
For most relational database systems, this order explains which names (columns or aliases) are valid because they must have been introduced in a previous step.
So in Oracle and SQL Server, you cannot use a term in the GROUP BY clause that you define in the SELECT clause because the GROUP BY is executed before the SELECT clause.
There are exceptions though: MySQL and Postgres seem to have additional smartness that allows it.
const button = document.getElementById(btnId);
button.addEventListener("click", function() {
// Submit form
}, {once : true});
// Disabling works too, but this is a more standard approach for general one-time events
There are several options to make curl output to a file
# saves it to myfile.txt
curl http://www.example.com/data.txt -o myfile.txt
# The #1 will get substituted with the url, so the filename contains the url
curl http://www.example.com/data.txt -o "file_#1.txt"
# saves to data.txt, the filename extracted from the URL
curl http://www.example.com/data.txt -O
# saves to filename determined by the Content-Disposition header sent by the server.
curl http://www.example.com/data.txt -O -J
Basically, parameters are user specified data to rails application.
When you post a form, you do it generally with POST request as opposed to GET request. You can think normal rails requests as GET requests, when you browse the site, if it helps.
When you submit a form, the control is thrown back to the application. How do you get the values you have submitted to the form? params
is how.
About your code. @vote = Vote.new params[:vote]
creates new Vote to database using data of params[:vote]. Given your form user submitted was named under name :vote, all data of it is in this :vote field of the hash.
Next two lines are used to get item and uid user has submitted to the form.
@extant = Vote.find(:last, :conditions => ["item_id = ? AND user_id = ?", item, uid])
finds newest, or last inserted, vote from database with conditions item_id = item and user_id = uid.
Next lines takes last vote time and current time.
put into javascript external file
(function ($) {
$(window).keydown(function (event) {
if (event.keyCode == 13) {
return false;
}
});
})(jQuery);
or somewhere inside body tag
<script>
$(document).ready(function() {
$(window).keydown(function(event) {
alert(1);
if(event.keyCode == 13) {
return false;
}
});
});
</script>
Here's the intended way to convert a String to a Date:
String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);
Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.
You should also try checking the error messages in curl_error(). You might need to do this once after each curl_* function.
Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):
In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.
Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.
In Python, overloading is not an applied concept. However, if you are trying to create a case where, for instance, you want one initializer to be performed if passed an argument of type foo
and another initializer for an argument of type bar
then, since everything in Python is handled as object, you can check the name of the passed object's class type and write conditional handling based on that.
class A:
def __init__(self, arg)
# Get the Argument's class type as a String
argClass = arg.__class__.__name__
if argClass == 'foo':
print 'Arg is of type "foo"'
...
elif argClass == 'bar':
print 'Arg is of type "bar"'
...
else
print 'Arg is of a different type'
...
This concept can be applied to multiple different scenarios through different methods as needed.
I find the existing explanations too gobbledygook. Here's my explanation in plain English:
STA: If a thread creates a COM object that's set to STA (when calling CoCreateXXX you can pass a flag that sets the COM object to STA mode), then only this thread can access this COM object (that's what STA means - Single Threaded Apartment), other thread trying to call methods on this COM object is under the hood silently turned into delivering messages to the thread that creates(owns) the COM object. This is very much like the fact that only the thread that created a UI control can access it directly. And this mechanism is meant to prevent complicated lock/unlock operations.
MTA: If a thread creates a COM object that's set to MTA, then pretty much every thread can directly call methods on it.
That's pretty much the gist of it. Although technically there're some details I didn't mention, such as in the 'STA' paragraph, the creator thread must itself be STA. But this is pretty much all you have to know to understand STA/MTA/NA.
as of 12.03.2019 FusionTables is no more...
Import the Shapefile into Google FusionTables ( http://www.google.com/fusiontables ) using http://www.shpescape.com/ and from there you can use the data in a number of ways, eg. display it using GoogleMaps.
I had the exact same issue. The following thread helped me solve it. Just set your Compile SDK version to Android P.
https://stackoverflow.com/a/49172361/1542720
I fixed this issue by selecting:
API 27+: Android API 27, P preview (Preview)
in the project structure settings. the following image shows my settings. The 13 errors that were coming while building the app, have disappeared.
In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.
Collections.addAll provides the shortest (one-line) receipt
Having
String[] array = {"foo", "bar", "baz"};
Set<String> set = new HashSet<>();
You can do as below
Collections.addAll(set, array);
The SublimeText 3 Column-Select plugin should be all you need. Install that, then make sure you have something like the following in your 'Default (OSX).sublime-keymap' file:
// Column mode
{ "keys": ["ctrl+alt+up"], "command": "column_select", "args": {"by": "lines", "forward": false}},
{ "keys": ["ctrl+alt+down"], "command": "column_select", "args": {"by": "lines", "forward": true}},
{ "keys": ["ctrl+alt+pageup"], "command": "column_select", "args": {"by": "pages", "forward": false}},
{ "keys": ["ctrl+alt+pagedown"], "command": "column_select", "args": {"by": "pages", "forward": true}},
{ "keys": ["ctrl+alt+home"], "command": "column_select", "args": {"by": "all", "forward": false}},
{ "keys": ["ctrl+alt+end"], "command": "column_select", "args": {"by": "all", "forward": true}}
What exactly about it did not work for you?
Async:
fs.readFile('test.txt', 'utf8', callback);
Sync:
var content = fs.readFileSync('test.txt', 'utf8');
body.addEventListener("load", init(), false);
That init() is saying run this function now and assign whatever it returns to the load event.
What you want is to assign the reference to the function, not the result. So you need to drop the ().
body.addEventListener("load", init, false);
Also you should be using window.onload and not body.onload
addEventListener
is supported in most browsers except IE 8.
I wrote this a long time ago (from years 1985-1992, with just a few tweaks since then), and just copy and paste the bits needed into each project.
You must call cfmakeraw
on a tty
obtained from tcgetattr
. You cannot zero-out a struct termios
, configure it, and then set the tty
with tcsetattr
. If you use the zero-out method, then you will experience unexplained intermittent failures, especially on the BSDs and OS X. "Unexplained intermittent failures" include hanging in read(3)
.
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int
set_interface_attribs (int fd, int speed, int parity)
{
struct termios tty;
if (tcgetattr (fd, &tty) != 0)
{
error_message ("error %d from tcgetattr", errno);
return -1;
}
cfsetospeed (&tty, speed);
cfsetispeed (&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr (fd, TCSANOW, &tty) != 0)
{
error_message ("error %d from tcsetattr", errno);
return -1;
}
return 0;
}
void
set_blocking (int fd, int should_block)
{
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
error_message ("error %d from tggetattr", errno);
return;
}
tty.c_cc[VMIN] = should_block ? 1 : 0;
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
if (tcsetattr (fd, TCSANOW, &tty) != 0)
error_message ("error %d setting term attributes", errno);
}
...
char *portname = "/dev/ttyUSB1"
...
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
error_message ("error %d opening %s: %s", errno, portname, strerror (errno));
return;
}
set_interface_attribs (fd, B115200, 0); // set speed to 115,200 bps, 8n1 (no parity)
set_blocking (fd, 0); // set no blocking
write (fd, "hello!\n", 7); // send 7 character greeting
usleep ((7 + 25) * 100); // sleep enough to transmit the 7 plus
// receive 25: approx 100 uS per char transmit
char buf [100];
int n = read (fd, buf, sizeof buf); // read up to 100 characters if ready to read
The values for speed are B115200
, B230400
, B9600
, B19200
, B38400
, B57600
, B1200
, B2400
, B4800
, etc. The values for parity are 0
(meaning no parity), PARENB|PARODD
(enable parity and use odd), PARENB
(enable parity and use even), PARENB|PARODD|CMSPAR
(mark parity), and PARENB|CMSPAR
(space parity).
"Blocking" sets whether a read()
on the port waits for the specified number of characters to arrive. Setting no blocking means that a read()
returns however many characters are available without waiting for more, up to the buffer limit.
Addendum:
CMSPAR
is needed only for choosing mark and space parity, which is uncommon. For most applications, it can be omitted. My header file /usr/include/bits/termios.h
enables definition of CMSPAR
only if the preprocessor symbol __USE_MISC
is defined. That definition occurs (in features.h
) with
#if defined _BSD_SOURCE || defined _SVID_SOURCE
#define __USE_MISC 1
#endif
The introductory comments of <features.h>
says:
/* These are defined by the user (or the compiler)
to specify the desired environment:
...
_BSD_SOURCE ISO C, POSIX, and 4.3BSD things.
_SVID_SOURCE ISO C, POSIX, and SVID things.
...
*/
Store your results in variables, and use them in your HTML and add the necessary styling.
$usercity = $ip['cityName'];
$usercountry = $ip['countryName'];
And in the HTML, you could do:
<div id="userdetails">
<p> User's IP: <?php echo $usercity; ?> </p>
<p> Country: <?php echo $usercountry; ?> </p>
</div>
Now, you can simply add the styles for country
class in your CSS, like so:
#userdetails {
/* styles go here */
}
Alternatively, you could also use this in your HTML:
<p style="font-size:15px; font-color: green;"><?php echo $userip; ?> </p>
<p style="font-size:15px; font-color: green;"><?php echo $usercountry; ?> </p>
Hope this helps!
Rename the Column by doing the following:
dataTable.Columns["ColumnName"].ColumnName = "newColumnName";
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
That depends on what headers you are sending along with your CSS files. Check your server configuration as you are probably not sending them manually. Do a google search for "http caching" to learn about different caching options you can set. You can force the browser to download a fresh copy of the file everytime it loads it for instance, or you can cache the file for one week...
Well yes arrays do exist, and no they're not different to lists when it comes to things like del
and append
:
>>> from array import array
>>> foo = array('i', range(5))
>>> foo
array('i', [0, 1, 2, 3, 4])
>>> del foo[:]
>>> foo
array('i')
>>> foo.append(42)
>>> foo
array('i', [42])
>>>
Differences worth noting: you need to specify the type when creating the array, and you save storage at the expense of extra time converting between the C type and the Python type when you do arr[i] = expression
or arr.append(expression)
, and lvalue = arr[i]
Yes, it does. The way to enable this depends on your version of Notepad++. On newer versions you can use:
Menu View ? Show Symbol ? *Show All Characters`
or
Menu View ? Show Symbol ? Show White Space and TAB
(Thanks to bers' comment and bkaid's answers below for these updated locations.)
On older versions you can look for:
Menu View ? Show all characters
or
Menu View ? Show White Space and TAB
synchronized
Java keyword worksWhen you add the synchronized
keyword to a static method, the method can only be called by a single thread at a time.
In your case, every method call will:
SessionFactory
Session
However, these were your requirements:
getObjectById
being called for all classes when it is called by a particular classSo, even if the getObjectById
method is thread-safe, the implementation is wrong.
SessionFactory
best practicesThe SessionFactory
is thread-safe, and it's a very expensive object to create as it needs to parse the entity classes and build the internal entity metamodel representation.
So, you shouldn't create the SessionFactory
on every getObjectById
method call.
Instead, you should create a singleton instance for it.
private static final SessionFactory sessionFactory = new Configuration()
.configure()
.buildSessionFactory();
Session
should always be closedYou didn't close the Session
in a finally
block, and this can leak database resources if an exception is thrown when loading the entity.
According to the Session.load
method JavaDoc might throw a HibernateException
if the entity cannot be found in the database.
You should not use this method to determine if an instance exists (use
get()
instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.
That's why you need to use a finally
block to close the Session
, like this:
public static synchronized Object getObjectById (Class objclass, Long id) {
Session session = null;
try {
session = sessionFactory.openSession();
return session.load(objclass, id);
} finally {
if(session != null) {
session.close();
}
}
}
In your case, you wanted to make sure only one thread gets access to that particular entity.
But the synchronized
keyword only prevents two threads from calling the getObjectById
concurrently. If the two threads call this method one after the other, you will still have two threads using this entity.
So, if you want to lock a given database object so no other thread can modify it, then you need to use database locks.
The synchronized
keyword only works in a single JVM. If you have multiple web nodes, this will not prevent multi-thread access across multiple JVMs.
What you need to do is use LockModeType.PESSIMISTIC_READ
or LockModeType.PESSIMISTIC_WRITE
while applying the changes to the DB, like this:
Session session = null;
EntityTransaction tx = null;
try {
session = sessionFactory.openSession();
tx = session.getTransaction();
tx.begin();
Post post = session.find(
Post.class,
id,
LockModeType.LockModeType.PESSIMISTIC_READ
);
post.setTitle("High-Performance Java Perisstence");
tx.commit();
} catch(Exception e) {
LOGGER.error("Post entity could not be changed", e);
if(tx != null) {
tx.rollback();
}
} finally {
if(session != null) {
session.close();
}
}
So, this is what I did:
EntityTransaction
and started a new database transactionPost
entity while holding a lock on the associated database recordPost
entity and committed the transactionException
being thrown, I rolled back the transactionprint('''first line \
second line''')
it will produce
first line second line
Maybe join
+split
:
>>> a=12345
>>> list(map(int,' '.join(str(a)).split()))
[1, 2, 3, 4, 5]
>>> [int(i) for i in ' '.join(str(a)).split()]
[1, 2, 3, 4, 5]
>>>
str.join
+ str.split
is your friend, also we use map
or list comprehension
to get a list, (split what we join :-)).
Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.
The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.
Changed if file not exists. Create empty file.
- name: create fake 'nologin' shell
file:
path: /etc/nologin
state: touch
register: p
changed_when: p.diff.before.state == "absent"
Note: The following method will work on windows.
An alternative method (if it is ok to run a single version of PHP at a time) is to define multiple Apache services, each of which will use a different PHP version.
First of all use conditions in the Apache configuration file:
<ifdefine php54>
SetEnv PHPRC C:/apache/php54/
ScriptAlias /php/ "C:/apache/php54/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>
<ifdefine php55>
SetEnv PHPRC C:/apache/php55/
ScriptAlias /php/ "C:/apache/php55/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>
Now using the httpd.exe create two separate services from command line (elevated to administrator):
httpd.exe -k install -n Apache224_php54 -D php54
httpd.exe -k install -n Apache224_php55 -D php55
Now you can start one of the above services at a time (should shutdown one before starting the other).
If you have previously installed Apache as service you can remove that using below command (replace the service name with the one you have used):
apache -k uninstall -n Apache224
One further note is that I personally use a "notification area icon program" called "Seobiseu" to start and stop services as needed. I have added the two above services to it.
commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable
.
Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable
, or in cases you don't want to implement Serializable
.
commons-beanutils BeanUtils - in most cases.
Spring BeanUtils - if you are already using spring and hence have this utility on the classpath.
I deliberately omitted the "do-it-yourself" option - the API's above provide a good control over what to and what not to clone (for example using transient
, or String[] ignoreProperties
), so reinventing the wheel isn't preferred.
use this
public static Set<Class> getExtendedClasses(Class superClass)
{
try
{
ResolverUtil resolver = new ResolverUtil();
resolver.findImplementations(superClass, superClass.getPackage().getName());
return resolver.getClasses();
}
catch(Exception e)
{Log.d("Log:", " Err: getExtendedClasses() ");}
return null;
}
getExtendedClasses(Animals.class);
Edit:
The getTimezoneOffset()
method in JavaScript, in a browser, returns the number of minutes offset from the 00:00 time zone. For example, America/New_York time zone in Daylight Savings (DST) returns the number 300. 300 minutes is 5 hours difference from zero. 300 minutes divided by 60 minutes is 5 hours. Every time zone is compared to the zero time zone, +00:00 / Etc/GMT / Greenwich time.
The next thing that you must know, is that the offset has the opposite sign of the actual time zone.
Information about time zones is maintained by the Internet Assigned Numbers Authority (iana)
A nicely formatted table of Time Zones is supplied by joda.org
+00:00 or Etc/GMT is Greenwich time
All time zones are offset from +00:00 / "Etc/GMT" / Greenwich time
Daylight Savings Time is always an earlier time than the "regular" time in the summer. You set your clocks back in the fall season. ("Fall Back" slogan to remember what to do)
So, America/New_York time in Daylight Savings (winter) is one hour before the regular time. So, for example, what was normally 5 p.m. in the afternoon in New York city in the summer, is now 4 p.m. America/New_York time in Daylight Savings. The name "America/New_York" time is a "Long Format" time zone name. The east coast of the U.S typically calls their time zone Eastern Standard Time (EST)
If you want to compare today's time zone offset to the time zone offset of some other date, you need to know that mathematical sign (+/- "Positive / Negative") of the time zone offset is the opposite of the time zone.
Look at the time zone table at joda.org and find the time zone for "America/New_York" It will have a negative sign in front of the Standard Offset.
The earth rotates counter-clockwise on it's axis. A person watch the sunrise in Greenwich sees the sunrise 5 hours before someone in New York City will see the sunrise. And someone on the West Coast of the U.S. will see the sunrise after someone on the East Coast of the U.S. sees the sunrise.
There's a reason why you need to know all of this. So that you'll be able to logically determine whether some JavaScript code is getting the DST status correctly or not, without needing to test every time zone at different times of the year.
Imagine that it's November in New York City, and the clocks have been set back an hour. In the summer in New York City, the offset is 240 minutes or 4 hours.
You can test this by creating a date that is in July and then getting the offset.
var July_Date = new Date(2017, 6, 1);
var july_Timezone_OffSet = July_Date.getTimezoneOffset();
console.log('july_Timezone_OffSet: ' + july_Timezone_OffSet)
What will print to the browser's developer tools console log?
Answer is: 240
So, now you can create a date in January and see what your browser returns for a time zone offset for the winter season.
var Jan_Date = new Date(2017, 0, 1);//Month is zero indexed - Jan is zero
var jan_Timezone_OffSet = Jan_Date.getTimezoneOffset();
console.log('jan_Timezone_OffSet: ' + jan_Timezone_OffSet)
Answer is: 300
Obviously 300 is bigger than 240. So, what does this mean? Should you write code that tests for the winter offset being bigger than the summer offset? Or the summer offset less than the winter offset? If there is a difference between the summer and winter time zone offsets, then you can assume that DST is being used for this time zone. But that doesn't tell you if today is using DST for the browsers time zone. So, you'll need to get the time zone offset for today.
var today = new Date();
var todaysTimeZone = today.getTimezoneOffset();
console.log('todaysTimeZone : ' + todaysTimeZone)
Answer is: ? - Depends on the time of year
If today's time zone offset and the summer time zone offset is the same, AND the summer and winter time zone offsets are different, then by logical deduction, today must be NOT be in DST.
Can you omit comparing the summer and winter time zone offsets, (To know if DST is used for this time zone) and just compare today's time zone offset to the summer TZ offset, and always get the correct answer?
today's TZ Offset !== Summer TZ Offset
Well, is today in the winter or summer? If you knew that then you could apply the following logic:
if ( it_is_winter && ( todays_TZ_Offset !== summer_TZ_Offset) {
var are_We_In_DST = true;
}
But the problem is, that you don't know if today's date is in winter or summer. Every time zone can have it's own rules for when DST starts and stops. You'd need to keep track of every time zone's rules for every time zone in the world. So, if there is a better and easier way then you might as well do it the better and easier way.
What we are left with, is that you need to know if this time zone uses DST, and then compare today's time zone offset with the summer time zone offset. That will always give you a reliable answer.
The final logic is:
if ( DST_Is_Used_In_This_Time_Zone && ( todays_TZ_Offset !== summer_TZ_Offset) {
var are_We_In_DST = true;
}
Function to determine if the time zone in the browser uses DST:
function is_DST_Used_In_This_TimeZone() {
var Jan_Date, jan_Timezone_OffSet, July_Date, july_Timezone_OffSet
offsetsNotEqual, thisYear, today;
today = new Date();//Create a date object that is now
thisYear = today.getFullYear();//Get the year as a number
Jan_Date = new Date(thisYear, 0, 1);//Month is zero indexed - Jan is zero
jan_Timezone_OffSet = Jan_Date.getTimezoneOffset();
console.log('jan_Timezone_OffSet: ' + jan_Timezone_OffSet)
July_Date = new Date(thisYear, 6, 1);
july_Timezone_OffSet = July_Date.getTimezoneOffset();
console.log('july_Timezone_OffSet: ' + july_Timezone_OffSet)
offsetsNotEqual = july_Timezone_OffSet !== jan_Timezone_OffSet;//True if not equal
console.log('offsetsNotEqual: ' + offsetsNotEqual);
return offsetsNotEqual;//If the offsets are not equal for summer and
//winter then the only possible reason is that DST is used for
//this time zone
}
You can count the frequency using two ways:
Using the count()
in str
:
a.count(b)
Or, you can use:
len(a.split(b))-1
Where a
is the string and b
is the substring whose frequency is to be calculated.
Simply use bootstrap-multiselect where you can populate dropdown with multiselect option and many more feaatures.
For doc and tutorials you may visit below link
.ToList returns an empty list. (same as new List() );
Add display: block;
and overflow: auto;
to .my-table
. This will simply cut off anything past the 280px
limit you enforced. There's no way to make it "look pretty" with that requirement due to words like pélagosthrough
which are wider than 280px
.
Java does not have this control structure.
It should be noted though, that other languages do.
Python for example, has the while-else construct.
In Java's case, you can mimic this behaviour as you have already shown:
if (rowIndex >= dataColLinker.size()) {
do {
dataColLinker.add(value);
} while(rowIndex >= dataColLinker.size());
} else {
dataColLinker.set(rowIndex, value);
}
In case you need a declarative solution, you can use dict.update()
to change values in a dict.
Either like this:
my_dict.update({'key1': 'value1', 'key2': 'value2'})
or like this:
my_dict.update(key1='value1', key2='value2')
Since Python 3.5 you can also use dictionary unpacking for this:
my_dict = { **my_dict, 'key1': 'value1', 'key2': 'value2'}
Note: This creates a new dictionary.
Since Python 3.9 you can also use the merge operator on dictionaries:
my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}
Note: This creates a new dictionary.
Or you can use the update operator:
my_dict |= {'key1': 'value1', 'key2': 'value2'}
I found a bug on Ankur answer and I've fixed it with this correction:
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Plz enter on Alphabets ')"
onchange="try{setCustomValidity('')}catch(e){}" />
The bug seen when you set an invalid input data, then correct the input and send the form. oops! you can't do this. I've tested it on firefox and chrome
You may use this following code actually it is rough but plz check it out
db = openOrCreateDatabase("sms.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor cc = db.rawQuery("SELECT * FROM datatable", null);
final ArrayList<String> row1 = new ArrayList<String>();
final ArrayList<String> row2 = new ArrayList<String>();
if(cc!=null) {
cc.moveToFirst();
startManagingCursor(cc);
for (int i=0; i<cc.getCount(); i++) {
String number = cc.getString(0);
String message = cc.getString(1);
row1.add(number);
row2.add(message);
final EditText et3 = (EditText) findViewById(R.id.editText3);
final EditText et4 = (EditText) findViewById(R.id.editText4);
Button bt1 = (Button) findViewById(R.id.button1);
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
et3.setText(row1.get(count));
et4.setText(row2.get(count));
count++;
break;
default:
break;
}
}
});
cc.moveToNext();
}
Often times we are interested in calculating the full significant digits, but for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.
In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style
.
For the case of just seeing two significant digits of some columns, we can use this code snippet:
import numpy as np
import pandas as pd
df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})
print(df)
var1 var2 var3
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
Gives:
var1 var2 var3
id
0 1.46 1.50 -0.57%
1 1.58 1.61 -0.51%
2 1.63 1.65 -0.48%
3 1.67 1.69 -0.35%
4 1.71 1.71 -0.31%
5 1.74 1.74 -0.12%
6 1.78 1.77 -0.17%
7 1.81 1.80 -0.20%
8 1.85 1.82 -0.14%
9 1.94 1.87 0.57%
If display command is not found try following:
from IPython.display import display
df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
display(df_style)
display
command, you need to have installed Ipython in your machine.display
command does not work in online python interpreter which do not have IPyton
installed such as https://repl.it/languages/python3The problem is that if you try to write a <table>
or a <tr>
or <td>
tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.
Instead of writing your table line by line, concatenate your table into a variable and insert it once created:
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2.218;
myArray[2] = 33;
myArray[3] = 114.94;
myArray[4] = 5;
myArray[5] = 33;
myArray[6] = 114.980;
myArray[7] = 5;
var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";
myTable+="<tr><td style='width: 100px; '>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td></tr>";
for (var i=0; i<8; i++) {
myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
myArray[i] = myArray[i].toFixed(3);
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
}
myTable+="</table>";
document.write( myTable);
//-->
</script>
If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:
<div id="tablePrint"> </div>
And in JS instead of document.write(myTable)
use the following code:
document.getElementById('tablePrint').innerHTML = myTable;
If you're using a JetBrains IDE (like IntelliJ IDEA, Android Studio, PyCharm), you can drag the patch file and drop it inside the IDE, and a dialog will appear, showing the patch's content. All you have to do now is to click "Apply patch", and a commit will be created.
For Microsoft, the answer is different. VS2013 is largely C99 compliant but "[t]he hh, j, z, and t length prefixes are not supported." For size_t "that is, unsigned __int32 on 32-bit platforms, unsigned __int64 on 64-bit platforms" use prefix I (capital eye) with type specifier o, u, x, or X. See VS2013 Size specification
As for off_t, it is defined as long in VC\include\sys\types.h.
For me the following command did the trick
sudo apt install php-mbstring
Floating point numbers (IEEE 754) are symmetrical, so if you can represent the greatest value (DBL_MAX
or numeric_limits<double>::max()
), just prepend a minus sign.
And then is the cool way:
double f;
(*((long long*)&f))= ~(1LL<<52);
As of Java 7, java.util.logging.SimpleFormatter supports getting its format from a system property, so adding something like this to the JVM command line will cause it to print on one line:
-Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
Alternatively, you can also add this to your logger.properties
:
java.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
In your pattern, you simply want to match all text between the two tags. Thus, you could use for example a [\w\W]
to match all characters.
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname>([\w\W]*?)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[1];
}
Hope below helps!
PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice
Now type is converted. You can use method or can access any property.
Example :$Format_date.AddDays(5)
If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.
usernameTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
}
});
SOLVED I struggled with this and later on, I realized that I was working on PHP 5.6, so I upgraded to PHP 7.0, then I released there were comments placed by git for conflicting codes. I found something like this in my code <<<<<<<< But solved it.
You are importing the module datetime, which doesn't have a strptime
function.
That module does have a datetime
object with that method though:
import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")
Alternatively you can import the datetime
object from the module:
from datetime import datetime
dtDate = datetime.strptime(sDate, "%m/%d/%Y")
Note that the strptime
method was added in python 2.5; if you are using an older version use the following code instead:
import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])
All you want is the below regex:
^\d+$
In SQL server 2012, below can be used
select FORMAT(getdate(), 'MMM yyyy')
This gives exact "Jun 2016"
You can fix it like this:
$scope.hoverIn = function(){
this.hoverEdit = true;
};
$scope.hoverOut = function(){
this.hoverEdit = false;
};
Inside of ngMouseover (and similar) functions context is a current item scope, so this refers to the current child scope.
Also you need to put ngRepeat
on li
:
<ul>
<li ng-repeat="task in tasks" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
{{task.name}}
<span ng-show="hoverEdit">
<a>Edit</a>
</span>
</li>
</ul>
However, when possible try to do such things with CSS only, this would be the optimal solution and no JS required:
ul li span {display: none;}
ul li:hover span {display: inline;}
I hate answering my own question, but @Matt Bodily put me on the right track.
The @Html.Action
method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" })
does indeed return the URL, but I finally discovered an overload of Html.ActionLink
that provided a better solution for my case:
@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)
Note: , null
is significant in this case, to match the right signature.
Documentation: @Html.ActionLink (LinkExtensions.ActionLink)
Documentation for this particular overload:
LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)
It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.
Still marking Matt's response as the answer.
Edit: Found yet another HTML helper to solve this:
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
Get Version using this.getClass().getPackage().getImplementationVersion()
PS Don't forget to add:
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
I was looking for an ExecutorService that can interrupt all timed out Runnables executed by it, but found none. After a few hours I created one as below. This class can be modified to enhance robustness.
public class TimedExecutorService extends ThreadPoolExecutor {
long timeout;
public TimedExecutorService(int numThreads, long timeout, TimeUnit unit) {
super(numThreads, numThreads, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(numThreads + 1));
this.timeout = unit.toMillis(timeout);
}
@Override
protected void beforeExecute(Thread thread, Runnable runnable) {
Thread interruptionThread = new Thread(new Runnable() {
@Override
public void run() {
try {
// Wait until timeout and interrupt this thread
Thread.sleep(timeout);
System.out.println("The runnable times out.");
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
interruptionThread.start();
}
}
Usage:
public static void main(String[] args) {
Runnable abcdRunnable = new Runnable() {
@Override
public void run() {
System.out.println("abcdRunnable started");
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
// logger.info("The runnable times out.");
}
System.out.println("abcdRunnable ended");
}
};
Runnable xyzwRunnable = new Runnable() {
@Override
public void run() {
System.out.println("xyzwRunnable started");
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
// logger.info("The runnable times out.");
}
System.out.println("xyzwRunnable ended");
}
};
int numThreads = 2, timeout = 5;
ExecutorService timedExecutor = new TimedExecutorService(numThreads, timeout, TimeUnit.SECONDS);
timedExecutor.execute(abcdRunnable);
timedExecutor.execute(xyzwRunnable);
timedExecutor.shutdown();
}
Answered the same question here:
To repost:
After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...
Html
<div class="item" data-order="2">2</div> <div class="item" data-order="1">1</div> <div class="item" data-order="4">4</div> <div class="item" data-order="3">3</div>
Plain jquery selector
$('.item');
[<div class="item" data-order="2">2</div>, <div class="item" data-order="1">1</div>, <div class="item" data-order="4">4</div>, <div class="item" data-order="3">3</div> ]
Lets sort this by data-order
function getSorted(selector, attrName) { return $($(selector).toArray().sort(function(a, b){ var aVal = parseInt(a.getAttribute(attrName)), bVal = parseInt(b.getAttribute(attrName)); return aVal - bVal; })); }
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>, <div class="item" data-order="2">2</div>, <div class="item" data-order="3">3</div>, <div class="item" data-order="4">4</div> ]
Hope this helps!
In windows you should use %WORKSPACE%
.
I had to delay a form submission in jQuery in order to execute an asynchronous call. Here's the simplified code...
$("$theform").submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax('/path/to/script.php',
{
type: "POST",
data: { value: $("#input_control").val() }
}).done(function(response) {
$this.unbind('submit').submit();
});
});
This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery
SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )
@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :
<h:inputHidden value="#{loginBean.loginStatus}"/>
and in your bean code:
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public String getLoginStatus() {
// Do your stuff here.
return loginStatus;
}
The issue is caused because of event bubbling. The first part of your code to add .grown
works fine.
The second part "removing grown class" on clicking the link doesn't work as expected as both the handler for .close_button
and .clickable
are executed. So it removes and readd the grown
class to the div
.
You can avoid this by using e.stopPropagation()
inside .close_button
click handler to avoid the event from bubbling.
DEMO: http://jsfiddle.net/vL8DP/
Full Code
$(document).on('click', '.clickable', function () {
$(this).addClass('grown').removeClass('spot');
}).on('click', '.close_button', function (e) {
e.stopPropagation();
$(this).closest('.clickable').removeClass('grown').addClass('spot');
});
Since React Native 0.4.3 you can read your local JSON file like this:
const customData = require('./customData.json');
and then access customData like a normal JS object.
create table #Temp
(
EventID int,
EventTitle Varchar(50),
EventStartDate DateTime,
EventEndDate DatetIme,
EventEnumDays int,
EventStartTime Datetime,
EventEndTime DateTime,
EventRecurring Bit,
EventType int
)
;WITH Calendar
AS (SELECT /*...*/)
Insert Into #Temp
Select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle
,EventType from Calendar
where (PlannedDate >= GETDATE()) AND ',' + EventEnumDays + ',' like '%,' + cast(datepart(dw, PlannedDate) as char(1)) + ',%'
or EventEnumDays is null
Make sure that the table is deleted after use
If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
Drop Table #Temp
End
If you need to store a password in memory and would like to have it encrypted you should use SecureString:
http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx
For more general uses I would use a FIPS approved algorithm such as Advanced Encryption Standard, formerly known as Rijndael. See this page for an implementation example:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx
You need a different seed at every execution.
You can start to call at the beginning of your program:
srand(time(NULL));
Note that % 10
yields a result from 0
to 9
and not from 1
to 10
: just add 1
to your %
expression to get 1
to 10
.
Inspired by Robert K's solution, strips html tags and prevents executing scripts and eventhandlers like: <img src=fake onerror="prompt(1)">
Tested on latest Chrome, FF, IE (should work from IE9, but haven't tested).
var decodeEntities = (function () {
//create a new html document (doesn't execute script tags in child elements)
var doc = document.implementation.createHTMLDocument("");
var element = doc.createElement('div');
function getText(str) {
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
return str;
}
function decodeHTMLEntities(str) {
if (str && typeof str === 'string') {
var x = getText(str);
while (str !== x) {
str = x;
x = getText(x);
}
return x;
}
}
return decodeHTMLEntities;
})();
Simply call:
decodeEntities('<img src=fake onerror="prompt(1)">');
decodeEntities("<script>alert('aaa!')</script>");
You will need to put a quote at the beginning of your first text and the end of your last.
According to www.mcafeesecure.com General Solution for vulnerable to cross-site scripting (XSS) filter function can be:
function xss_cleaner($input_str) {
$return_str = str_replace( array('<','>',"'",'"',')','('), array('<','>',''','"',')','('), $input_str );
$return_str = str_ireplace( '%3Cscript', '', $return_str );
return $return_str;
}
It looks like for iOS 6, Apple is recommending you use the NSUUID class.
From the message now in the UIDevice docs for uniqueIdentifier
property:
Deprecated in iOS 5.0. Use the identifierForVendor property of this class or the advertisingIdentifier property of the ASIdentifierManager class instead, as appropriate, or use the UUID method of the NSUUID class to create a UUID and write it to the user defaults database.
You can try this:
const data = {
name : "Test",
value: 12
}
if("name" in data){
//Found
}
else {
//Not found
}
I have to add BINARY to the ColumnX, to get result as case sensitive
SELECT * FROM MyTable WHERE BINARY(ColumnX) REGEXP '^[a-z]';
try setting AutoPostBack="True"
on the DropDownList.
This is a work around.
[EDIT]
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<table cellspacing="1" width="100%" bgcolor="#cccccc">
<thead>
<tr>
<td bgcolor="#ffffff" width="70px">
</td>
<td class="csstablelisttd" width="70px">
<b>Time Slot </b>
</td>
<td class="csstablelisttd">
<b> Patient Name</b>
</td>
</tr>
</thead>
</table>
<!-- THIS GIVES THE SCROLLER -->
<div style="height: 500px; overflow-y: auto">
<table id="tableAppointment" cellspacing="1" width="100%" bgcolor="#cccccc">
<tbody>
<tr>
<td class="csstablelisttd" valign="top" width="70px">
8:00AM
</td>
<td class="csstablelisttd" width="70px">
0
</td>
<td class="csstablelisttd">
<span>Name 1</span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
9:00AM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
10:00AM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
11:00AM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
12:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
01:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
02:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
03:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
04:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
05:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
06:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
07:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
08:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
A LINQ approach:
string s = "This is a Test String.\n This is a next line.\t This is a tab.\n'";
string s1 = String.Join("", s.Where(c => c != '\n' && c != '\r' && c != '\t'));
For all who came here from google and are using an anchor element for firing the event, please make sure to void the click likewise:
<a
href='javascript:void(0)'
onclick='javascript:whatever causing the page to scroll to the top'
></a>
I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.
Try Find out divs height and setting div height (Similar to the one Matt posted but using a loop)
For Scala >= 2.12, use Source.fromResource
:
scala.io.Source.fromResource("located_in_resouces.any")
To align horizontally it's pretty straight forward:
<style type="text/css">
body {
margin: 0;
padding: 0;
text-align: center;
}
.bodyclass #container {
width: ???px; /*SET your width here*/
margin: 0 auto;
text-align: left;
}
</style>
<body class="bodyclass ">
<div id="container">type your content here</div>
</body>
and for vertical align, it's a bit tricky: here's the source
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Universal vertical center with CSS</title>
<style>
.greenBorder {border: 1px solid green;} /* just borders to see it */
</style>
</head>
<body>
<div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
<div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
<div class="greenBorder" style=" #position: relative; #top: -50%">
any text<br>
any height<br>
any content, for example generated from DB<br>
everything is vertically centered
</div>
</div>
</div>
</body>
</html>
You inherit class attributes, not class constructors .This is how it goes :
If no constructor is added in the super class, if no then the compiler adds a no argument contructor. This default constructor is invoked implicitly whenever a new instance of the sub class is created . Here the sub class may or may not have constructor, all is ok .
if a constructor is provided in the super class, the compiler will see if it is a no arg constructor or a constructor with parameters.
if no args, then the compiler will invoke it for any sub class instanciation . Here also the sub class may or may not have constructor, all is ok .
if 1 or more contructors in the parent class have parameters and no args constructor is absent, then the subclass has to have at least 1 constructor where an implicit call for the parent class construct is made via super (parent_contractor params) .
this way you are sure that the inherited class attributes are always instanciated .
First declare UIImageView and give it frame
UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake( 10.0f, 15.0f, 40.0f,40.0f )];
[imageView setBackgroundColor: [UIColor clearColor]];
[imageView setImage:[UIImage imageNamed:@"comments_profile_image.png"]];
[self.view addSubview: imageView];
This answer is late but might be helpful to anyone who arrives from Google: You might well need to declare
<item name="android:windowActionBar">true</item>
in your styles.xml
. It seems false
can be the default. You also need to be on API 11 or higher.
More details can be found in the documentation here. Specifically, quote:
Tip: If you have a custom activity theme in which you'd like to remove the action bar, set the android:windowActionBar style property to false. However, if you remove the action bar using a theme, then the window will not allow the action bar at all, so you cannot add it later—calling getActionBar() will return null.
What is a practical, real world example of the Linked List?
The simplest and most straightforward is a train.
Train cars are linked in a specific order so that they may be loaded, unloaded, transferred, dropped off, and picked up in the most efficient manner possible.
For instance, the Jiffy Mix plant needs sugar, flour, cornmeal, etc. Just around the bend might be a paper processing plant that needs chlorine, sulfuric acid, and hydrogen.
Now, we can stop the train, unload each car of its contents, then let the train go on, but then everything else on the train has to sit while flour is sucked out of the caisson, then the sugar, etc.
Instead, the cars are loaded on the train in order so that a whole chunk of it can be detached, and the remainder of the train moves on.
The end of the train is easier to detach than a portion in the middle, and vastly easier than detaching a few cars in one spot, and a few cars in another spot.
If needed, however, you can insert and remove items at any point in the train.
Much like a linked list.
-Adam
I know this is an old question. But I too needed the same one recently, and I got this question from stackoverflow + another answer from this blog. The answer which was in the blog was more straight forward as it focuses specially for this kind of a validation. Here is how to do it.
$.validator.addClassRules("price", {
required: true,
minlength: 2
});
This method does not require you to have validate method above this call.
Hope this will help someone in the future too. Source here.
In lldb as of beta 5, you can see the class of an object with the command:
fr v -d r shipDate
which outputs something like:
(DBSalesOrderShipDate_DBSalesOrderShipDate_ *) shipDate = 0x7f859940
The command expanded out means something like:
Frame Variable
(print a frame variable) -d run_target
(expand dynamic types)
Something useful to know is that using "Frame Variable" to output variable values guarantees no code is executed.
I would just query for the for
attribute instead of repetitively recursing the DOM tree.
$("input:checkbox").on("change", function() {
$("label[for='"+this.id+"']").text("TESTTTT");
});
Without script:
<form action="where-you-want-to-go"><input type="submit"></form>
Better yet, since you are just going somewhere, present the user with the standard interface for "just going somewhere":
<a href="where-you-want-to-go">ta da</a>
Although, the context sounds like "Simulate a normal search where the user submits a form", in which case the first option is the way to go.
cd ios && rm Podfile.lock && pod install
worked for me.
I believe the action name is "workbench.action.quickOpen".
If you are on the first line, pressing (upper case) J will join that line and the next line together, removing the newline. You can also combine this with a count, so pressing 3J
will combine all 3 lines together.
Complementing the @DanielLew answer, to get the values of the parameteres you have to do this:
URI example: myapp://path/to/what/i/want?keyOne=valueOne&keyTwo=valueTwo
in your activity:
Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
String valueOne = uri.getQueryParameter("keyOne");
String valueTwo = uri.getQueryParameter("keyTwo");
}
This is an Android 8 update.
In earlier version of Android, to LoadLibrary native shared libraries (for access via JNI for example) I hard-wired my native code to iterate through a range of potential directory paths for the lib folder, based on the various apk installation/upgrade algorithms:
/data/data/<PackageName>/lib
/data/app-lib/<PackageName>-1/lib
/data/app-lib/<PackageName>-2/lib
/data/app/<PackageName>-1/lib
/data/app/<PackageName>-2/lib
This approach is hokey and will not work for Android 8; from https://developer.android.com/about/versions/oreo/android-8.0-changes.html you'll see that as part of their "Security" changes you now need to use sourceDir:
"You can no longer assume that APKs reside in directories whose names end in -1 or -2. Apps should use sourceDir to get the directory, and not rely on the directory format directly."
Correction, sourceDir is not the way to find your native shared libraries; use something like. Tested for Android 4.4.4 --> 8.0
// Return Full path to the directory where native JNI libraries are stored.
private static String getNativeLibraryDir(Context context) {
ApplicationInfo appInfo = context.getApplicationInfo();
return appInfo.nativeLibraryDir;
}
This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.
So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader
instance. Any time you are creating a Reader
from an InputStream
, you need to specify the character encoding, or java.nio.charset.Charset
instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8
). If you don't specify a Charset
, Java will use your platform default encoding, which on Windows is usually CP-1252.
GitHub has a nice section called "Dealing with “non-fast-forward” errors"
This error can be a bit overwhelming at first, do not fear.
Simply put, git cannot make the change on the remote without losing commits, so it refuses the push.
Usually this is caused by another user pushing to the same branch. You can remedy this by fetching and merging the remote branch, or using pull to perform both at once.In other cases this error is a result of destructive changes made locally by using commands like
git commit --amend
orgit rebase
.
While you can override the remote by adding--force
to thepush
command, you should only do so if you are absolutely certain this is what you want to do.
Force-pushes can cause issues for other users that have fetched the remote branch, and is considered bad practice. When in doubt, don’t force-push.
Git cannot make changes on the remote like a fast-forward merge, which a Visual Git Reference illustrates like:
This is not exactly your case, but helps to see what "fast-forward" is (where the HEAD
of a branch is simply moved to a new more recent commit).
The "branch master->master (non-fast-forward) Already-up-to-date
" is usually for local branches which don't track their remote counter-part.
See for instance this SO question "git pull says up-to-date but git push rejects non-fast forward".
Or the two branches are connected, but in disagreement with their respective history:
See "Never-ending GIT story - what am I doing wrong here?"
This means that your subversion branch and your remote git master branch do not agree on something.
Some change was pushed/committed to one that is not in the other.
Fire upgitk --all
, and it should give you a clue as to what went wrong - look for "forks" in the history.
If you bracket the @ you can use it directly
declare @TEMP table (ID int, Name varchar(max))
insert into @temp values (1,'one'), (2,'two')
SELECT * FROM @TEMP
WHERE [@TEMP].[ID] = 1
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
Edit: Jakub Narebski has more git-fu. The following much simpler command works perfectly:
git describe --tags
(Or without the --tags
if you have checked out an annotated tag. My tag is lightweight, so I need the --tags.)
original answer follows:
git describe --exact-match --tags $(git log -n1 --pretty='%h')
Someone with more git-fu may have a more elegant solution...
This leverages the fact that git-log
reports the log starting from what you've checked out. %h
prints the abbreviated hash. Then git describe --exact-match --tags
finds the tag (lightweight or annotated) that exactly matches that commit.
The $()
syntax above assumes you're using bash or similar.
Consider the fast FILTER method:
$('.rnd').filter('h2,h4')
returns:
[<h2 id=?"foo" class=?"rnd">?Second?</h2>?, <h4 id=?"bar" class=?"rnd">?Fourth?</h4>?]
so:
$('.rnd').filter('h2,h4').each(function() { /*...$(this)...*/ });
Try this:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" value="Change option to 2" onclick="changeOpt()"/>
<script>
function changeOpt(){
document.getElementById("sel").options[1].selected = true;
alert("changed")
}
</script>
I would first want to know what you are trying to accomplish here to need an argument to be passed to new Runnable() or to run(). The usual way should be to have a Runnable object which passes data(str) to its threads by setting member variables before starting. The run() method then uses these member variable values to do execute someFunc()
Following is a free list of tools you can use to check, test and verify your JS code:
Hope this helps.
From the doc for path.resolve
:
The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.
But path.join
keeps trailing slashes
So
__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'
Not for nothing, but you shouldn't just automatically use the latest library. If they release the newest library tomorrow and it breaks some of your scripts, you are SOL, but if you use the library you used to develop the scripts, you will ensure they will work.
I personally prefer the "boolean1 ^ boolean2" expression due to its succinctness.
If I was in your situation (working in a team), I would strike a compromise by encapsulating the "boolean1 ^ boolean2" logic in a function with a descriptive name such as "isDifferent(boolean1, boolean2)".
For example, instead of using "boolean1 ^ boolean2", you would call "isDifferent(boolean1, boolean2)" like so:
if (isDifferent(boolean1, boolean2))
{
//do it
}
Your "isDifferent(boolean1, boolean2)" function would look like:
private boolean isDifferent(boolean1, boolean2)
{
return boolean1 ^ boolean2;
}
Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression "(boolean1 && !boolean2) || (boolean2 && !boolean1)"!
This problem occurs due to missing import of FormsModule,ReactiveFormsModule .I also came with same problem. My case was diff. as i was working with modules.So i missed above imports in my parent modules though i had imported it into child modules,it wasn't working.
Then i imported it into my parent modules as below, and it worked!
import { ReactiveFormsModule,FormsModule } from '@angular/forms';
import { AlertModule } from 'ngx-bootstrap';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
],
declarations: [MyComponent]
})
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?
) as the request body.
This requires Content-Type
and Content-Length
headers, so the receiving server knows how to interpret the incoming data. (*)
var querystring = require('querystring');
var http = require('http');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded
for the traditional format that a standard HTML form would use.
It's easy to send JSON (application/json
) in exactly the same manner; just JSON.stringify()
the data beforehand.
URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.
The bottom line is: The server must be able to interpret the content type in question. It could be text/plain
or anything else; there is no need to convert data if the receiving server understands it as it is.
Add a charset parameter (e.g. application/json; charset=Windows-1252
) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
sys.argv[0]
is not the first argument but the filename of the python program you are currently executing. I think you want sys.argv[1]
There is no default database for user. There is default database for current session.
You can get it using DATABASE() function -
SELECT DATABASE();
And you can set it using USE statement -
USE database1;
You should set it manually - USE db_name
, or in the connection string.
I got this working with the following directive:
app.directive('datatableSetup', function () {
return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});
And in the HTML:
<table class="table table-hover dataTable dataTable-columnfilter " datatable-setup="">
trouble shooting if the above doesnt work for you.
1) note that 'datatableSetup' is the equivalent of 'datatable-setup'. Angular changes the format into camel case.
2) make sure that app is defined before the directive. e.g. simple app definition and directive.
var app = angular.module('app', []);
app.directive('datatableSetup', function () {
return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});
My general rule of thumb is to use Get when you are making requests to the server that aren't going to alter state. Posts are reserved for requests to the server that alter state.
I have tried all of these solutions and none worked. After some trial and error I figured it out.
<style type="text/css">
#map_canvas {
line-height:normal;
}
</style>
Set line-height:normal for the map canvas div.
The first answer will print a string with prefix b'. That means your string will be like this b'your_string' To solve this issue please add the following line of code.
encoded_string= base64.b64encode(img_file.read())
print(encoded_string.decode('utf-8'))
The right way is to fix the overflow, but....
You can give yourself a bigger stack:-
using System.Threading;
Thread T = new Thread(threadDelegate, stackSizeInBytes);
T.Start();
You can use System.Diagnostics.StackTrace FrameCount property to count the frames you've used and throw your own exception when a frame limit is reached.
Or, you can calculate the size of the stack remaining and throw your own exception when it falls below a threshold:-
class Program
{
static int n;
static int topOfStack;
const int stackSize = 1000000; // Default?
// The func is 76 bytes, but we need space to unwind the exception.
const int spaceRequired = 18*1024;
unsafe static void Main(string[] args)
{
int var;
topOfStack = (int)&var;
n=0;
recurse();
}
unsafe static void recurse()
{
int remaining;
remaining = stackSize - (topOfStack - (int)&remaining);
if (remaining < spaceRequired)
throw new Exception("Cheese");
n++;
recurse();
}
}
Just catch the Cheese. ;)
See Math.Pow. The function takes a value and raises it to a specified power:
Math.Pow(100.00, 3.00); // 100.00 ^ 3.00
This is really just an expansion of BBB's answer which lead to to get my experiment working.
This script will simply create a file /tmp/testfile when you click on the button that says "Open Script".
This requires 3 files.
The File Tree:
root@test:/var/www/html# tree testscript/
testscript/
+-- index.html
+-- testexec.php
+-- test.sh
1. The main WebPage:
root@test:/var/www/html# cat testscript/index.html
<form action="/testscript/testexec.php">
<input type="submit" value="Open Script">
</form>
2. The PHP Page that runs the script and redirects back to the main page:
root@test:/var/www/html# cat testscript/testexec.php
<?php
shell_exec("/var/www/html/testscript/test.sh");
header('Location: http://192.168.1.222/testscript/index.html?success=true');
?>
3. The Script :
root@test:/var/www/html# cat testscript/test.sh
#!/bin/bash
touch /tmp/testfile
Combining much of above here is my real practical example, selecting records based on both meterid & timestamp. I have needed this command for years. Executes really quickly.
mysqldump -uuser -ppassword main_dbo trHourly --where="MeterID =5406 AND TIMESTAMP<'2014-10-13 05:00:00'" --no-create-info --skip-extended-insert | grep '^INSERT' > 5406.sql
I seem to have a blind spot as regards your html structure, but I think that this is what you're looking for. It should find the currently-selected option from the select
input, assign its text to the newVal
variable and then apply that variable to the value
attribute of the #costLabel
label:
$(document).ready(
function() {
$('select[name=package]').change(
function(){
var newText = $('option:selected',this).text();
$('#costLabel').text('Total price: ' + newText);
}
);
}
);
<form name="thisForm" id="thisForm" action="#" method="post">
<fieldset>
<select name="package" id="package">
<option value="standard">Standard - €55 Monthly</option>
<option value="standardAnn">Standard - €49 Monthly</option>
<option value="premium">Premium - €99 Monthly</option>
<option value="premiumAnn" selected="selected">Premium - €89 Monthly</option>
<option value="platinum">Platinum - €149 Monthly</option>
<option value="platinumAnn">Platinum - €134 Monthly</option>
</select>
</fieldset>
<fieldset>
<label id="costLabel" name="costLabel">Total price: </label>
</fieldset>
</form>
Working demo of the above at: JS Bin
One of the best tools is using the Debugging Tools for Windows, and taking a memory dump of the process using adplus, then use windbg and the sos plugin to analyze the process memory, threads, and call stacks.
You can use this method for identifying problems on servers too, after installing the tools, share the directory, then connect to the share from the server using (net use) and either take a crash or hang dump of the process.
Then analyze offline.
Is sku
just a property of the Product
model? If so:
$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();
foreach ($products as $product ) {
// Access $product->sku here...
}
Or is sku
a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.
I was still getting these errors even after confirming that the correct python
and pylint
were being used from my virtual env.
Eventually I figured out that in Visual Studio Code I was A) opening my project directory, which is B) where my Python virtual environment was, but I was C) running my main Python program from two levels deeper. Those three things need to be in sync for everything to work.
Here's what I would recommend:
In Visual Studio Code, open the directory containing your main Python program. (This may or may not be the top level of the project directory.)
Select Terminal menu > New Terminal, and create an virtual environment directly inside the same directory.
python3 -m venv env
Install pylint in the virtual environment. If you select any Python file in the sidebar, Visual Studio Code will offer to do this for you. Alternatively, source env/bin/activate
then pip install pylint
.
In the blue bottom bar of the editor window, choose the Python interpreter env/bin/python
. Alternatively, go to Settings and set "Python: Python Path." This sets python.pythonPath
in Settings.json.
Extend LinearLayout/RelativeLayout and use it straight on the XML
package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
Paint paint;
public LinearLayoutOutlined(Context context) {
super(context);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
public LinearLayoutOutlined(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
/*
Paint fillPaint = paint;
fillPaint.setARGB(255, 0, 255, 0);
fillPaint.setStyle(Paint.Style.FILL);
canvas.drawPaint(fillPaint) ;
*/
Paint strokePaint = paint;
strokePaint.setARGB(255, 255, 0, 0);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Rect r = canvas.getClipBounds() ;
Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
canvas.drawRect(outline, strokePaint) ;
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.pkg_name.LinearLayoutOutlined
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=...
android:layout_height=...
>
... your widgets here ...
</com.pkg_name.LinearLayoutOutlined>
Try this:
var t = this.Controls.OfType<TextBox>().AsEnumerable<TextBox>();
foreach (TextBox item in t)
{
item.Text = "";
}
I have added xml snippet to make a textview center alligned in both Linear and Relative Layout.
In Linear Layout
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text In Center"
android:layout_gravity="center"
android:gravity="center"/>
In Relative Layout
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text In Center"
android:layout_centerInParent= true/>
You need to use css-loader when creating bundle with webpack.
Install it:
npm install css-loader --save-dev
And add it to loaders in your webpack configs:
module.exports = {
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" },
// ...
]
}
};
After this, you will be able to include css files in js.
UIView's pointInside:withEvent: could be a good solution. Will return a boolean value indicating wether or not the given CGPoint is in the UIView instance you are using. Example:
UIView *aView = [UIView alloc]initWithFrame:CGRectMake(0,0,100,100);
CGPoint aPoint = CGPointMake(5,5);
BOOL isPointInsideView = [aView pointInside:aPoint withEvent:nil];
You can used following code that can solve your problem.
Matrix matrix = new Matrix();
matrix.postScale(0.5f, 0.5f);
Bitmap croppedBitmap = Bitmap.createBitmap(bitmapOriginal, 100, 100,100, 100, matrix, true);
Above method do postScalling of image before cropping, so you can get best result with cropped image without getting OOM error.
For more detail you can refer this blog
Instead of typedef struct { ... } pos;
you should be doing struct pos { ... };
. The issue here is that you are using the pos
type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.
Further, the typedef struct { ... } name;
pattern is a C-ism, and doesn't have much place in C++.
To answer your question about inline
, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline
, the compiler effectively ignores it because the method is already declared inline.
(inline
methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)
This has worked for me in turning "//"
into just "/"
.
str.replace(/\/\//g, '/');
In the same way just get their other numbers using the other "People" references
People.TYPE_HOME
People.TYPE_MOBILE
People.TYPE_OTHER
People.TYPE_WORK
Much simpler to my opinion:
sed -r 's/\s+//g' filename
Use the @RequestParam to pass a parameter to the controller handler method.
In the jsp your form should have an input field with name = "id"
like the following:
<input type="text" name="id" />
<input type="submit" />
Then in your controller, your handler method should be like the following:
@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
Person person = personService.getCurrentlyAuthenticatedUser();
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
return "note";
}
Please also refer to these answers and tutorial:
A YAML sequence is an array. So this is the right way to express it:
key:
- string1
- string2
- string3
- string4
- string5
- string6
That's identical in meaning to:
key: ['string1', 'string2', 'string3', 'string4', 'string5', 'string6']
It's also legal to split a single-line array over several lines:
key: ['string1', 'string2', 'string3',
'string4', 'string5',
'string6']
and even have multi-line strings in single-line arrays:
key: ['string1', 'long
string', 'string3', 'string4', 'string5', 'string6']
git merge --abort
Abort the current conflict resolution process, and try to reconstruct the pre-merge state.
If there were uncommitted worktree changes present when the merge started,
git merge --abort
will in some cases be unable to reconstruct these changes. It is therefore recommended to always commit or stash your changes before running git merge.
git merge --abort
is equivalent togit reset --merge
whenMERGE_HEAD
is present.
To create list of lists, you need to separate them with commas, like this
coin_args = [
["pennies", '2.5', '50.0', '.01'],
["nickles", '5.0', '40.0', '.05'],
["dimes", '2.268', '50.0', '.1'],
["quarters", '5.67', '40.0', '.25']
]
"How do I for example read a 3 bit integer value starting at the second bit?"
int number = // whatever;
uint8_t val; // uint8_t is the smallest data type capable of holding 3 bits
val = (number & (1 << 2 | 1 << 3 | 1 << 4)) >> 2;
(I assumed that "second bit" is bit #2, i. e. the third bit really.)
The client_id
and client_secret
, by default, should go in the Authorization header, not the form-urlencoded body.
client_id
and client_secret
, with a colon between them: [email protected]:12345678
.YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==
Authorization: Basic YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
Sounds like your initialized AudioElement
class and the event listener belong within a component rather than in state. Within the event listener you can dispatch an action, which will update progress
in state.
You can either initialize the AudioElement
class object in a new React component or just convert that class to a React component.
class MyAudioPlayer extends React.Component {
constructor(props) {
super(props);
this.player = new AudioElement('test.mp3');
this.player.audio.ontimeupdate = this.updateProgress;
}
updateProgress () {
// Dispatch action to reducer with updated progress.
// You might want to actually send the current time and do the
// calculation from within the reducer.
this.props.updateProgressAction();
}
render () {
// Render the audio player controls, progress bar, whatever else
return <p>Progress: {this.props.progress}</p>;
}
}
class MyContainer extends React.Component {
render() {
return <MyAudioPlayer updateProgress={this.props.updateProgress} />
}
}
function mapStateToProps (state) { return {}; }
return connect(mapStateToProps, {
updateProgressAction
})(MyContainer);
Note that the updateProgressAction
is automatically wrapped with dispatch
so you don't need to call dispatch directly.
The situation never really applies to plural.
An enum
shows an attribute of something or another. I'll give an example:
enum Humour
{
Irony,
Sarcasm,
Slapstick,
Nothing
}
You can have one type, but try think of it in the multiple, rather than plural:
Humour.Irony | Humour.Sarcasm
Rather than
Humours { Irony, Sarcasm }
You have a sense of humour, you don't have a sense of humours.
IValueConverter implementation can be used. Converter class which takes inheritance from IValueConverter takes some parameters like value
(percentage) and parameter
(parent's width) and returns desired width value. In XAML file, component's width is set with the desired value:
public class SizePercentageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter == null)
return 0.7 * value.ToDouble();
string[] split = parameter.ToString().Split('.');
double parameterDouble = split[0].ToDouble() + split[1].ToDouble() / (Math.Pow(10, split[1].Length));
return value.ToDouble() * parameterDouble;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Don't need to implement this
return null;
}
}
XAML:
<UserControl.Resources>
<m:SizePercentageConverter x:Key="PercentageConverter" />
</UserControl.Resources>
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
Width="{Binding Converter={StaticResource PercentageConverter}, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualWidth}"
Height="{Binding Converter={StaticResource PercentageConverter}, ConverterParameter=0.6, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualHeight}">
....
</ScrollViewer>
Use preg_replace()
and instead of [ \t\n\r]
use \s
:
$output = preg_replace('!\s+!', ' ', $input);
From Regular Expression Basic Syntax Reference:
\d, \w and \s
Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.
When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".
If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".
try,
str_list = " ".join([str(ele) for ele in numlist])
this statement will give you each element of your list in string
format
print("The list now looks like [{0}]".format(str_list))
and,
change print(numlist.pop(2)+" has been removed")
to
print("{0} has been removed".format(numlist.pop(2)))
as well.
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
The way to do it is with ternary operator:
name = city.getName() == null ? city.getName() : "N/A"
However, I believe you have a typo in your code above, and you mean to say:
if (city.getName() != null) ...
Subversion supports a command named "Cleanup"; it is used to release the locks on a project
Thank you all for your help, I added this code and it seems it fixed the issue:
.navbar .navbar-nav {
display: inline-block;
float: none;
}
.navbar .navbar-collapse {
text-align: center;
}
Source
Vanilla JavaScript is all you need:
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(function(e){sum += e}); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(e => sum += e); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e in a) sum += e; sum
"00123foobar"
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e of a) sum += e; sum
10
preg_match_all(/<pre>([^>]*?)<\/pre>/,$content,$matches)
this regex will select everyting between tag. no matter is it in new line(work with multiline.
Try something like this:
df.select([c for c in df.columns if c in ['_2','_4','_5']]).show()
You may create a new list with an input of a previous list like so:
List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);
This will allow you to modify the order or what elemtents are contained independent of the first list.
Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.
example:
MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"
Edit
To avoid this you need a deep copy of each element in the list like so:
List<Torero> one = new ArrayList<Torero>();
//add elements
List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
Torero copy = deepCopy(t);
two.add(copy);
}
with copy like the following:
public Torero deepCopy(Torero input){
Torero copy = new Torero();
copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
return copy;
}
1 #!/usr/bin/python
2
3 a = raw_input('Enter the statement: ')
4
5 ########### To count number of words in the statement ##########
6
7 words = len(a.split(' '))
8 print 'Number of words in the statement are: %r' %words
9
10 ########### To count vowels in the statement ##########
11
12 print '\n' "Below is the vowel's count in the statement" '\n'
13 vowels = 'aeiou'
14
15 for key in vowels:
16 print key, '=', a.lower().count(key)
17
If you use nano with a language like python (as in your example) it's also a good idea to convert tabs to spaces.
Edit your ~/.nanorc file (or create it) and add:
set tabsize 4
set tabstospaces
If you already got a file with tabs and want to convert them to spaces i recommend the expand
command (shell):
expand -4 input.py > output.py
Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.
<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->
Otherwise, you can put !important
at the end of your CSS like this: color:#ffffff!important;
but I would advise against using !important
at all costs.