OK so I created a static async method. That disabled the control that launches the action and changes the application cursor. It runs the action as a task and waits for to finish. Control returns to the caller while it waits. So the application remains responsive, even while the busy icon spins.
async public static void LengthyOperation(Control control, Action action)
{
try
{
control.Enabled = false;
Application.UseWaitCursor = true;
Task doWork = new Task(() => action(), TaskCreationOptions.LongRunning);
Log.Info("Task Start");
doWork.Start();
Log.Info("Before Await");
await doWork;
Log.Info("After await");
}
finally
{
Log.Info("Finally");
Application.UseWaitCursor = false;
control.Enabled = true;
}
Here's the code form the main form
private void btnSleep_Click(object sender, EventArgs e)
{
var control = sender as Control;
if (control != null)
{
Log.Info("Launching lengthy operation...");
CursorWait.LengthyOperation(control, () => DummyAction());
Log.Info("...Lengthy operation launched.");
}
}
private void DummyAction()
{
try
{
var _log = NLog.LogManager.GetLogger("TmpLogger");
_log.Info("Action - Sleep");
TimeSpan sleep = new TimeSpan(0, 0, 16);
Thread.Sleep(sleep);
_log.Info("Action - Wakeup");
}
finally
{
}
}
I had to use a separate logger for the dummy action (I am using Nlog) and my main logger is writing to the UI (a rich text box). I wasn't able to get the busy cursor show only when over a particular container on the form (but I didn't try very hard.) All controls have a UseWaitCursor property, but it doesn't seem have any effect on the controls I tried (maybe because they weren't on top?)
Here's the main log, which shows things happening in the order we expect:
16:51:33.1064 Launching lengthy operation...
16:51:33.1215 Task Start
16:51:33.1215 Before Await
16:51:33.1215 ...Lengthy operation launched.
16:51:49.1276 After await
16:51:49.1537 Finally
Note your code contains Dir("thesentence")
which should be Dir(thesentence)
.
Change your code to this
Sub test()
thesentence = InputBox("Type the filename with full extension", "Raw Data File")
Range("A1").Value = thesentence
If Dir(thesentence) <> "" Then
MsgBox "File exists."
Else
MsgBox "File doesn't exist."
End If
End Sub
I'm not entirely certain that this applies to Scala but, in Java, I solved the NotSerializableException
by refactoring my code so that the closure did not access a non-serializable final
field.
Install a JDK.
It's possible to get Eclipse to run with a JRE, or at least it used to be, but why bother? Eclipse is much happier with a JDK.
Remember that the JRE that is used to run Eclipse does not have to be the JRE that Eclipse uses to run an application.
PS. I'm assuming here that the original poster's problem was getting Eclipse to start, and not (as some other Answers seem to address) getting Eclipse to start an application.
If we want to add numbers of an Array and find the average of them follow this easy way! .....
public class Array {
public static void main(String[] args) {
int[]array = {1,3,5,7,9,6,3};
int i=0;
int sum=0;
double average=0;
for( i=0;i<array.length;i++){
System.out.println(array[i]);
sum=sum+array[i];
}
System.out.println("sum is:"+sum);
System.out.println("average is: "+(double)sum/vargu.length);
}
}
Easily you can do it.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
Credits: https://freakycoder.com/android-notes-24-how-to-add-back-button-at-toolbar-941e6577418e
In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:
If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.
For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use @Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use @Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).
$("element").data('bs.modal').isShown
won't work if the modal hasn't been shown before. You will need to add an extra condition:
$("element").data('bs.modal')
so the answer taking into account first appearance:
if ($("element").data('bs.modal') && $("element").data('bs.modal').isShown){
...
}
SELECT TOP (@count) * FROM SomeTable
This will only work with SQL 2005+
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
this works well for me even though the XML structure is complex.
And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.
The main problem might not come from the attributes.
I figured I'd leave this here for those upgrading to Turbolinks 5: the easiest way to fix your code is to go from:
var ready;
ready = function() {
// Your JS here
}
$(document).ready(ready);
$(document).on('page:load', ready)
to:
var ready;
ready = function() {
// Your JS here
}
$(document).on('turbolinks:load', ready);
Reference: https://github.com/turbolinks/turbolinks/issues/9#issuecomment-184717346
Form validation can be enabled in markup via the data-api or via JavaScript. Automatically enable form validation by adding data-toggle="validator"
to your form element.
<form role="form" data-toggle="validator">
...
</form>
Or activate validation via JavaScript:
$('#myForm').validator()
and you need to use required flag in input field
For more details Click Here
I don't know if this question is still relevant, but there is such possibility in Postman now. They added it a few months ago.
All you need is create simple .js file and run it via node.js. It looks like this:
var path = require('path'),
async = require('async'), //https://www.npmjs.com/package/async
newman = require('newman'),
parametersForTestRun = {
collection: path.join(__dirname, 'postman_collection.json'), // your collection
environment: path.join(__dirname, 'postman_environment.json'), //your env
};
parallelCollectionRun = function(done) {
newman.run(parametersForTestRun, done);
};
// Runs the Postman sample collection thrice, in parallel.
async.parallel([
parallelCollectionRun,
parallelCollectionRun,
parallelCollectionRun
],
function(err, results) {
err && console.error(err);
results.forEach(function(result) {
var failures = result.run.failures;
console.info(failures.length ? JSON.stringify(failures.failures, null, 2) :
`${result.collection.name} ran successfully.`);
});
});
Then just run this .js file ('node fileName.js' in cmd).
More details here
with pages as (
SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
SUM (case
when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
else lob_used_page_count + row_overflow_used_page_count
end) as pages
FROM sys.dm_db_partition_stats
group by object_id
), extra as (
SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
FROM sys.dm_db_partition_stats p, sys.internal_tables it
WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
pages * 8 as data_kb,
(CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
(CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id
Takes into account internal tables, such as those used for XML storage.
Edit: If you divide the data_kb
and index_kb
values by 1024.0, you will get the numbers you see in the GUI.
With the help of a few answers posted here, I was able to find the issue
First I run
sudo -i
So I could have root access.
Than I deleted the xxxx.err file
rm -rf /usr/local/mysql/data/xxxx.err
after I started MySQL in SafeMode
/usr/local/mysql/bin/mysqld_safe start
It will try to start and will exit because of an error... a new xxx.err file will be created and you need to read it to see the cause of the error
tail -f /usr/local/mysql/data/mysqld.local.err
On my case, for some reason, it was missing some folder and file inside /var/log/
folder... So I created both
cd /var/log
mkdir mysql
touch mysql-bin.index
After the new file was created, than you need to change permission
chown -R _mysql /var/log/mysql
When all those steps where taken, my database started working immediately...
Hope this can help others here... The key is to read the error and log and find whats is wrong...
You could test the url via AJAX and read the status code - that is if the URL is in the same domain.
If it's a remote domain, you could have a server script on your own domain check out a remote URL.
I had this problem yesterday. @Quentin's answer is ok:
No, you cannot reference one rule-set from another.
but I made a javascript function to simulate inheritance in css (like .Net):
var inherit_array;_x000D_
var inherit;_x000D_
inherit_array = [];_x000D_
Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {_x000D_
Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {_x000D_
if (cssRule_i.style != null) {_x000D_
inherit = cssRule_i.style.getPropertyValue("--inherits").trim();_x000D_
} else {_x000D_
inherit = "";_x000D_
}_x000D_
if (inherit != "") {_x000D_
inherit_array.push({ selector: cssRule_i.selectorText, inherit: inherit });_x000D_
}_x000D_
});_x000D_
});_x000D_
Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {_x000D_
Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {_x000D_
if (cssRule_i.selectorText != null) {_x000D_
inherit_array.forEach(function (inherit_i, index) {_x000D_
if (cssRule_i.selectorText.split(", ").includesMember(inherit_i.inherit.split(", ")) == true) {_x000D_
cssRule_i.selectorText = cssRule_i.selectorText + ", " + inherit_i.selector;_x000D_
}_x000D_
});_x000D_
}_x000D_
});_x000D_
});
_x000D_
Array.prototype.includesMember = function (arr2) {_x000D_
var arr1;_x000D_
var includes;_x000D_
arr1 = this;_x000D_
includes = false;_x000D_
arr1.forEach(function (arr1_i, index) {_x000D_
if (arr2.includes(arr1_i) == true) {_x000D_
includes = true;_x000D_
}_x000D_
});_x000D_
return includes;_x000D_
}
_x000D_
and equivalent css:
.test {_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
.productBox, .imageBox {_x000D_
--inherits: .test;_x000D_
display: inline-block;_x000D_
}
_x000D_
and equivalent HTML :
<div class="imageBox"></div>
_x000D_
I tested it and worked for me, even if rules are in different css files.
Update: I found a bug in hierarchichal inheritance in this solution, and am solving the bug very soon .
I think this is the easy way example to iterate item.
declare @cateid int
select CateID into [#TempTable] from Category where GroupID = 'STOCKLIST'
while (select count(*) from #TempTable) > 0
begin
select top 1 @cateid = CateID from #TempTable
print(@cateid)
--DO SOMETHING HERE
delete #TempTable where CateID = @cateid
end
drop table #TempTable
there is also a sneak way with pandas:
pd.to_timedelta(x) - pd.to_timedelta(y)
Deleting registry keys as suggested above got my service stuck in the stopping state. The following procedure worked for me:
open task manager > select services tab > select the service > right click and select "go to process" > right click on the process and select End process
Service should be gone after that
declare @hours int = 5;
select dateadd(hour,@hours,getdate())
You do it like this:
df = read.table("file.txt", nrows=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
colClasses = as.list(apply(df, 2, class))
needCols = c("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
colClasses[!names(colClasses) %in% needCols] = list(NULL)
df = read.table("file.txt", header=TRUE, colClasses=colClasses, sep="\t", stringsAsFactors=FALSE)
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
You can try:
if(Character.isSpaceChar(ch))
{
// Do something...
}
Or:
if((int) ch) == 32)
{
// Do something...
}
This code and notation is not mine. Evan K solves a multi value same name query with a custom function ;) is taken from:
http://php.net/manual/en/function.parse-str.php#76792 Credits go to Evan K.
It bears mentioning that the parse_str
builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:
<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');
# the above produces:
$foo = array('foo' => '3');
?>
Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.
<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');
# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>
This can be confusing for anyone who's used to the CGI standard, so keep it in mind. As an alternative, I use a "proper" querystring parser function:
<?php
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
There are multiple ways of achieving this.
The routerLink attribute requires you to import the routingModule into the feature module in case you lazy loaded the feature module or just import the app-routing-module if it is not automatically added to the AppModule imports array.
<a [routerLink]="['/user', user.id]">John Doe</a>
<a routerLink="urlString">John Doe</a> // urlString is computed in your component
// Inject Router into your component
// Inject ActivatedRoute into your component. This will allow the route to be done related to the current url
this._router.navigate(['user',user.id], {relativeTo: this._activatedRoute})
this._router.navigateByUrl(urlString).then((bool) => {}).catch()
Use exceljs library for creating and writing into existing excel sheets.
You can check this tutorial for detailed explanation.
This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.
Perhaps, a good way is just to cut out a substring:
String St = "super exemple of string key : text I want to keep - end of my string";
int pFrom = St.IndexOf("key : ") + "key : ".Length;
int pTo = St.LastIndexOf(" - ");
String result = St.Substring(pFrom, pTo - pFrom);
Swift 4 and 5
For example, you have a UITableViewCell
with name MyCell
class MyCell: UITableViewCell {
var delegate:MyCellDelegate!
@IBAction private func myAction(_ sender: UIButton){
delegate.didPressButton(cell: self)
}
}
Now create a protocol
protocol MyCellDelegate {
func didPressButton(cell: UITableViewCell)
}
Next step, create an Extension of UITableView
extension UITableView {
func returnIndexPath(cell: UITableViewCell) -> IndexPath?{
guard let indexPath = self.indexPath(for: cell) else {
return nil
}
return indexPath
}
}
In your UIViewController
implement the protocol MyCellDelegate
class ViewController: UIViewController, MyCellDelegate {
func didPressButton(cell: UITableViewCell) {
if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
print(indexpath)
}
}
}
In UIViewController
override func viewDidLoad() {
super.viewDidLoad()
//using the same `UITableView extension` get the IndexPath here
didPressButton = { cell in
if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
print(indexpath)
}
}
}
var didPressButton: ((UITableViewCell) -> Void)
class MyCell: UITableViewCell {
@IBAction private func myAction(_ sender: UIButton){
didPressButton(self)
}
}
Note:- if you want to get
UICollectionView
indexPath you can use thisUICollectionView extension
and repeat the above steps
extension UICollectionView {
func returnIndexPath(cell: UICollectionViewCell) -> IndexPath?{
guard let indexPath = self.indexPath(for: cell) else {
return nil
}
return indexPath
}
}
Agree completely with Bryan and others.
Instead, consider using multiple sections in your email that you can jump to using links and anchors (the 'a' tag). I think that you can emulate the behavior you want by including multiple copies of the text further down in your email. This is a bet messy though, so you could just have sets of anchors that link to each other and allow you to move back in forth between the 'summary' section and the 'expanded' one.
Example:
<a href="#section1">Jump to section!</a>
<p>A bunch of content</p>
<h2 id="section1">An anchor!</h2>
Clicking on the first link will move focus to the sub-section.
This seems to take care of business pretty well. A fidde is here:
<label for="upload-file">A proper input label</label>
<div class="upload-button">
<div class="upload-cover">
Upload text or whatevers
</div>
<!-- this is later in the source so it'll be "on top" -->
<input name="upload-file" type="file" />
</div> <!-- .upload-button -->
/* first things first - get your box-model straight*/
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
label {
/* just positioning */
float: left;
margin-bottom: .5em;
}
.upload-button {
/* key */
position: relative;
overflow: hidden;
/* just positioning */
float: left;
clear: left;
}
.upload-cover {
/* basically just style this however you want - the overlaying file upload should spread out and fill whatever you turn this into */
background-color: gray;
text-align: center;
padding: .5em 1em;
border-radius: 2em;
border: 5px solid rgba(0,0,0,.1);
cursor: pointer;
}
.upload-button input[type="file"] {
display: block;
position: absolute;
top: 0; left: 0;
margin-left: -75px; /* gets that button with no-pointer-cursor off to the left and out of the way */
width: 200%; /* over compensates for the above - I would use calc or sass math if not here*/
height: 100%;
opacity: .2; /* left this here so you could see. Make it 0 */
cursor: pointer;
border: 1px solid red;
}
.upload-button:hover .upload-cover {
background-color: #f06;
}
I too had OpenJDK on my Ubuntu machine:
$ java -version
java version "1.7.0_51"
OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.13.04.2)
OpenJDK 64-Bit Server VM (build 24.45-b08, mixed mode)
Replacing OpenJDK with the HotSpot VM works fine:
sudo apt-get autoremove openjdk-7-jre-headless
Read this for detail :
// 1 define a function pointer and initialize to NULL
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;
// C++
class TMyClass
{
public:
int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
int DoMore(float a, char b, char c) const
{ cout << "TMyClass::DoMore" << endl; return a-b+c; };
/* more of TMyClass */
};
pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore
// Calling Function using Function Pointer
(*this.*pt2ConstMember)(12, 'a', 'b');
Just write this query in your db phpmyadmin.
ALTER TABLE TableName ADD UNIQUE (FieldName)
Eg: ALTER TABLE user ADD UNIQUE (email)
After doing some testing, i came up with this solution, let me know in case it helps.
Add this below 2 conditions in your query and it will find the records which don't contain numeric data
and REGEXP_LIKE(<column_name>, '\D') -- this selects non numeric data
and not REGEXP_LIKE(column_name,'^[-]{1}\d{1}') -- this filters out negative(-) values
I have found a solution. It is just a workaround to my problem but currently the only solution.
ViewPager PagerAdapter not updating the View
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Does anyone know whether this is a bug or not?
The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo
ls
show the right files?git init
? (git-init documentation)Either of those would cause your error.
jQuery.trim() works well.
Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time. This is done in the order than they appear in the source code.
You can setup an interval to keep checking if the user has scrolled then do something accordingly.
Borrowing from the great John Resig in his article.
Example:
let didScroll = false;
window.onscroll = () => didScroll = true;
setInterval(() => {
if ( didScroll ) {
didScroll = false;
console.log('Someone scrolled me!')
}
}, 250);
This convention is followed for security reasons. For example if unauthorized person is allowed to access root JSP file directly from URL then they can navigate through whole application without any authentication and they can access all the secured data.
ABCPDF can do so as well -- check out http://www.websupergoo.com/helppdf6net/default.html
I wrote a version that can parse through a list of objects dynamically to create the table as a string. I split it into three functions for writing the header columns, the body rows, and stitching it all together. I exported as a string for use on a server. My code uses template strings to keep things elegant.
If you want to add styling (like bootstrap), that can be done by adding more html to HEAD_PREFIX
and HEAD_SUFFIX
.
// helper functions
const TABLE_PREFIX = '<div><table class="tg">';
const TABLE_SUFFIX = '</table></div>';
const TABLE_HEAD_PREFIX = '<thead><tr>';
const TABLE_HEAD_SUFFIX = '</tr></thead>';
const TABLE_BODY_PREFIX = '<tbody><tr>';
const TABLE_BODY_SUFFIX = '</tr></tbody>';
function generateTableHead(cols) {
return `
${TABLE_HEAD_PREFIX}
<td>#</td>
${cols.map((col) => `<td>${col}</td>`).join('')}
${TABLE_HEAD_SUFFIX}`;
}
function generateTableBody(cols, data) {
return `
${TABLE_BODY_PREFIX}
${data.map((object, index) => `
<tr><td>${index}</td>
${cols.map((col) => `<td>${object[col]}</td>`).join('')}
</tr>`).join('')}
${TABLE_BODY_SUFFIX}`;
}
/**
* generate an html table from an array of objects with the same values
*
* @param {array<string>} cols array of object columns used in order of columns on table
* @param {array<object>} data array of objects containing data in a single depth
*/
function generateTable(data, defaultCols = false) {
let cols = defaultCols;
if (!cols) cols = Object.keys(data[0]); // auto generate columns if not defined
return `
${TABLE_PREFIX}
${generateTableHead(cols)}
${generateTableBody(cols, data)}
${TABLE_SUFFIX}`;
}
Here's an example use:
const mountains = [
{ height: 200, name: "Mt. Mountain" },
{ height: 323, name: "Old Broken Top"},
]
const htmlTableString = generateTable(mountains );
You can embed websites into another website using the <embed>
tag, like so:
<embed src="http://www.example.com" style="width:500px; height: 300px;">
You can change the height, width, and URL to suit your needs.
The <embed>
tag is the most up-to-date way to embed websites, as it was introduced with HTML5.
On Servlet 3.0 or newer you could just specify
<web-app ...>
<error-page>
<location>/general-error.html</location>
</error-page>
</web-app>
But as you're still on Servlet 2.5, there's no other way than specifying every common HTTP error individually. You need to figure which HTTP errors the enduser could possibly face. On a barebones webapp with for example the usage of HTTP authentication, having a disabled directory listing, using custom servlets and code which can possibly throw unhandled exceptions or does not have all methods implemented, then you'd like to set it for HTTP errors 401, 403, 500 and 503 respectively.
<error-page>
<!-- Missing login -->
<error-code>401</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Forbidden directory listing -->
<error-code>403</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Missing resource -->
<error-code>404</error-code>
<location>/Error404.html</location>
</error-page>
<error-page>
<!-- Uncaught exception -->
<error-code>500</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Unsupported servlet method -->
<error-code>503</error-code>
<location>/general-error.html</location>
</error-page>
That should cover the most common ones.
In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!
Example -Before :
<string-array name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Example - After:
<string-array android:name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance
before trying to spy on the method.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const instance = app.instance()
const spy = jest.spyOn(instance, 'myClickFunc')
instance.forceUpdate();
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
Add a "User-Agent" header to your request.
Some servers attempt to block spidering programs and scrapers from accessing their server because, in earlier days, requests did not send a user agent header.
You can either try to set a custom user agent value or use some value that identifies a Browser like "Mozilla/5.0 Firefox/26.0"
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("user-agent", "Mozilla/5.0 Firefox/26.0");
headers.set("user-key", "your-password-123"); // optional - in case you auth in headers
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Game[]> respEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Game[].class);
logger.info(respEntity.toString());
This worked best.
(from p in Context.person_account_portfolio
where p.person_id == personId select p).ToList()
.ForEach(x => x.is_default = false);
Context.SaveChanges();
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
Updated answer, from Peter in comments :
This is de "old terminology", use directally the WSDL2 "endepoint" definition (WSDL2 translated "port" to "endpoint").
Maybe you find an answer in this document : http://www.w3.org/TR/wsdl.html
A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:
- Types– a container for data type definitions using some type system (such as XSD).
- Message– an abstract, typed definition of the data being communicated.
- Operation– an abstract description of an action supported by the service.
- Port Type–an abstract set of operations supported by one or more endpoints.
- Binding– a concrete protocol and data format specification for a particular port type.
- Port– a single endpoint defined as a combination of a binding and a network address.
- Service– a collection of related endpoints.
http://www.ehow.com/info_12212371_definition-service-endpoint.html
The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal.
Took me a while to find this but note that if you have a spacing error you will also get the same error:
[: =: unary operator expected
Correct:
if [ "$APP_ENV" = "staging" ]
vs
if ["$APP_ENV" = "staging" ]
As always setting -x
debug variable helps to find these:
set -x
What i do is to prepare a 512x512 PNG, the Alpha Channel is good for rounded corners or drop shadows, then I upload it to this site http://convertico.com/, and for free then it returns me a 6 sizes .ico file with 256x256, 128x128, 64x64, 48x48, 32x32 and 16x16 sizes.
Its as simple as:
var blah = {}; // make a new dictionary (empty)
or
var blah = {key: value, key2: value2}; // make a new dictionary with two pairs
then
blah.key3 = value3; // add a new key/value pair
blah.key2; // returns value2
blah['key2']; // also returns value2
Note: Your question is about escaping, not encoding. Escaping is using <, etc. to allow the parser to distinguish between "this is an XML command" and "this is some text". Encoding is the stuff you specify in the XML header (UTF-8, ISO-8859-1, etc).
First of all, like everyone else said, use an XML library. XML looks simple but the encoding+escaping stuff is dark voodoo (which you'll notice as soon as you encounter umlauts and Japanese and other weird stuff like "full width digits" (&#FF11; is 1)). Keeping XML human readable is a Sisyphus' task.
I suggest never to try to be clever about text encoding and escaping in XML. But don't let that stop you from trying; just remember when it bites you (and it will).
That said, if you use only UTF-8, to make things more readable you can consider this strategy:
<![CDATA[ ... ]]>
I'm using this in an SQL editor and it allows the developers to cut&paste SQL from a third party SQL tool into the XML without worrying about escaping. This works because the SQL can't contain umlauts in our case, so I'm safe.
<div class="container-fluid">
<div class="col-sm-12 text-center">
<button class="btn btn-primary" title="Submit"></button>
<button class="btn btn-warning" title="Cancel"></button>
</div>
</div>
state={
name:"",
email:""
}
handalSubmit = () => {
after api call
let resetFrom = {}
fetch('url')
.then(function(response) {
if(response.success){
resetFrom{
name:"",
email:""
}
}
})
this.setState({...resetFrom})
}
I had a similar issue, and following reply from ArtB,
I found that my user didn't have the proper configurations. so what I did:
Note: manually modifying such XML files is risky. Do it at your own risk. Since I was already locked out, I didn't have much to lose. AFAIK Worst case I would have deleted the ~/.jenkins/config.xml file as prev post mentioned.
**> 1. ssh to the jenkins machine
- cd ~/.jenkins (I guess that some installations put it under /var/lib/jenkins/config.xml, but not in my case )
- vi config.xml, and under authorizationStrategy xml tag, add the below section (just used my username instead of "put-your-username")
- restart jenkins. in my case as root service tomcat7 stop; ; service tomcat7 start
- Try to login again. (worked for me)**
under
add:
<permission>hudson.model.Computer.Build:put-your-username</permission>
<permission>hudson.model.Computer.Configure:put-your-username</permission>
<permission>hudson.model.Computer.Connect:put-your-username</permission>
<permission>hudson.model.Computer.Create:put-your-username</permission>
<permission>hudson.model.Computer.Delete:put-your-username</permission>
<permission>hudson.model.Computer.Disconnect:put-your-username</permission>
<permission>hudson.model.Hudson.Administer:put-your-username</permission>
<permission>hudson.model.Hudson.ConfigureUpdateCenter:put-your-username</permission>
<permission>hudson.model.Hudson.Read:put-your-username</permission>
<permission>hudson.model.Hudson.RunScripts:put-your-username</permission>
<permission>hudson.model.Hudson.UploadPlugins:put-your-username</permission>
<permission>hudson.model.Item.Build:put-your-username</permission>
<permission>hudson.model.Item.Cancel:put-your-username</permission>
<permission>hudson.model.Item.Configure:put-your-username</permission>
<permission>hudson.model.Item.Create:put-your-username</permission>
<permission>hudson.model.Item.Delete:put-your-username</permission>
<permission>hudson.model.Item.Discover:put-your-username</permission>
<permission>hudson.model.Item.Read:put-your-username</permission>
<permission>hudson.model.Item.Workspace:put-your-username</permission>
<permission>hudson.model.Run.Delete:put-your-username</permission>
<permission>hudson.model.Run.Update:put-your-username</permission>
<permission>hudson.model.View.Configure:put-your-username</permission>
<permission>hudson.model.View.Create:put-your-username</permission>
<permission>hudson.model.View.Delete:put-your-username</permission>
<permission>hudson.model.View.Read:put-your-username</permission>
<permission>hudson.scm.SCM.Tag:put-your-username</permission>
Now, you can go to different directions. For example I had github oauth integration, so I could have tried to replace the authorizationStrategy with something like below:
Note:, It worked in my case because I had a specific github oauth plugin that was already configured. So it is more risky than the previous solution.
<authorizationStrategy class="org.jenkinsci.plugins.GithubAuthorizationStrategy" plugin="[email protected]">
<rootACL>
<organizationNameList class="linked-list">
<string></string>
</organizationNameList>
<adminUserNameList class="linked-list">
<string>put-your-username</string>
<string>username2</string>
<string>username3</string>
<string>username_4_etc_put_username_that_will_become_administrator</string>
</adminUserNameList>
<authenticatedUserReadPermission>true</authenticatedUserReadPermission>
<allowGithubWebHookPermission>false</allowGithubWebHookPermission>
<allowCcTrayPermission>false</allowCcTrayPermission>
<allowAnonymousReadPermission>false</allowAnonymousReadPermission>
</rootACL>
</authorizationStrategy>
I've used HttpClient in .NET 4.0 applications on numerous occasions. If you are familiar with NuGet, you can do an Install-Package Microsoft.Net.Http to add it to your project. See the link below for further details.
Predicate
has methods and
, or
and negate
.
However, String::isEmpty
is not a Predicate
, it's just a String -> Boolean
lambda and it could still become anything, e.g. Function<String, Boolean>
. Type inference is what needs to happen first. The filter
method infers type implicitly. But if you negate it before passing it as an argument, it no longer happens. As @axtavt mentioned, explicit inference can be used as an ugly way:
s.filter(((Predicate<String>) String::isEmpty).negate()).count()
There are other ways advised in other answers, with static not
method and lambda most likely being the best ideas. This concludes the tl;dr section.
However, if you want some deeper understanding of lambda type inference, I'd like to explain it a bit more to depth, using examples. Look at these and try to figure out what happens:
Object obj1 = String::isEmpty;
Predicate<String> p1 = s -> s.isEmpty();
Function<String, Boolean> f1 = String::isEmpty;
Object obj2 = p1;
Function<String, Boolean> f2 = (Function<String, Boolean>) obj2;
Function<String, Boolean> f3 = p1::test;
Predicate<Integer> p2 = s -> s.isEmpty();
Predicate<Integer> p3 = String::isEmpty;
Predicate
to Object
- silly but validPredicate
to Function
, it's no longer about inferencetest
that is defined by its lambdaInteger
doesn't have isEmpty
methodString::isEmpty
static method with Integer
argumentI hope this helps get some more insight into how type inferrence works.
There is possibly a quicker way, but I would do:
a <- rnorm(100) # Our data
q <- quantile(a) # You can supply your own breaks, see ?quantile
# Define a simple function that checks in which quantile a number falls
getQuant <- function(x)
{
for (i in 1:(length(q)-1))
{
if (x>=q[i] && x<q[i+1])
break;
}
i
}
# Apply the function to the data
res <- unlist(lapply(as.matrix(a), getQuant))
Addition to above great answers, if you want some range of IPs to be authorized, you could edit /var/lib/pgsql/{VERSION}/data
file and put something like
host all all 172.0.0.0/8 trust
It will accept incoming connections from any host of the above range. Source: http://www.linuxtopia.org/online_books/database_guides/Practical_PostgreSQL_database/c15679_002.htm
According to MSDN, e.AddedItems
:
Gets a list that contains the items that were selected.
So you could use:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
}
You could also use SelectedItem
if you use string
values for the Items
from the sender
:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (sender as ComboBox).SelectedItem as string;
}
or
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
}
Since both Content
and SelectedItem
are objects, a safer approach would be to use .ToString()
instead of as string
I fixed it with Datejs
This is alerting the first day:
var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);
This is for the last day:
var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);
While the answers with List<T>.ForEach
are very good.
I found String.Join<T>(string separator, IEnumerable<T> values)
method more useful.
Example :
List<string> numbersStrLst = new List<string>
{ "One", "Two", "Three","Four","Five"};
Console.WriteLine(String.Join(", ", numbersStrLst));//Output:"One, Two, Three, Four, Five"
int[] numbersIntAry = new int[] {1, 2, 3, 4, 5};
Console.WriteLine(String.Join("; ", numbersIntAry));//Output:"1; 2; 3; 4; 5"
Remarks :
If separator is null, an empty string (String.Empty
) is used instead. If any member of values is null, an empty string is used instead.
Join(String, IEnumerable<String>)
is a convenience method that lets you concatenate each element in an IEnumerable(Of String) collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions.
This should work just fine for the problem, whereas for others, having array values. Use other overloads of this same method, String.Join Method (String, Object[])
Reference: https://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx
I found this piece of code somewhere in the web. Maybe it helps you and I give you an update so far I accomodated it for the same purpose... Maybe I don't.... who the futt knows... with all the nogodders and dobedders in here :-/
function runVLC(target, stream)
{
var support=true
var addr='rtsp://' + window.location.hostname + stream
if ($.browser.msie){
$(target).html('<object type = "application/x-vlc-plugin"' + 'version =
"VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' +
'events = "true"' + 'id = "vlc"></object>')
}
else if ($.browser.mozilla || $.browser.webkit){
$(target).html('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' +
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' +
'width="660" height="372"' +
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' +
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' +
'branding="false"' + 'controls="false"' + 'aspectRatio="16:9"' +
'target="whatever.mp4"></embed>')
}
else{
support=false
$(target).empty().html('<div id = "dialog_error">Error: browser not supported!</div>')
}
if (support){
var vlc = document.getElementById('vlc')
if (vlc){
var opt = new Array(':network-caching=300')
try{
var id = vlc.playlist.add(addr, '', opt)
vlc.playlist.playItem(id)
}
catch (e){
$(target).empty().html('<div id = "dialog_error">Error: ' + e + '<br>URL: ' + addr +
'</div>')
}
}
}
}
/* $(target + ' object').css({'width': '100%', 'height': '100%'}) */
Greets
Gee
I reduce the whole crap now to:
function runvlc(){
var target=$('body')
var error=$('#dialog_error')
var support=true
var addr='rtsp://../html/media/video/TESTCARD.MP4'
if (navigator.userAgent.toLowerCase().indexOf("msie")!=-1){
target.append('<object type = "application/x-vlc-plugin"' + 'version = "
VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' +
'events = "true"' + 'id = "vlc"></object>')
}
else if (navigator.userAgent.toLowerCase().indexOf("msie")==-1){
target.append('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' +
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' +
'width="660" height="372"' +
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' +
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' +
'branding="false"' +
'controls="false"' + 'aspectRatio="16:9"' + 'target="whatever.mp4">
</embed>')
}
else{
support=false
error.empty().html('Error: browser not supported!')
error.show()
if (support){
var vlc=document.getElementById('vlc')
if (vlc){
var options=new Array(':network-caching=300') /* set additional vlc--options */
try{ /* error handling */
var id = vlc.playlist.add(addr,'',options)
vlc.playlist.playItem(id)
}
catch (e){
error.empty().html('Error: ' + e + '<br>URL: ' + addr + '')
error.show()
}
}
}
}
};
Didn't get it to work in ie as well... 2b continued...
Greets
Gee
Acording to the docs:
Note The urllib2 module has been split across several modules in Python 3 named
urllib.request
andurllib.error
. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
So it appears that it is impossible to do what you want but you can use appropriate python3 functions from urllib.request
.
Try putting display: block
in the <li>
tags instead of the <ul>
I just moved source folder connector
from folder mysql
to site-packages
.
And run import connector
you can remove an App from the store or "Unpublish" by clicking a tiny label bellow your app's title, right side of the "PUBLISHED" green status label.
Works even if your app was live (published) for long time, mine was.
Regards.
Try this.
$sub_total = 0;
and within your loop now you can use this
$sub_total += ($item['quantity'] * $product['price']);
It should solve your problem.
If iframe's source is an external domain, browsers will hide the iframe contents (Same Origin Policy). A workaround is saving the external contents in a file, for example (in PHP):
<?php
$contents = file_get_contents($external_url);
$res = file_put_contents($filename, $contents);
?>
then, get the new file content (string) and parse it to html, for example (in jquery):
$.get(file_url, function(string){
var html = $.parseHTML(string);
var contents = $(html).contents();
},'html');
Try something like this:
<html>
<body>
<script type="text/javascript">
function doSomething(event) {
var source = event.target || event.srcElement;
console.log(source);
alert('test');
if(window.event) {
// IE8 and earlier
// doSomething
} else if(e.which) {
// IE9/Firefox/Chrome/Opera/Safari
// doSomething
}
}
</script>
<button onclick="doSomething('param')" id="id_button">
action
</button>
</body>
</html>
Your code should work, but I'm aware that answer doesn't help you. You can see a working example here (jsfiddle).
Jquery:
$(document).on('click','#test-element',function(){
alert("You clicked the element with and ID of 'test-element'");
});
As someone already pointed out, you are using an ID instead of a class. If you have more that one element on the page with an ID, then jquery will return only the first element with that ID. There won't be any errors because that's how it works. If this is the problem, then you'll notice that the click event works for the first test-element
but not for any that follow.
If this does not accurately describe the symptoms of the problem, then perhaps your selector is wrong. Your update leads me to believe this is the case because of inspecting an element then clicking the page again and triggering the click. What could be causing this is if you put the event listener on the actual document
instead of test-element
. If so, when you click off the document and back on (like from the developer window back to the document) the event will trigger. If this is the case, you'll also notice the click event is triggered if you click between two different tabs (because they are two different document
s and therefore you are clicking the document.
If neither of these are the answer, posting HTML will go a long way toward figuring it out.
DateTime values should be inserted as if they are strings surrounded by single quotes
'20201231'
but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME)
to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:
CREATE TABLE dbo.T(D DATETIME)
--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')
--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))
The cross-platform way to do this is to print('\a')
. This will send the ASCII Bell character to stdout, and will hopefully generate a beep (a for 'alert'). Note that many modern terminal emulators provide the option to ignore bell characters.
Since you're on Windows, you'll be happy to hear that Windows has its own (brace yourself) Beep API, which allows you to send beeps of arbitrary length and pitch. Note that this is a Windows-only solution, so you should probably prefer print('\a')
unless you really care about Hertz and milliseconds.
The Beep API is accessed through the winsound module: http://docs.python.org/library/winsound.html
Use tags label and our method for =, is bound to input. If follow the rules of the form, and avoid confusion with tags, use the following:
<style type="text/css">
label.lab:before { content: 'input: '; }
</style>
or compare (short code):
<style type="text/css">
div label { content: 'input: '; color: red; }
</style>
form....
<label class="lab" for="single"></label><input name="n" id="single" ...><label for="single"> - simle</label>
or compare (short code):
<div><label></label><input name="n" ...></div>
Of course you can, just use setTimeout
to change a class or something to trigger the transition.
HTML:
<p id="aap">OHAI!</p>
CSS:
p {
opacity:1;
transition:opacity 500ms;
}
p.waa {
opacity:0;
}
JS to run on load or DOMContentReady:
setTimeout(function(){
document.getElementById('aap').className = 'waa';
}, 5000);
Being late to this, but after Java 8, I personally find this following approach with the Stream
API more concise and can be an alternative to the accepted answer.
For example,
Arrays.stream(new int[size]).boxed().collect(Collectors.toList())
where size
is the desired List
size and without the disadvantage mentioned here, all elements in the List
are initialized as 0
.
(I did a quick search and did not see stream
in any answers posted - feel free to let me know if this answer is redundant and I can remove it)
It sounds like you want something like:
var query = from order in workOrders
join plan in plans
on order.WorkOrderNumber equals plan.WorkOrderNumber
select new
{
order.WorkOrderNumber,
order.Description,
plan.ScheduledDate
};
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
List installed dependencies:
composer show -i
composer show -i -t
-i
short for --installed
.
-t
short for --tree
.
in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.
the return statement exits from the current function and exit() exits from the program
they are the same when used in main() function
also return is a statement while exit() is a function which requires stdlb.h header file
The recommended way to do this:
Nowadays, you should really be using DateTime objects for any date/time math. This requires you to have a PHP version >= 5.2. As shown in Glavic's answer, you can use the following:
$monthNum = 3;
$dateObj = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F'); // March
The !
formatting character is used to reset everything to the Unix epoch. The m
format character is the numeric representation of a month, with leading zeroes.
Alternative solution:
If you're using an older PHP version and can't upgrade at the moment, you could this solution.
The second parameter of date()
function accepts a timestamp, and you could use mktime()
to create one, like so:
$monthNum = 3;
$monthName = date('F', mktime(0, 0, 0, $monthNum, 10)); // March
If you want the 3-letter month name like Mar
, change F
to M
. The list of all available formatting options can be found in the PHP manual documentation.
Just make a new folder inside C:\xampp\htdocs like C:\xampp\htdocs\test and place your index.php or whatever file in it. Access it by browsing localhost/test/
Good luck!
The %#08X
conversion must precede the value with 0X
; that is required by the standard. There's no evidence in the standard that the #
should alter the behaviour of the 08
part of the specification except that the 0X
prefix is counted as part of the length (so you might want/need to use %#010X
. If, like me, you like your hex presented as 0x1234CDEF
, then you have to use 0x%08X
to achieve the desired result. You could use %#.8X
and that should also insert the leading zeroes.
Try variations on the following code:
#include <stdio.h>
int main(void)
{
int j = 0;
printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
for (int i = 0; i < 8; i++)
{
j = (j << 4) | (i + 6);
printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
}
return(0);
}
On an RHEL 5 machine, and also on Mac OS X (10.7.5), the output was:
0x00000000 = 00000000 = 00000000 = 0000000000
0x00000006 = 0X000006 = 0X00000006 = 0x00000006
0x00000067 = 0X000067 = 0X00000067 = 0x00000067
0x00000678 = 0X000678 = 0X00000678 = 0x00000678
0x00006789 = 0X006789 = 0X00006789 = 0x00006789
0x0006789A = 0X06789A = 0X0006789A = 0x0006789a
0x006789AB = 0X6789AB = 0X006789AB = 0x006789ab
0x06789ABC = 0X6789ABC = 0X06789ABC = 0x06789abc
0x6789ABCD = 0X6789ABCD = 0X6789ABCD = 0x6789abcd
I'm a little surprised at the treatment of 0; I'm not clear why the 0X
prefix is omitted, but with two separate systems doing it, it must be standard. It confirms my prejudices against the #
option.
The treatment of zero is according to the standard.
ISO/IEC 9899:2011 §7.21.6.1 The
fprintf
function¶6 The flag characters and their meanings are:
...
#
The result is converted to an "alternative form". ... Forx
(orX
) conversion, a nonzero result has0x
(or0X
) prefixed to it. ...
(Emphasis added.)
Note that using %#X
will use upper-case letters for the hex digits and 0X
as the prefix; using %#x
will use lower-case letters for the hex digits and 0x
as the prefix. If you prefer 0x
as the prefix and upper-case letters, you have to code the 0x
separately: 0x%X
. Other format modifiers can be added as needed, of course.
For printing addresses, use the <inttypes.h>
header and the uintptr_t
type and the PRIXPTR
format macro:
#include <inttypes.h>
#include <stdio.h>
int main(void)
{
void *address = &address; // &address has type void ** but it converts to void *
printf("Address 0x%.12" PRIXPTR "\n", (uintptr_t)address);
return 0;
}
Example output:
Address 0x7FFEE5B29428
Choose your poison on the length — I find that a precision of 12 works well for addresses on a Mac running macOS. Combined with the .
to specify the minimum precision (digits), it formats addresses reliably. If you set the precision to 16, the extra 4 digits are always 0 in my experience on the Mac, but there's certainly a case to be made for using 16 instead of 12 in portable 64-bit code (but you'd use 8 for 32-bit code).
ls
is part of coreutils. You can get it with git :
git clone git://git.sv.gnu.org/coreutils
You'll find coreutils listed with other packages (scroll to bottom) on this page.
Like This:
<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>
To show just yours:
SELECT
db, type, specific_name, param_list, returns
FROM
mysql.proc
WHERE
definer LIKE
CONCAT('%', CONCAT((SUBSTRING_INDEX((SELECT user()), '@', 1)), '%'));
This is not an error message but a warning. It is very clearly explained in their website as :
This warning, i.e. not an error, message is reported when no SLF4J providers could be found on the class path. Placing one (and only one) of slf4j-nop.jar slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem. Note that these providers must target slf4j-api 1.8 or later.
In the absence of a provider, SLF4J will default to a no-operation (NOP) logger provider.
My two cents, adding trim to remove the initial whitespaces left in sAc's answer.
var str = 'Hello, World, etc';
var str_array = str.split(',');
for(var i = 0; i < str_array.length; i++) {
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Add additional code here, such as:
alert(str_array[i]);
}
After getting several upvotes on this answer, I wanted to revisit this. If you want to split on comma, and perform a trim operation, you can do it in one method call without any explicit loops due to the fact that split
will also take a regular expression as an argument:
'Hello, cruel , world!'.split(/\s*,\s*/);
//-> ["Hello", "cruel", "world!"]
This solution, however, will not trim the beginning of the first item and the end of the last item which is typically not an issue.
And so to answer the question in regards to process in a loop, if your target browsers support ES5 array extras such as the map
or forEach
methods, then you could just simply do the following:
myStringWithCommas.split(/\s*,\s*/).forEach(function(myString) {
console.log(myString);
});
std::fill
is one way. Takes two iterators and a value to fill the region with. That, or the for loop, would (I suppose) be the more C++ way.
For setting an array of primitive integer types to 0 specifically, memset
is fine, though it may raise eyebrows. Consider also calloc
, though it's a bit inconvenient to use from C++ because of the cast.
For my part, I pretty much always use a loop.
(I don't like to second-guess people's intentions, but it is true that std::vector
is, all things being equal, preferable to using new[]
.)
The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.
It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.
I'm also reading an exported file which contains french and German languages. I used Encoding.GetEncoding("iso-8859-1"), true which worked out without any challenges.
I encountered the same error. My linker command did have the rt library included -lrt
which is correct and it was working for a while. After re-installing Kubuntu it stopped working.
A separate forum thread suggested the -lrt
needed to come after the project object files.
Moving the -lrt
to the end of the command fixed this problem for me although I don't know the details of why.
Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:
Entity.java:
@Entity
@NamedQueries({
@NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
@Column(name = "attribute")
private String attribute;
}
Dao.java:
public class Dao {
public List<Entity> findByAttributes(Set<String> attributes) {
Query query = em.createNamedQuery("byAttributes");
query.setParameter(1, attributes);
List<Entity> entities = query.getResultList();
return entities;
}
}
if you know the file name, but don't know the file extention you can use this function:
public function showImage($name)
{
$types = [
'gif'=> 'image/gif',
'png'=> 'image/png',
'jpeg'=> 'image/jpeg',
'jpg'=> 'image/jpeg',
];
$root_path = '/var/www/my_app'; //use your framework to get this properly ..
foreach($types as $type=>$meta){
if(file_exists($root_path .'/uploads/'.$name .'.'. $type)){
header('Content-type: ' . $meta);
readfile($root_path .'/uploads/'.$name .'.'. $type);
return;
}
}
}
Note: the correct content-type for JPG files is image/jpeg
.
The source
builtin is a bashism. Write this simply as .
instead.
e.g.
. $FILE
# OR you may need to use a relative path (such as in an `npm` script):
. ./$FILE
You can write that in single line, but it's not something that someone would be able to read. Keep it like you already wrote it, it's already beautiful by itself.
If you have too much if/else
constructs, you may think about using of different datastructures, like Dictionaries
(to look up keys) or Collection
(to run conditional LINQ
queries on it)
You can call more than one target goal with maven. mvn clean install
calls clean
first, then install
. You have to clean manually, because clean is not a standard target goal and not executed automatically on every install.
clean
removes the target folder - it deletes all class files, the java docs, the jars, reports and so on. If you don't clean
, then maven will only "do what has to be done", like it won't compile classes when the corresponding source files haven't changed (in brief).
we call it target in ant and goal in maven
In java 8 , It's really easy to get timestamp in UTC by using java 8 java.time.Instant library :
Instant.now();
That few word of code will return the UTC Timestamp.
In Lollipop (21), you can use Intent.EXTRA_REPLACEMENT_EXTRAS
to override the intent for Facebook specifically (and specify a link only)
https://developer.android.com/reference/android/content/Intent.html#EXTRA_REPLACEMENT_EXTRAS
private void doShareLink(String text, String link) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share_via));
// for 21+, we can use EXTRA_REPLACEMENT_EXTRAS to support the specific case of Facebook
// (only supports a link)
// >=21: facebook=link, other=text+link
// <=20: all=link
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
shareIntent.putExtra(Intent.EXTRA_TEXT, text + " " + link);
Bundle facebookBundle = new Bundle();
facebookBundle.putString(Intent.EXTRA_TEXT, link);
Bundle replacement = new Bundle();
replacement.putBundle("com.facebook.katana", facebookBundle);
chooserIntent.putExtra(Intent.EXTRA_REPLACEMENT_EXTRAS, replacement);
} else {
shareIntent.putExtra(Intent.EXTRA_TEXT, link);
}
chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(chooserIntent);
}
The solutions above didn't help me. I've tried 2 first steps from this link. Worked fine for me. But don't forget to
import com.melnykov.fab.FloatingActionButton;
instead of
import android.support.design.widget.FloatingActionButton;
in your MainActivity.java
Something like:
select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id
If you have php installed - you can use built-in server. Just open target dir with files and run
php -S localhost:8001
<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>
Instructions
First, insert these lines wherever you want within your newsletter code. Then:
If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.
All you need is a ADODB.Connection
Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset ' Microsoft ActiveX Data Objects Library
Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"
Set rs = cnn.Execute(SQLQuery) ' Retrieve the data
Note that in Entity Framework 6.1 (currently in beta) will support the IndexAttribute to annotate the index properties which will automatically result in a (unique) index in your Code First Migrations.
Some times , the text has the same color that background, try with android:background="#CCCCCC" into listview properties and you will can see that.
The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
The lookup time is slow because when you use mmap
to does not load content of array to memory when you invoke load
method. Data is lazy loaded when particular data is needed.
And this happens in lookup in your case. But second lookup won`t be so slow.
This is nice feature of mmap
when you have a big array you do not have to load whole data into memory.
To solve your can use joblib you can dump any object you want using joblib.dump
even two or more numpy arrays
, see the example
firstArray = np.arange(100)
secondArray = np.arange(50)
# I will put two arrays in dictionary and save to one file
my_dict = {'first' : firstArray, 'second' : secondArray}
joblib.dump(my_dict, 'file_name.dat')
This style:
table tr td { border: 1px solid red; }
td table tr td { border: none; }
gives me:
this http://img12.imageshack.us/img12/4477/borders.png
However, using a class is probably the right approach here.
Here's a basic code that will help serializing the C# objects into xml:
using System;
public class clsPerson
{
public string FirstName;
public string MI;
public string LastName;
}
class class1
{
static void Main(string[] args)
{
clsPerson p=new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}
You might like to consider ADO - a worksheet or range can be used as a table.
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adPersistXML = 1
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
''It wuld probably be better to use the proper name, but this is
''convenient for notes
strFile = Workbooks(1).FullName
''Note HDR=Yes, so you can use the names in the first row of the set
''to refer to columns, note also that you will need a different connection
''string for >=2007
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
rs.Open "Select * from [Sheet1$]", cn, adOpenStatic, adLockOptimistic
If Not rs.EOF Then
rs.MoveFirst
rs.Save "C:\Docs\Table1.xml", adPersistXML
End If
rs.Close
cn.Close
For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:
<ul>
<li *ngFor="let item of items | slice:0:10">
{{ item }}
</li>
</ul>
You have two " "
before the =
let imageToDeleteParameters = imagesToDelete.map { ["id": $0.id, "url": $0.url.absoluteString, "_destroy": true] }
I liked Danila's solution and started using it but nobody else on the team liked having to create 4 classes for each repository. Danila's solution is the only one here that let's you use the Spring Data methods in the Impl class. However, I found a way to do it with just a single class:
public interface UserRepository extends MongoAccess, PagingAndSortingRepository<User> {
List<User> getByUsername(String username);
default List<User> getByUsernameCustom(String username) {
// Can call Spring Data methods!
findAll();
// Can write your own!
MongoOperations operations = getMongoOperations();
return operations.find(new Query(Criteria.where("username").is(username)), User.class);
}
}
You just need some way of getting access to your db bean (in this example, MongoOperations). MongoAccess provides that access to all of your repositories by retrieving the bean directly:
public interface MongoAccess {
default MongoOperations getMongoOperations() {
return BeanAccessor.getSingleton(MongoOperations.class);
}
}
Where BeanAccessor is:
@Component
public class BeanAccessor implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getSingleton(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static <T> T getSingleton(String beanName, Class<T> clazz){
return applicationContext.getBean(beanName, clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanAccessor.applicationContext = applicationContext;
}
}
Unfortunately, you can't @Autowire in an interface. You could autowire the bean into a MongoAccessImpl and provide a method in the interface to access it, but Spring Data blows up. I don't think it expects to see an Impl associated even indirectly with PagingAndSortingRepository.
You can use this code:
private void OnClickNavigate(object sender, RoutedEventArgs e)
{
NavigatedWindow navigatesWindow = new NavigatedWindow();
navigatesWindow.ShowDialog();
}
IPv4 address is a very complicated thing.
Note: Indentation and lining are only for illustration purposes and do not exist in the real RegEx.
\b(
((
(2(5[0-5]|[0-4][0-9])|1[0-9]{2}|[1-9]?[0-9])
|
0[Xx]0*[0-9A-Fa-f]{1,2}
|
0+[1-3]?[0-9]{1,2}
)\.){1,3}
(
(2(5[0-5]|[0-4][0-9])|1[0-9]{2}|[1-9]?[0-9])
|
0[Xx]0*[0-9A-Fa-f]{1,2}
|
0+[1-3]?[0-9]{1,2}
)
|
(
[1-3][0-9]{1,9}
|
[1-9][0-9]{,8}
|
(4([0-1][0-9]{8}
|2([0-8][0-9]{7}
|9([0-3][0-9]{6}
|4([0-8][0-9]{5}
|9([0-5][0-9]{4}
|6([0-6][0-9]{3}
|7([0-1][0-9]{2}
|2([0-8][0-9]{1}
|9([0-5]
))))))))))
)
|
0[Xx]0*[0-9A-Fa-f]{1,8}
|
0+[1-3]?[0-7]{,10}
)\b
These IPv4 addresses are validated by the above RegEx.
127.0.0.1
2130706433
0x7F000001
017700000001
0x7F.0.0.01 # Mixed hex/dec/oct
000000000017700000001 # Have as many leading zeros as you want
0x0000000000007F000001 # Same as above
127.1
127.0.1
These are rejected.
256.0.0.1
192.168.1.099 # 099 is not a valid number
4294967296 # UINT32_MAX + 1
0x100000000
020000000000
The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The code above depends on the nuget package RestSharp, which you can easily install.
I have had a similar issue recently and realised that it's not due to background-size:cover
but background-attachment:fixed
.
I solved the issue by using a media query for iPhone and setting background-attachment
property to scroll
.
For my case:
.cover {
background-size: cover;
background-attachment: fixed;
background-position: center center;
@media (max-width: @iphone-screen) {
background-attachment: scroll;
}
}
Edit: The code block is in LESS and assumes a pre-defined variable for @iphone-screen
. Thanks for the notice @stephband.
java.io.DataInput.readUTF()
and java.io.DataOutput.writeUTF(String)
say that a String
object is represented by two bytes of length information and the modified UTF-8 representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with DataInput
and DataOutput
.
In addition, The specification of CONSTANT_Utf8_info
found in the Java virtual machine specification defines the structure as follows.
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
You can find that the size of 'length' is two bytes.
That the return type of a certain method (e.g. String.length()
) is int
does not always mean that its allowed maximum value is Integer.MAX_VALUE
. Instead, in most cases, int
is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of int
are converted to int
before calculation (if my memory serves me correctly) and it is one reason to choose int
when there is no special reason.
The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the modified UTF-8 representation, not the number of characters in a String
object.
String
objects may be able to have much more characters at runtime. However, if you want to use String
objects with DataInput
and DataOutput
interfaces, it is better to avoid using too long String
objects. I found this limitation when I implemented Objective-C equivalents of DataInput.readUTF()
and DataOutput.writeUTF(String)
.
Jonathan from the ExcelCentral forums suggests:
=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1
This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:
=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1
For weeks beginning on Tuesday, use:
=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1
etc.
I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).
If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.
Ex.
Filename: csvsample.php
class csvsample {
}
This is what I did to integrate Identity with an existing database.
Create a sample MVC project with MVC template. This has all the code needed for Identity implementation - Startup.Auth.cs, IdentityConfig.cs, Account Controller code, Manage Controller, Models and related views.
Install the necessary nuget packages for Identity and OWIN. You will get an idea by seeing the references in the sample Project and the answer by @Sam
Copy all these code to your existing project. Please note don't forget to add the "DefaultConnection" connection string for Identity to map to your database. Please check the ApplicationDBContext class in IdentityModel.cs where you will find the reference to "DefaultConnection" connection string.
This is the SQL script I ran on my existing database to create necessary tables:
USE ["YourDatabse"]
GO
/****** Object: Table [dbo].[AspNetRoles] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetRoles](
[Id] [nvarchar](128) NOT NULL,
[Name] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserClaims] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserClaims](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserLogins] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserLogins](
[LoginProvider] [nvarchar](128) NOT NULL,
[ProviderKey] [nvarchar](128) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED
(
[LoginProvider] ASC,
[ProviderKey] ASC,
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserRoles] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserRoles](
[UserId] [nvarchar](128) NOT NULL,
[RoleId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUsers] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUsers](
[Id] [nvarchar](128) NOT NULL,
[Email] [nvarchar](256) NULL,
[EmailConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](max) NULL,
[SecurityStamp] [nvarchar](max) NULL,
[PhoneNumber] [nvarchar](max) NULL,
[PhoneNumberConfirmed] [bit] NOT NULL,
[TwoFactorEnabled] [bit] NOT NULL,
[LockoutEndDateUtc] [datetime] NULL,
[LockoutEnabled] [bit] NOT NULL,
[AccessFailedCount] [int] NOT NULL,
[UserName] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[AspNetUserClaims] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[AspNetUserLogins] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[AspNetUserRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[AspNetRoles] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
GO
ALTER TABLE [dbo].[AspNetUserRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
GO
Check and solve any remaining errors and you are done. Identity will handle the rest :)
((1,2,3,4),
(5,6,7,8),
(9,0,1,2))
Using tuples instead of lists makes it marginally harder to change the data structure in unwanted ways.
If you are going to do extensive use of those, you are best off wrapping a true number array in a class, so you can define methods and properties on them. (Or, you could NumPy, SciPy, ... if you are going to do your processing with those libraries.)
Basically what you do is correct. Looking at redmine docs you linked to, it seems that suffix after the dot in the url denotes type of posted data (.json for JSON, .xml for XML), which agrees with the response you get - Processing by AttachmentsController#upload as XML
. I guess maybe there's a bug in docs and to post binary data you should try using http://redmine/uploads
url instead of http://redmine/uploads.xml
.
Btw, I highly recommend very good and very popular Requests library for http in Python. It's much better than what's in the standard lib (urllib2). It supports authentication as well but I skipped it for brevity here.
import requests
with open('./x.png', 'rb') as f:
data = f.read()
res = requests.post(url='http://httpbin.org/post',
data=data,
headers={'Content-Type': 'application/octet-stream'})
# let's check if what we sent is what we intended to send...
import json
import base64
assert base64.b64decode(res.json()['data'][len('data:application/octet-stream;base64,'):]) == data
UPDATE
To find out why this works with Requests but not with urllib2 we have to examine the difference in what's being sent. To see this I'm sending traffic to http proxy (Fiddler) running on port 8888:
Using Requests
import requests
data = 'test data'
res = requests.post(url='http://localhost:8888',
data=data,
headers={'Content-Type': 'application/octet-stream'})
we see
POST http://localhost:8888/ HTTP/1.1
Host: localhost:8888
Content-Length: 9
Content-Type: application/octet-stream
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/1.0.4 CPython/2.7.3 Windows/Vista
test data
and using urllib2
import urllib2
data = 'test data'
req = urllib2.Request('http://localhost:8888', data)
req.add_header('Content-Length', '%d' % len(data))
req.add_header('Content-Type', 'application/octet-stream')
res = urllib2.urlopen(req)
we get
POST http://localhost:8888/ HTTP/1.1
Accept-Encoding: identity
Content-Length: 9
Host: localhost:8888
Content-Type: application/octet-stream
Connection: close
User-Agent: Python-urllib/2.7
test data
I don't see any differences which would warrant different behavior you observe. Having said that it's not uncommon for http servers to inspect User-Agent
header and vary behavior based on its value. Try to change headers sent by Requests one by one making them the same as those being sent by urllib2 and see when it stops working.
The base dn is dc=example,dc=com
.
I don't know about openca, but I will try this answer since you got very little traffic so far.
A base dn is the point from where a server will search for users. So I would try to simply use admin
as a login name.
If openca behaves like most ldap aware applications, this is what is going to happen :
admin
will be done by the server starting at the base dn (dc=example,dc=com
).cn=admin,dc=example,dc=com
) will be used to bind with the supplied password.Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :
dn
your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com
.objectClass
for your admin
user. It will be either inetOrgPerson
or user
. There will be others like top
, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson)
. Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user))
. Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.
Just compare the year, month and day values.
Declare @DateToSearch DateTime
Set @DateToSearch = '14 AUG 2008'
SELECT *
FROM table1
WHERE Year(column_datetime) = Year(@DateToSearch)
AND Month(column_datetime) = Month(@DateToSearch)
AND Day(column_datetime) = Day(@DateToSearch)
An addition to Christopher Bradford's answer to use the HTML escaping anywhere,
since most people don't use CGI
nowadays, you can also use Rack
:
require 'rack/utils'
Rack::Utils.escape_html('Usage: foo "bar" <baz>')
EXEC sys.sp_configure N'max server memory (MB)', N'2147483646'
GO
RECONFIGURE WITH OVERRIDE
GO
What value you specify for the server memory is not important, as long as it differs from the current one.
Btw, the thing that causes the speedup is not the query cache, but the data cache.
Here is the example works fine in oracle
select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');
You can start with Instant.ofEpochMilli(long):
LocalDate date =
Instant.ofEpochMilli(startDateLong)
.atZone(ZoneId.systemDefault())
.toLocalDate();
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
There is a system property eclipse.buildId (for example, for Eclipse Luna, I have 4.4.1.M20140925-0400 as a value there).
I'm not sure in which version of Eclipse did this property become available.
Also, dive right in and explore all the available system properties -- there is quite a bit of information available under eclipse.*, os.* osgi.* and org.osgi.* namespaces.
UPDATE!
After experimenting with different Eclipse versions, it seems that eclipse.buildId
system property is not the way to go. For example, on Eclipse Luna 4.4.0, it gives the result of 4.4.2.M20150204-1700
which is obviously incorrect.
I suspect eclipse.buildId
system property is set to the version of org.eclipse.platform
plugin. Unfortunately, this does not (always) give the correct result. However, good news is that I have a solution with working code sample which I will outline in a separate answer.
for file in Data/*.txt
do
for ((i = 0; i < 3; i++))
do
name=${file##*/}
base=${name%.txt}
./MyProgram.exe "$file" Logs/"${base}_Log$i.txt"
done
done
The name=${file##*/}
substitution (shell parameter expansion) removes the leading pathname up to the last /
.
The base=${name%.txt}
substitution removes the trailing .txt
. It's a bit trickier if the extensions can vary.
try
- catch
- finally
are the key words for using exception handling case.
As normal explanotory
try {
//code statements
//exception thrown here
//lines not reached if exception thrown
} catch (Exception e) {
//lines reached only when exception is thrown
} finally {
// always executed when the try block is exited
//independent of an exception thrown or not
}
The finally block prevent executing...
System.exit(0);
An easy solution for most situations: copy/paste the markdown into a viewer in the "cloud." Here are two choices:
Nothing to install! Cross platform! Cross browser! Always available!
Disadvantages: could be hassle for large files, standard cloud application security issues.
For those who are complining about Michael Tiptop's solution not working, here is the .Net4+ way of doing it:
public static string StripTags(this string markup)
{
try
{
StringReader sr = new StringReader(markup);
XPathDocument doc;
using (XmlReader xr = XmlReader.Create(sr,
new XmlReaderSettings()
{
ConformanceLevel = ConformanceLevel.Fragment
// for multiple roots
}))
{
doc = new XPathDocument(xr);
}
return doc.CreateNavigator().Value; // .Value is similar to .InnerText of
// XmlDocument or JavaScript's innerText
}
catch
{
return string.Empty;
}
}
Php has an function to count the occurrences in the array http://www.php.net/manual/en/function.array-count-values.php
You may be confusing Javascript arrays with PHP arrays. In PHP, arrays are very flexible. They can either be numerically indexed or associative, or even mixed.
array('Item 1', 'Item 2', 'Items 3') // numerically indexed array
array('first' => 'Item 1', 'second' => 'Item 2') // associative array
array('first' => 'Item 1', 'Item 2', 'third' => 'Item 3')
Other languages consider these two to be different things, Javascript being among them. An array in Javascript is always numerically indexed:
['Item 1', 'Item 2', 'Item 3'] // array (numerically indexed)
An "associative array", also called Hash or Map, technically an Object in Javascript*, works like this:
{ first : 'Item 1', second : 'Item 2' } // object (a.k.a. "associative array")
They're not interchangeable. If you need "array keys", you need to use an object. If you don't, you make an array.
*
Technically everything is an Object in Javascript, please put that aside for this argument. ;)
$(window).scroll(function() {
$('.logo_container, .slogan').css({
"opacity" : ".1",
"transition" : "opacity .8s ease-in-out"
});
});
Check the fiddle: http://jsfiddle.net/2k3hfwo0/2/
The easiest way is to create C# Process and launch external tool to print your PDF file
private static void ExecuteRawFilePrinter() {
Process process = new Process();
process.StartInfo.FileName = "c:\\Program Files (x86)\\RawFilePrinter\\RawFilePrinter.exe";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.Arguments = string.Format("-p \"c:\\Users\\Me\\Desktop\\mypdffile.pdf\" \"gdn02ptr006\"");
process.Start();
process.WaitForExit();
}
Code above launches RawFilePrinter.exe (similar to 2Printer.exe), but with better support. It is not free, but by making donation allow you to use it everywhere and redistribute with your application. Latest version to download: http://bigdotsoftware.pl/rawfileprinter
You could add dataformatstring="{0:M-dd-yyyy}
" attribute to the bound field, like this:
<asp:BoundField DataField="Date" HeaderText="Date" DataFormatString="{0:dd-M-yyyy}" />
I Faced the same issue. For me it was just to unckeck the option :
Tablix Properties=> Page Break Option => Keep together on one page if possible
Of SSRS Report. It was trying to put all records on the same page instead of creating many pages.
Alternative solution that worked really well for me:
init: function() {
this.on("addedfile", function(event) {
while (this.files.length > this.options.maxFiles) {
this.removeFile(this.files[0]);
}
});
}
I have a same problem, with volley, but this is my solution:
In Android Manifiest, in tag application add:
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"
create in folder xml this file network_security_config.xml and write this:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
inside tag application add this tag:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
This works with multiple statements:
if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6
Or you can split it over multiple lines:
if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6
The container div, and sometimes content div, are almost always used to allow for more sophisticated CSS styling. The body tag is special in some ways. Browsers don't treat it like a normal div; its position and dimensions are tied to the browser window.
But a container div is just a div and you can style it with margins and borders. You can give it a fixed width, and you can center it with margin-left: auto; margin-right: auto
.
Plus, content, like a copyright notice for example, can go on the outside of the container div, but it can't go on the outside of the body, allowing for content on the outside of a border.
From http://www.sqlite.org/lang_createtable.html:
CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);
How to delete a non empty folder using unlinkat() in c?
Here is my work on it:
/*
* Program to erase the files/subfolders in a directory given as an input
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void remove_dir_content(const char *path)
{
struct dirent *de;
char fname[300];
DIR *dr = opendir(path);
if(dr == NULL)
{
printf("No file or directory found\n");
return;
}
while((de = readdir(dr)) != NULL)
{
int ret = -1;
struct stat statbuf;
sprintf(fname,"%s/%s",path,de->d_name);
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
continue;
if(!stat(fname, &statbuf))
{
if(S_ISDIR(statbuf.st_mode))
{
printf("Is dir: %s\n",fname);
printf("Err: %d\n",ret = unlinkat(dirfd(dr),fname,AT_REMOVEDIR));
if(ret != 0)
{
remove_dir_content(fname);
printf("Err: %d\n",ret = unlinkat(dirfd(dr),fname,AT_REMOVEDIR));
}
}
else
{
printf("Is file: %s\n",fname);
printf("Err: %d\n",unlink(fname));
}
}
}
closedir(dr);
}
void main()
{
char str[10],str1[20] = "../",fname[300]; // Use str,str1 as your directory path where it's files & subfolders will be deleted.
printf("Enter the dirctory name: ");
scanf("%s",str);
strcat(str1,str);
printf("str1: %s\n",str1);
remove_dir_content(str1); //str1 indicates the directory path
}
Below is an alternative implementation of a 'create user' controller method using Claims based roles.
The created claims then work with the Authorize attribute e.g. [Authorize(Roles = "Admin, User.*, User.Create")]
// POST api/User/Create
[Route("Create")]
public async Task<IHttpActionResult> Create([FromBody]CreateUserModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Generate long password for the user
var password = System.Web.Security.Membership.GeneratePassword(25, 5);
// Create the user
var user = new ApiUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
// Add roles (permissions) for the user
foreach (var perm in model.Permissions)
{
await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, perm));
}
return Ok<object>(new { UserName = user.UserName, Password = password });
}
It seems that the only parameter that allows you to inject custom text is the "quote".
https://www.facebook.com/sharer/sharer.php?u=THE_URL"e=THE_CUSTOM_TEXT
There is a built in method which would be the fastest method also, calling tolist
on the .values
np array:
df.values.tolist()
[[0.0, 3.61, 380.0, 3.0],
[1.0, 3.67, 660.0, 3.0],
[1.0, 3.19, 640.0, 4.0],
[0.0, 2.93, 520.0, 4.0]]
Just go to Google Fonts - http://www.google.com/fonts/ , add the font you like to your collection, and press the download button. And then just use the @fontface to connect this font to your web page. Btw, if you open the link you are using, you'll see an example of using @fontface
http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600,300
For an example
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
src: local('Open Sans Light'), local('OpenSans-Light'), url(http://themes.googleusercontent.com/static/fonts/opensans/v6/DXI1ORHCpsQm3Vp6mXoaTaRDOzjiPcYnFooOUGCOsRk.woff) format('woff');
}
Just change the url address to the local link on the font file, you've downloaded.
You can do it even easier.
Just download the file, you've linked:
http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600,300
Name it opensans.css or so.
Then just change the links in url() to your path to font files.
And then replace your example string with:
<link href='opensans.css' rel='stylesheet' type='text/css'>
CDATA is Obsolete.
Note that CDATA sections should not be used within HTML; they only work in XML.
So do not use it in HTML 5.
https://developer.mozilla.org/en-US/docs/Web/API/CDATASection#Specifications
If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8
into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.
Try:
php_value error_reporting 2039
It seems you can provide just the local image name, assuming it is in the same folder...
It suffices like:
background-image: url("img1.png")
In addition to using pure threads or the Celery queue (note that flask-celery is no longer required), you could also have a look at flask-apscheduler:
https://github.com/viniciuschiele/flask-apscheduler
A simple example copied from https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py:
from flask import Flask
from flask_apscheduler import APScheduler
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'jobs:job1',
'args': (1, 2),
'trigger': 'interval',
'seconds': 10
}
]
SCHEDULER_API_ENABLED = True
def job1(a, b):
print(str(a) + ' ' + str(b))
if __name__ == '__main__':
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
# it is also possible to enable the API directly
# scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
app.run()
In addition to the other answers, the following directory contains deletable system images on a Mac for Android Studio 2.3.3. I was able to delete the android-16 and android-17 directories without any problem because I didn't have any emulators which used them. (I kept the android-24 which was in use.)
$ pwd
/Users/gareth/Library/Android/sdk/system-images
$ du -h
2.5G ./android-16/default/x86
2.5G ./android-16/default
2.5G ./android-16/google_apis/x86
2.5G ./android-16/google_apis
5.1G ./android-16
2.5G ./android-17/default/x86
2.5G ./android-17/default
2.5G ./android-17
3.0G ./android-24/default/x86_64
3.0G ./android-24/default
3.0G ./android-24
11G .
What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?
From Google's "I'm Feeling Lucky" on vmalloc
:
kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before memory gets fragmented.
So with the code you have provided.
var bytes = Convert.FromBase64String(resizeImage.Content);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes ,0, bytes.Length);
imageFile.Flush();
}
The code of exchange is below:
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException
Exception RestClientException
has HttpClientErrorException
and HttpStatusCodeException
exception.
So in RestTemplete
there may occure HttpClientErrorException
and HttpStatusCodeException
exception.
In exception object you can get exact error message using this way: exception.getResponseBodyAsString()
Here is the example code:
public Object callToRestService(HttpMethod httpMethod, String url, Object requestObject, Class<?> responseObject) {
printLog( "Url : " + url);
printLog( "callToRestService Request : " + new GsonBuilder().setPrettyPrinting().create().toJson(requestObject));
try {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(requestObject, requestHeaders);
long start = System.currentTimeMillis();
ResponseEntity<?> responseEntity = restTemplate.exchange(url, httpMethod, entity, responseObject);
printLog( "callToRestService Status : " + responseEntity.getStatusCodeValue());
printLog( "callToRestService Body : " + new GsonBuilder().setPrettyPrinting().create().toJson(responseEntity.getBody()));
long elapsedTime = System.currentTimeMillis() - start;
printLog( "callToRestService Execution time: " + elapsedTime + " Milliseconds)");
if (responseEntity.getStatusCodeValue() == 200 && responseEntity.getBody() != null) {
return responseEntity.getBody();
}
} catch (HttpClientErrorException exception) {
printLog( "callToRestService Error :" + exception.getResponseBodyAsString());
//Handle exception here
}catch (HttpStatusCodeException exception) {
printLog( "callToRestService Error :" + exception.getResponseBodyAsString());
//Handle exception here
}
return null;
}
Here is the code description:
In this method you have to pass request and response class. This method will automatically parse response as requested object.
First of All you have to add message converter.
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
Then you have to add requestHeader
.
Here is the code:
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(requestObject, requestHeaders);
Finally, you have to call exchange method:
ResponseEntity<?> responseEntity = restTemplate.exchange(url, httpMethod, entity, responseObject);
For prety printing i used Gson library.
here is the gradle : compile 'com.google.code.gson:gson:2.4'
You can just call the bellow code to get response:
ResponseObject response=new RestExample().callToRestService(HttpMethod.POST,"URL_HERE",new RequestObject(),ResponseObject.class);
Here is the full working code:
import com.google.gson.GsonBuilder;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
public class RestExample {
public RestExample() {
}
public Object callToRestService(HttpMethod httpMethod, String url, Object requestObject, Class<?> responseObject) {
printLog( "Url : " + url);
printLog( "callToRestService Request : " + new GsonBuilder().setPrettyPrinting().create().toJson(requestObject));
try {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(requestObject, requestHeaders);
long start = System.currentTimeMillis();
ResponseEntity<?> responseEntity = restTemplate.exchange(url, httpMethod, entity, responseObject);
printLog( "callToRestService Status : " + responseEntity.getStatusCodeValue());
printLog( "callToRestService Body : " + new GsonBuilder().setPrettyPrinting().create().toJson(responseEntity.getBody()));
long elapsedTime = System.currentTimeMillis() - start;
printLog( "callToRestService Execution time: " + elapsedTime + " Milliseconds)");
if (responseEntity.getStatusCodeValue() == 200 && responseEntity.getBody() != null) {
return responseEntity.getBody();
}
} catch (HttpClientErrorException exception) {
printLog( "callToRestService Error :" + exception.getResponseBodyAsString());
//Handle exception here
}catch (HttpStatusCodeException exception) {
printLog( "callToRestService Error :" + exception.getResponseBodyAsString());
//Handle exception here
}
return null;
}
private void printLog(String message){
System.out.println(message);
}
}
Thanks :)
Assuming two decimal places on your percentages, the data type you use depends on how you plan to store your percentages. If you are going to store their fractional equivalent (e.g. 100.00% stored as 1.0000), I would store the data in a decimal(5,4)
data type with a CHECK
constraint that ensures that the values never exceed 1.0000 (assuming that is the cap) and never go below 0 (assuming that is the floor). If you are going to store their face value (e.g. 100.00% is stored as 100.00), then you should use decimal(5,2)
with an appropriate CHECK
constraint. Combined with a good column name, it makes it clear to other developers what the data is and how the data is stored in the column.
all answers are correct, but I want to mention that time delta accepts negative arguments.
>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses
File -> Spreadsheet Settings -> (Tab) Calculation -> Recalculation (3 Options)
- On change
- On change and every minute
- On change and every hour
This affects how often NOW, TODAY, RAND, and RANDBETWEEN are updated.
but..
.. it updates only, if the functions arguments (their ranges, cells) are affected by that.
from my example
I use google spreadsheet to find out the age of a person. I have his birthday date in the format (dd.mm.yyyy) -> it's the used format here in Switzerland.
=ARRAYFORMULA(IF(ISTEXT(K4:K), IF(TODAY() - DATE(YEAR(TODAY()), MONTH(REGEXREPLACE(K4:K, "[.]", "/")), DAY(REGEXREPLACE(K4:K, "[.]", "/"))) > 0, YEAR(TODAY()) - YEAR(REGEXREPLACE(K4:K, "[.]", "/")) + 1, YEAR(TODAY()) - YEAR(REGEXREPLACE(K4:K, "[.]", "/"))), IF(LEN(K4:K) > 0, IF(TODAY() - DATE(YEAR(TODAY()), MONTH(K4:K), DAY(K4:K)) > 0, YEAR(TODAY()) - YEAR(K4:K) + 1, YEAR(TODAY()) - YEAR(K4:K)), "")))
I'm using TODAY()
and I did the recalculation settings described above. -> but no automatically refresh. :-(
It updates only, if I change some value inside the ranges where the function is looking for.
So I wrote a Google Script (Tools -> Script Editor..) for that purpose.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetMaster = ss.getSheetByName("Master");
var sortRange = sheetMaster.getRange(firstRow, firstColumn, lastRow, lastColumn);
sortRange.getCell(1, 2).setValue(sortRange.getCell(1, 2).getValue());
}
You need to set numbers for firstRow
, firstColumn
, lastRow
, lastColumn
The Script get active when the spreadsheets open, writes the content of one cell into the same cell again. That's enough to trigger the TODAY()
function.
Look for more information on that link from Edward Moffett. Force google sheet formula to recalculate
Best regards,
Christoph
I got the same problem after upgrading java from 1.8.0_202 to 1.8.0_211
Problem:
Here are directories where new version of 1.8.0_211 of Java installed:
Directory of c:\Program Files\Java\jre1.8.0_211\bin Directory of c:\Program Files (x86)\Common Files\Oracle\Java\javapath
So one is located in 32 bit and second is in 64 bit Program files folder. The one that is specified in the PATH is 32 bit version (c:\Program Files (x86)\Common Files\Oracle\Java\javapath), even though it was 64 bit version of the Java that was installed.
Solution:
Change system environments variable PATH from c:\Program Files (x86)\Common Files\Oracle\Java\javapath to c:\Program Files\Java\jre1.8.0_211\bin
I wouldn't advise this, it goes against standard practices, and doesn't offer that much in return. You want to keep the body for content, not options.
I created the following procedure
:
if object_id('tool.create_insert', 'P') is null
begin
exec('create procedure tool.create_insert as');
end;
go
alter procedure tool.create_insert(@schema varchar(200) = 'dbo',
@table varchar(200),
@where varchar(max) = null,
@top int = null,
@insert varchar(max) output)
as
begin
declare @insert_fields varchar(max),
@select varchar(max),
@error varchar(500),
@query varchar(max);
declare @values table(description varchar(max));
set nocount on;
-- Get columns
select @insert_fields = isnull(@insert_fields + ', ', '') + c.name,
@select = case type_name(c.system_type_id)
when 'varchar' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + cast(' + c.name + ' as varchar) + '''''''', ''null'')'
when 'datetime' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + convert(varchar, ' + c.name + ', 121) + '''''''', ''null'')'
else isnull(@select + ' + '', '' + ', '') + 'isnull(cast(' + c.name + ' as varchar), ''null'')'
end
from sys.columns c with(nolock)
inner join sys.tables t with(nolock) on t.object_id = c.object_id
inner join sys.schemas s with(nolock) on s.schema_id = t.schema_id
where s.name = @schema
and t.name = @table;
-- If there's no columns...
if @insert_fields is null or @select is null
begin
set @error = 'There''s no ' + @schema + '.' + @table + ' inside the target database.';
raiserror(@error, 16, 1);
return;
end;
set @insert_fields = 'insert into ' + @schema + '.' + @table + '(' + @insert_fields + ')';
if isnull(@where, '') <> '' and charindex('where', ltrim(rtrim(@where))) < 1
begin
set @where = 'where ' + @where;
end
else
begin
set @where = '';
end;
set @query = 'select ' + isnull('top(' + cast(@top as varchar) + ')', '') + @select + ' from ' + @schema + '.' + @table + ' with (nolock) ' + @where;
insert into @values(description)
exec(@query);
set @insert = isnull(@insert + char(10), '') + '--' + upper(@schema + '.' + @table);
select @insert = @insert + char(10) + @insert_fields + char(10) + 'values(' + v.description + ');' + char(10) + 'go' + char(10)
from @values v
where isnull(v.description, '') <> '';
end;
go
Then you can use it that way:
declare @insert varchar(max),
@part varchar(max),
@start int,
@end int;
set @start = 1;
exec tool.create_insert @schema = 'dbo',
@table = 'customer',
@where = 'id = 1',
@insert = @insert output;
-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
set @end = charindex(char(10), @insert);
if @end = 0
begin
set @end = len(@insert) + 1;
end;
print substring(@insert, @start, @end - 1);
set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;
The output would be something like that:
--DBO.CUSTOMER
insert into dbo.customer(id, name, type)
values(1, 'CUSTOMER NAME', 'F');
go
If you just want to get a range of rows, use the @top
parameter as bellow:
declare @insert varchar(max),
@part varchar(max),
@start int,
@end int;
set @start = 1;
exec tool.create_insert @schema = 'dbo',
@table = 'customer',
@top = 100,
@insert = @insert output;
-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
set @end = charindex(char(10), @insert);
if @end = 0
begin
set @end = len(@insert) + 1;
end;
print substring(@insert, @start, @end - 1);
set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;
The previous answers have lost the first frame. And it will be nice to store the images in a folder.
# create a folder to store extracted images
import os
folder = 'test'
os.mkdir(folder)
# use opencv to do the job
import cv2
print(cv2.__version__) # my version is 3.1.0
vidcap = cv2.VideoCapture('test_video.mp4')
count = 0
while True:
success,image = vidcap.read()
if not success:
break
cv2.imwrite(os.path.join(folder,"frame{:d}.jpg".format(count)), image) # save frame as JPEG file
count += 1
print("{} images are extacted in {}.".format(count,folder))
By the way, you can check the frame rate by VLC. Go to windows -> media information -> codec details
Once a thread is started, it is not necessary to retain a reference to the Thread object. The thread continues to execute until the thread procedure ends.
new Thread(new ThreadStart(SecondFoo)).Start();
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<solid android:color="@color/colorAccent" />
<corners
android:bottomLeftRadius="500dp"
android:bottomRightRadius="500dp"
android:topLeftRadius="500dp"
android:topRightRadius="500dp" />
</shape>
Now, in which element you want to use this shape just add:
android:background="@drawable/custom_round_ui_shape"
Create a new XML in drawable named "custom_round_ui_shape"
As @David Heffeman indicates the recommendation is to use .yaml
when possible, and the recommendation has been that way since September 2006.
That some projects use .yml
is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).
The best way to approach this is to be rigorous when creating new files (i.e. use .yaml
) and be permissive when accepting input (i.e. allow .yml
when you encounter it), possible automatically upgrading/correcting these errors when possible.
The other recommendation I have is to document the argument(s) why you have to use .yml
, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml
has more pages than .yaml
" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml
extension instead of the correct .yaml
, but I think you will be hard pressed to do so.
Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose
used .yml
, but in later versions started to use .yaml
, although they still support .yml
). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml
instead of appveyor.yml
for building the windows wheels of my YAML parser for Python).
On the other hand:
The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.
So it seems fitting that they also use a subset of the recommended extension.
Your understanding of foreach
is incomplete.
It works with any type that exposes IEnumerable
(or implements a GetEnumerable
method) and uses the returned IEnumerator
to iterate over the items in the collection.
How the Enumerator
does this (using an index, yield
statement or magic) is an implementation detail.
In order to achieve what you want, you should use a for
loop:
for (int i = 0; i < mylist.Count; i++)
{
}
Note:
Getting the number of items in a list is slightly different depending on the type of list
For Collections: Use Count [property]
For Arrays: Use Length [property]
For IEnumerable: Use Count() [Linq method]
it is just that add below code in the index.html head tag
<html>
<head>
<base href="/">
...
that worked like a charm for me.
It's not because it doesn't make sense; it makes perfect sense to define "x++" as "x += 1, evaluating to the previous binding of x".
If you want to know the original reason, you'll have to either wade through old Python mailing lists or ask somebody who was there (eg. Guido), but it's easy enough to justify after the fact:
Simple increment and decrement aren't needed as much as in other languages. You don't write things like for(int i = 0; i < 10; ++i)
in Python very often; instead you do things like for i in range(0, 10)
.
Since it's not needed nearly as often, there's much less reason to give it its own special syntax; when you do need to increment, +=
is usually just fine.
It's not a decision of whether it makes sense, or whether it can be done--it does, and it can. It's a question of whether the benefit is worth adding to the core syntax of the language. Remember, this is four operators--postinc, postdec, preinc, predec, and each of these would need to have its own class overloads; they all need to be specified, and tested; it would add opcodes to the language (implying a larger, and therefore slower, VM engine); every class that supports a logical increment would need to implement them (on top of +=
and -=
).
This is all redundant with +=
and -=
, so it would become a net loss.
There is a hack that can be done to use GIF images to show true color. One can prepare a GIF animation with 256 color paletted frames with 0 frame delay and set the animation to be shown only once. So, all frames could be shown at the same time. At the end, a true colored GIF image is rendered.
Many software is capable of preparing such GIF images. However, the output file size is larger than a PNG file. It must be used if it is really necessary.
Edit: As @mwfarnley mentioned, there might be hiccups. Still, there are still possible workarounds. One may see a working example here. The final rendered image looks like that:
You've got the right idea, so here's how to go ahead: the onclick
handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:
<script type="text/javascript">
function recp(id) {
$('#myStyle').load('data.php?id=' + id);
}
</script>
<a href="#" onClick="recp('1')" > One </a>
<a href="#" onClick="recp('2')" > Two </a>
<a href="#" onClick="recp('3')" > Three </a>
<div id='myStyle'>
</div>
Then you put your PHP code into a separate file: (I've called it data.php
in the above example)
<?php
require ('myConnect.php');
$id = $_GET['id'];
$results = mysql_query("SELECT para FROM content WHERE para_ID='$id'");
if( mysql_num_rows($results) > 0 )
{
$row = mysql_fetch_array( $results );
echo $row['para'];
}
?>
If you want specific users to have access to all or part of the WMI object space, you need to permission them as shown here. Note that you have to be running on as an admin to perform this setting.
You can use JSON.stringify(object)
with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array))
, which is the following code (more detail can be found on this answer):
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
}
To make it more generic, you can override the JSON.stringify
function and you won't have to worry about it again, to do this, just paste this at the top of your page:
// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
return oldJSONStringify(convArrToObj(input));
};
})();
And now JSON.stringify
will accept arrays
or objects
! (link to jsFiddle with example)
Edit:
Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array)
always returns []
, which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify
with an object
):
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
A little simpler than Lars' answer:
something_needs_directory_xxx : xxx/..
and generic rule:
%/.. : ;@mkdir -p $(@D)
No touch-files to clean up or make .PRECIOUS :-)
If you want to see another little generic gmake trick, or if you're interested in non-recursive make with minimal scaffolding, you might care to check out Two more cheap gmake tricks and the other make-related posts in that blog.
.border-blue.background { ... }
is for one item with multiple classes.
.border-blue, .background { ... }
is for multiple items each with their own class.
.border-blue .background { ... }
is for one item where '.background' is the child of '.border-blue'.
See Chris' answer for a more thorough explanation.
You can use NOW()
:
INSERT INTO servers (server_name, online_status, exchange, disk_space, network_shares, c_time)
VALUES('m1', 'ONLINE', 'exchange', 'disk_space', 'network_shares', NOW())
I made an example resolving your problem.
You have to make a wrapper, float it, then position absolute your div and give to it 100% height.
HTML
<div class="container">
<div class="left">"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </div>
<div class="right-wrapper">
<div class="right">"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." </div>
</div>
<div class="clear"> </div>
</div>
CSS:
.container {
width: 100%;
position:relative;
}
.left {
width: 50%;
background-color: rgba(0, 0, 255, 0.6);
float: left;
}
.right-wrapper {
width: 48%;
float: left;
}
.right {
height: 100%;
position: absolute;
}
Explanation: The .right div is absolutely positioned. That means that its width and height, and top and left positiones will be calculed based on the first parent div absolutely or relative positioned ONLY if width or height properties are explicitly declared in CSS; if they aren't explicty declared, those properties will be calculed based on the parent container (.right-wrapper).
So, the 100% height of the DIV will be calculed based on .container final height, and the final position of .right position will be calculed based on the parent container.
Make sure you are running from that folder of your application, where you have the package.json.
Using jquery you might do something like this:
// To disable
$('#targetDiv').children().attr('disabled', 'disabled');
// To enable
$('#targetDiv').children().attr('enabled', 'enabled');
Here's a jsFiddle example: http://jsfiddle.net/monknomo/gLukqygq/
You could also select the target div's children and add a "disabled" css class to them with different visual properties as a callout.
//disable by adding disabled class
$('#targetDiv').children().addClass("disabled");
//enable by removing the disabled class
$('#targetDiv').children().removeClass("disabled");
Here's a jsFiddle with the as an example: https://jsfiddle.net/monknomo/g8zt9t3m/
All you have to do is use the value attribute of input tags:
<input type="text" value="Your Value" />
Or, in the case of a textarea:
<textarea>Your Value</textarea>
It's quite unpractical to make multiple select with size 1. think about it. I made a fiddle here: https://jsfiddle.net/wqd0yd5m/2/
<select name="test" multiple>
<option>123</option>
<option>456</option>
<option>789</option>
</select>
Try to explore other options such as using checkboxes to achieve your goal.
x^y
is not "x
to the power of y
". It's "x
XOR y
".
JPG and JPEG stand both for an image format proposed and supported by the Joint Photographic Experts Group. The two terms have the same meaning and are interchangeable.
To read on, check out Difference between JPG and JPEG.
The reason for the different file extensions dates back to the early versions of Windows. The original file extension for the Joint Photographic Expert Group File Format was ‘.jpeg’; however in Windows all files required a three letter file extension. So, the file extension was shortened to ‘.jpg’. However, Macintosh was not limited to three letter file extensions, so Mac users used ‘.jpeg’. Eventually, with upgrades Windows also began to accept ‘.jpeg’. However, many users were already used to ‘.jpg’, so both the three letter file extension and the four letter extension began to be commonly used, and still is.
Today, the most commonly accepted and used form is the ‘.jpg’, as many users were Windows users. Imaging applications, such as Adobe Photoshop, save all JPEG files with a ".jpg" extension on both Mac and Windows, in an attempt to avoid confusion. The Joint Photographic Expert Group File Format can also be saved with the upper-case ‘.JPEG’ and ‘.JPG’ file extensions, which are less common, but also accepted.
Just set the path variable to JDK bin in environment variables.
Variable Name : PATH
Variable Value : C:\Program Files\Java\jdk1.8.0_31\bin
But the best practice is to set JAVA_HOME and PATH as follow.
Variable Name : JAVA_HOME
Variable Value : C:\Program Files\Java\jdk1.8.0_31
Variable Name : PATH
Variable Value : %JAVA_HOME%\bin
This worked for me:
from matplotlib import pyplot as plt
from IPython.display import clear_output
import numpy as np
for i in range(50):
clear_output(wait=True)
y = np.random.random([10,1])
plt.plot(y)
plt.show()