You have to cast, I'm afraid:
f((byte)0);
I believe that will perform the appropriate conversion at compile-time instead of execution time, so it's not actually going to cause performance penalties. It's just inconvenient :(
Can you use boost?
samm$ cat split.cc
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <string>
#include <vector>
int
main()
{
std::string split_me( "hello world how are you" );
typedef std::vector<std::string> Tokens;
Tokens tokens;
boost::split( tokens, split_me, boost::is_any_of(" ") );
std::cout << tokens.size() << " tokens" << std::endl;
BOOST_FOREACH( const std::string& i, tokens ) {
std::cout << "'" << i << "'" << std::endl;
}
}
sample execution:
samm$ ./a.out
8 tokens
'hello'
'world'
''
'how'
'are'
''
''
'you'
samm$
Using the accepted answer you have to access each record by using Customers[i].customer
, and you need an extra CustomerJson
class, which is a little annoying. If you don't want to do that, you can use the following:
public class CustomerList
{
[JsonConverter(typeof(MyListConverter))]
public List<Customer> customer { get; set; }
}
Note that I'm using a List<>
, not an Array. Now create the following class:
class MyListConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Values())
{
var childToken = child.Children().First();
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(childToken.CreateReader(), newObject);
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
Axios.post solution with IE and other browsers
I've found some incredible solutions here. But they frequently don't take into account problems with IE browser. Maybe it will save some time to somebody else.
axios.post("/yourUrl"
, data,
{responseType: 'blob'}
).then(function (response) {
let fileName = response.headers["content-disposition"].split("filename=")[1];
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE variant
window.navigator.msSaveOrOpenBlob(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}),
fileName);
} else {
const url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', response.headers["content-disposition"].split("filename=")[1]);
document.body.appendChild(link);
link.click();
}
}
);
example above is for excel files, but with little changes can be applied to any format.
And on server I've done this to send an excel file.
response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=exceptions.xlsx")
location.reload(true); will hard reload the current page, ignoring the cache.
Cache.delete() can also be used for new chrome, firefox and opera.
Actually you can find very easy the day a video was created, right-click, property but remember it will only give the details of any copy date of the video but if you do click where it says DETAILS JUST there is the information you need, the original date that the archive was created on. Note that most modern devices will produce this information when you take pictures and videos but others will not.
For start Activity 2 from Activity 1 and get result, you could use startActivityForResult and implement onActivityResult in Activity 1 and use setResult in Activity2.
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(NUMERO1, numero1);
intent.putExtra(NUMERO2, numero2);
//startActivity(intent);
startActivityForResult(intent, MI_REQUEST_CODE);
You can use savefig()
to export to an image file:
plt.savefig('filename.png')
In addition, you can specify the dpi
argument to some scalar value, for example:
plt.savefig('filename.png', dpi=300)
Also try System.currentTimeMillis()
In my case I had the same issue on running from eclipse. Just did the following to resolve it: Right Click the Project --> Mavan --> Update Project.
And it worked!
Underscore-java has static method U.formatXml(string)
. I am the maintainer of the project. Live example
import com.github.underscore.lodash.U;
public class MyClass {
public static void main(String args[]) {
String xml = "<tag><nested>hello</nested></tag>";
System.out.println(U.formatXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>" + xml + "</root>"));
}
}
Output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<tag>
<nested>hello</nested>
</tag>
</root>
When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.
However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.
Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.
If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.
To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.
As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html
I linux this works too:
import sys
sys.path.extend(["/path/to/dotpy/file/"])
I made some improvements to the Darcula theme so it's a bit more usable for rubyists. You can find the repo and installation instructions Here.
You must write
<img src="theSource" style="width:30px;height:30px;" />
Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.
I haven't seen anything like this posted yet, but I thought I'd put it out there.
<div class="main">
<header>Header</header>
<div class="content">Content</div>
Then CSS:
body, html {
height: 100%;
margin: 0;
padding: 0;
}
.main {
height: 100%;
padding-top: 50px;
box-sizing: border-box;
}
header {
height: 50px;
margin-top: -50px;
width: 100%;
background-color: #5078a5;
}
.content {
height: 100%;
background-color: #999999;
}
Here is a working jsfiddle
Note: I have no idea what the browser compatability is for this. I was just playing around with alternate solutions and this seemed to work well.
Having trouble with a button onclick event in jsfiddle?
If so see Onclick event not firing on jsfiddle.net
My hack during development is to change my Deployment manifest to add the latest tag and always pull like so
image: etoews/my-image:latest
imagePullPolicy: Always
Then I delete the pod manually
kubectl delete pod my-app-3498980157-2zxhd
Because it's a Deployment, Kubernetes will automatically recreate the pod and pull the latest image.
A branch is just a reference to a commit. Until you commit anything to the repository, you don't have any branches. You can see this in a non-bare repository as well.
$ mkdir repo
$ cd repo
$ git init
Initialized empty Git repository in /home/me/repo/.git/
$ git branch
$ touch foo
$ git add foo
$ git commit -m "new file"
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 foo
$ git branch
* master
I have a completely different take on this. I use MailHide for this.
MailHide is a system from Google whereby the user needs to complete a reCAPTCHA test to then reveal the email to them.
There is no button type cancel https://www.w3schools.com/jsref/prop_pushbutton_type.asp
To achieve cancel functionality I used DOM history
<button type="button" class="btn btn-primary" onclick="window.history.back();">Cancel</button>
_x000D_
For more details : https://www.w3schools.com/jsref/met_his_back.asp
Though it is possible that something got deleted, it has been my experience that something gets screwed up in the project file. I have yet to pin down what that "something" is. I've had similar issues when the SDK installation is just fine. There are a couple of options.
First, add all of your files to a new project. This seems to usually work. Kind of a pain, though.
Second, you can right-click project in XCode/Get Info/Build/Library Search Paths. Add new paths similar to /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/usr/lib. Add appropriate versions of that string for each version (2.2.1, etc) and platform (simulator or iPhoneOS). Perform a similar action for Framework Search Paths if frameworks are your problem.
Third, which is more work but more reliable, is to open project.pbxproj from within MyProject.xcodeproj (Textmate is good for this). Look for "/* Begin XCBuildConfiguration section */", then "LIBRARY_SEARCH_PATHS" and "FRAMEWORK_SEARCH_PATHS". Add or modify the paths as appropriate, and save the file.
In any case, a pain in the butt, and I'd sure like to pin-point the cause because I've had this happen a couple of times. Project builds fine, then just up and refuses to do so with what seems to be little reason.
Just need to remove and re-install react-scripts
To Remove
yarn remove react-scripts
To Add
yarn add react-scripts
and then rm -rf node_modules/ yarn.lock && yarn
react-scripts
version mauallyIt's pretty crazy town that the only way to make checked false is to omit any values. With Angular 1.x, you can do this:
<input type="radio" ng-checked="false">
which is a lot more sane, if you need to make it unchecked.
One of the libraries that I use for Font Awesome is this:
https://github.com/Bearded-Hen/Android-Bootstrap
Specifically,
https://github.com/Bearded-Hen/Android-Bootstrap/wiki/Font-Awesome-Text
The documentation is easy to understand.
First, add the needed dependencies in the build.gradle:
dependencies {
compile 'com.beardedhen:androidbootstrap:1.2.3'
}
Secondly, you can add this in your XML:
<com.beardedhen.androidbootstrap.FontAwesomeText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fontawesometext:fa_icon="fa-github"
android:layout_margin="10dp"
android:textSize="32sp"
/>
but make sure you add this in your root layout if you want to use above code example:
xmlns:fontawesometext="http://schemas.android.com/apk/res-auto"
A quick wrap up. Maybe someone has a better explanation.
A call stack is composed of 1 or many several stack frames. Each stack frame corresponds to a call to a function or procedure which has not yet terminated with a return.
To use a stack frame, a thread keeps two pointers, one is called the Stack Pointer (SP), and the other is called the Frame Pointer (FP). SP always points to the "top" of the stack, and FP always points to the "top" of the frame. Additionally, the thread also maintains a program counter (PC) which points to the next instruction to be executed.
The following are stored on the stack: local variables and temporaries, actual parameters of the current instruction (procedure, function, etc.)
There are different calling conventions regarding the cleaning of the stack.
One way is (this is with Bash)
grep -P '\t'
-P
turns on Perl regular expressions so \t will work.
As user unwind says, it may be specific to GNU grep. The alternative is to literally insert a tab in there if the shell, editor or terminal will allow it.
You can simply write :
class A(object):
def __init__(self):
print "Initialiser A was called"
class B(A):
def __init__(self):
A.__init__(self)
# A.__init__(self,<parameters>) if you want to call with parameters
print "Initialiser B was called"
class C(B):
def __init__(self):
# A.__init__(self) # if you want to call most super class...
B.__init__(self)
print "Initialiser C was called"
Slightly off-topic: But here is if you have an Array of Dictionaries i.e: [ [String : String] ]
var array_has_dictionary = [ // Start of array
// Dictionary 1
[
"name" : "xxxx",
"age" : "xxxx",
"last_name":"xxx"
],
// Dictionary 2
[
"name" : "yyy",
"age" : "yyy",
"last_name":"yyy"
],
] // end of array
cell.textLabel?.text = Array(array_has_dictionary[1])[1].key
// Output: age -> yyy
try changing this part,
<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up for newsletter
for this
<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up for newsletter
You ask for quickest, but perhaps you mean "best" or "correct" or "typical"?
You also ask for commas to indicate thousands, but perhaps you mean "in normal human readable form according to the local custom of your user"?
You do it as so:
int i = 35634646;
String s = NumberFormat.getIntegerInstance().format(i);
Americans will get "35,634,646"
Germans will get "35.634.646"
Swiss Germans will get "35'634'646"
Models don't exist in isolation. The structures you'd define for a simulation of cars entering a car park, an embedded system which guides you to a free space, a car parking billing system or for the automated gates/ticket machines usual in car parks are all different.
Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().
from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])
sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']
tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')
We are selecting the last index (-1) of the tuple
As we can see in ActionController::Base
, before_action
is just a new syntax for before_filter
.
However all before_filters
syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1
Finally, the Chrome team will release a fix for this issue with Chrome 37 which will be released to public in July 2014. See example comparison of current stable Chrome 35 and latest Chrome 37 (early development preview) here:
1.) There is NO proper solution when loading fonts via @import
, <link href=
or Google's webfont.js
. The problem is that Chrome simply requests .woff files from Google's API which render horribly. Surprisingly all other font file types render beautifully. However, there are some CSS tricks that will "smoothen" the rendered font a little bit, you'll find the workaround(s) deeper in this answer.
2.) There IS a real solution for this when self-hosting the fonts, first posted by Jaime Fernandez in another answer on this Stackoverflow page, which fixes this issue by loading web fonts in a special order. I would feel bad to simply copy his excellent answer, so please have a look there. There is also an (unproven) solution that recommends using only TTF/OTF fonts as they are now supported by nearly all browsers.
3.) The Google Chrome developer team works on that issue. As there have been several huge changes in the rendering engine there's obviously something in progress.
I've written a large blog post on that issue, feel free to have a look: How to fix the ugly font rendering in Google Chrome
See how the example from the initial question look today, in Chrome 29:
Left: Firefox 23, right: Chrome 29
Top: Firefox 23, bottom: Chrome 29
Fixing the above screenshot with -webkit-text-stroke:
First row is default, second has:
-webkit-text-stroke: 0.3px;
Third row has:
-webkit-text-stroke: 0.6px;
So, the way to fix those fonts is simply giving them
-webkit-text-stroke: 0.Xpx;
or the RGBa syntax (by nezroy, found in the comments! Thanks!)
-webkit-text-stroke: 1px rgba(0,0,0,0.1)
There's also an outdated possibility: Give the text a simple (fake) shadow:
text-shadow: #fff 0px 1px 1px;
RGBa solution (found in Jasper Espejo's blog):
text-shadow: 0 0 1px rgba(51,51,51,0.2);
If you want to be updated on this issue, have a look on the according blog post: How to fix the ugly font rendering in Google Chrome. I'll post news if there're news on this.
This is a big bug in Google Chrome and the Google Chrome Team does know about this, see the official bug report here. Currently, in May 2013, even 11 months after the bug was reported, it's not solved. It's a strange thing that the only browser that messes up Google Webfonts is Google's own browser Chrome (!). But there's a simple workaround that will fix the problem, please see below for the solution.
STATEMENT FROM GOOGLE CHROME DEVELOPMENT TEAM, MAY 2013
Official statement in the bug report comments:
Our Windows font rendering is actively being worked on. ... We hope to have something within a milestone or two that developers can start playing with. How fast it goes to stable is, as always, all about how fast we can root out and burn down any regressions.
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
The default visibility (no keyword) is package which means that it will be available to every class that is located in the same package.
Interesting side note is that protected doesn't limit visibility to the subclasses but also to the other classes in the same package
You can also compare epoch seconds :
$d1->format('U') < $d2->format('U')
Source : http://laughingmeme.org/2007/02/27/looking-at-php5s-datetime-and-datetimezone/ (quite interesting article about DateTime)
Using slf4j and a wrapper is nice but the use of it's built in interpolation breaks down when you have more than two values to interpolate, since then you need to create an Array of values to interpolate.
A more Scala like solution is to use a thunk or cluster to delay the concatenation of the error message. A good example of this is Lift's logger
Which looks like this:
class Log4JLogger(val logger: Logger) extends LiftLogger {
override def trace(msg: => AnyRef) = if (isTraceEnabled) logger.trace(msg)
}
Note that msg is a call-by-name and won't be evaluated unless isTraceEnabled is true so there's no cost in generating a nice message string. This works around the slf4j's interpolation mechanism which requires parsing the error message. With this model, you can interpolate any number of values into the error message.
If you have a separate trait that mixes this Log4JLogger into your class, then you can do
trace("The foobar from " + a + " doesn't match the foobar from " +
b + " and you should reset the baz from " + c")
instead of
info("The foobar from {0} doesn't match the foobar from {1} and you should reset the baz from {c},
Array(a, b, c))
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.
-pattern_type glob
This great option makes it easier to select the images in many cases.
Slideshow video with one image per second
ffmpeg -framerate 1 -pattern_type glob -i '*.png' \
-c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
Add some music to it, cutoff when the presumably longer audio when the images end:
ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
-c:a copy -shortest -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
Here are two demos on YouTube:
Be a hippie and use the Theora patent-unencumbered video format:
ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
-c:a copy -shortest -c:v libtheora -r 30 -pix_fmt yuv420p out.ogg
Your images should of course be sorted alphabetically, typically as:
0001-first-thing.jpg
0002-second-thing.jpg
0003-and-third.jpg
and so on.
I would also first ensure that all images to be used have the same aspect ratio, possibly by cropping them with imagemagick
or nomacs beforehand, so that ffmpeg will not have to make hard decisions. In particular, the width has to be divisible by 2, otherwise conversion fails with: "width not divisible by 2".
Normal speed video with one image per frame at 30 FPS
ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
-c:v libx264 -pix_fmt yuv420p out.mp4
Here's what it looks like:
GIF generated with: https://askubuntu.com/questions/648603/how-to-create-an-animated-gif-from-mp4-video-via-command-line/837574#837574
Add some audio to it:
ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
-i audio.ogg -c:a copy -shortest -c:v libx264 -pix_fmt yuv420p out.mp4
Result: https://www.youtube.com/watch?v=HG7c7lldhM4
These are the test media I've used:a
wget -O opengl-rotating-triangle.zip https://github.com/cirosantilli/media/blob/master/opengl-rotating-triangle.zip?raw=true
unzip opengl-rotating-triangle.zip
cd opengl-rotating-triangle
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg
Images generated with: How to use GLUT/OpenGL to render to a file?
It is cool to observe how much the video compresses the image sequence way better than ZIP as it is able to compress across frames with specialized algorithms:
opengl-rotating-triangle.mp4
: 340K opengl-rotating-triangle.zip
: 7.3M Convert one music file to a video with a fixed image for YouTube upload
Answered at: https://superuser.com/questions/700419/how-to-convert-mp3-to-youtube-allowed-video-format/1472572#1472572
Full realistic slideshow case study setup step by step
There's a bit more to creating slideshows than running a single ffmpeg command, so here goes a more interesting detailed example inspired by this timeline.
Get the input media:
mkdir -p orig
cd orig
wget -O 1.png https://upload.wikimedia.org/wikipedia/commons/2/22/Australopithecus_afarensis.png
wget -O 2.jpg https://upload.wikimedia.org/wikipedia/commons/6/61/Homo_habilis-2.JPG
wget -O 3.jpg https://upload.wikimedia.org/wikipedia/commons/c/cb/Homo_erectus_new.JPG
wget -O 4.png https://upload.wikimedia.org/wikipedia/commons/1/1f/Homo_heidelbergensis_-_forensic_facial_reconstruction-crop.png
wget -O 5.jpg https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Sabaa_Nissan_Militiaman.jpg/450px-Sabaa_Nissan_Militiaman.jpg
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg
cd ..
# Convert all to PNG for consistency.
# https://unix.stackexchange.com/questions/29869/converting-multiple-image-files-from-jpeg-to-pdf-format
# Hardlink the ones that are already PNG.
mkdir -p png
mogrify -format png -path png orig/*.jpg
ln -P orig/*.png png
Now we have a quick look at all image sizes to decide on the final aspect ratio:
identify png/*
which outputs:
png/1.png PNG 557x495 557x495+0+0 8-bit sRGB 653KB 0.000u 0:00.000
png/2.png PNG 664x800 664x800+0+0 8-bit sRGB 853KB 0.000u 0:00.000
png/3.png PNG 544x680 544x680+0+0 8-bit sRGB 442KB 0.000u 0:00.000
png/4.png PNG 207x238 207x238+0+0 8-bit sRGB 76.8KB 0.000u 0:00.000
png/5.png PNG 450x600 450x600+0+0 8-bit sRGB 627KB 0.000u 0:00.000
so the classic 480p (640x480 == 4/3) aspect ratio seems appropriate.
Do one conversion with minimal resizing to make widths even (TODO
automate for any width, here I just manually looked at identify
output and reduced width and height by one):
mkdir -p raw
convert png/1.png -resize 556x494 raw/1.png
ln -P png/2.png png/3.png png/4.png png/5.png raw
ffmpeg -framerate 1 -pattern_type glob -i 'raw/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p raw.mp4
This produces terrible output, because as seen from:
ffprobe raw.mp4
ffmpeg just takes the size of the first image, 556x494, and then converts all others to that exact size, breaking their aspect ratio.
Now let's convert the images to the target 480p aspect ratio automatically by cropping as per ImageMagick: how to minimally crop an image to a certain aspect ratio?
mkdir -p auto
mogrify -path auto -geometry 640x480^ -gravity center -crop 640x480+0+0 png/*.png
ffmpeg -framerate 1 -pattern_type glob -i 'auto/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p auto.mp4
So now, the aspect ratio is good, but inevitably some cropping had to be done, which kind of cut up interesting parts of the images.
The other option is to pad with black background to have the same aspect ratio as shown at: Resize to fit in a box and set background to black on "empty" part
mkdir -p black
ffmpeg -framerate 1 -pattern_type glob -i 'black/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p black.mp4
Generally speaking though, you will ideally be able to select images with the same or similar aspect ratios to avoid those problems in the first place.
About the CLI options
Note however that despite the name, -glob
this is not as general as shell Glob patters, e.g.: -i '*'
fails: https://trac.ffmpeg.org/ticket/3620 (apparently because filetype is deduced from extension).
-r 30
makes the -framerate 1
video 30 FPS to overcome bugs in players like VLC for low framerates: VLC freezes for low 1 FPS video created from images with ffmpeg Therefore it repeats each frame 30 times to keep the desired 1 image per second effect.
Next steps
You will also want to:
cut up the part of the audio that you want before joining it: Cutting the videos based on start and end time using ffmpeg
ffmpeg -i in.mp3 -ss 03:10 -to 03:30 -c copy out.mp3
TODO: learn to cut and concatenate multiple audio files into the video without intermediate files, I'm pretty sure it's possible:
Tested on
ffmpeg 3.4.4, vlc 3.0.3, Ubuntu 18.04.
Bibliography
1.Close your project:Completely quit Xcode. 2.Go to your project location:there you will find two files in you root folder with varying extensions: Appname.xcodeproj and Appname.xcworkspace
Now open your project by Double clicking on file with the extensions xcworkspace.(***Appname.xcworkspace*)**
Yourproject will open in xcode. Now run your project again.
If you pay close attention when installing your pods,firebase makes it clear to open your project with your-project.xcworkspace after installing pods firebaseIOS Setup
$ cd your-project directory
$ pod init
Add to Podfile
pod 'Firebase/Core'
And finally:
$ pod install
$ open your-project.xcworkspace
Dont forget to add firebase to your AppDelegate
Another variation
.blink {_x000D_
-webkit-animation: blink 1s step-end infinite;_x000D_
animation: blink 1s step-end infinite;_x000D_
}_x000D_
@-webkit-keyframes blink { 50% { visibility: hidden; }}_x000D_
@keyframes blink { 50% { visibility: hidden; }}
_x000D_
This is <span class="blink">blink</span>
_x000D_
Create a css and set the value style="width:50px;"
in css code. Call the class of CSS in the drop down list. Then it will work.
You can try this to avoid indicating custom date and if there is need to display start and end dates of current month:
LocalDate start = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()-1);
LocalDate end = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()).plusMonths(1);
System.out.println("Start of month: " + start);
System.out.println("End of month: " + end);
Result:
> Start of month: 2019-12-01
> End of month: 2019-12-30
There are two Solution of this Problem.
1) Don't write network call in Main UI Thread, Use Async Task for that.
2) Write below code into your MainActivity file after setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And below import statement into your java file.
import android.os.StrictMode;
On groupby
object, the agg
function can take a list to apply several aggregation methods at once. This should give you the result you need:
df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])
On a side note, in PowerShell 3.0 you can use the Get-Content
cmdlet with the new Raw switch:
$text = Get-Content .\file.txt -Raw
If your databaseName
value is correct, then use this: DriverManger.getconnection("jdbc:sqlserver://ServerIp:1433;user=myuser;password=mypassword;databaseName=databaseName;")
Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.
<script>
function radioClick(radio){
alert()
}
</script>
<label>Cash on delivery</label>
<input type="radio" onclick="radioClick('A')" name="payment_method" class="form-group">
<br>
<label>Debit/Credit card, GPay, Paytm etc..</label>
<input type="radio" onclick="radioClick('B')" name="payment_method" class="form-group">
This is the simplest code to draw a rotated and scaled image:
function drawImage(ctx, image, x, y, w, h, degrees){
ctx.save();
ctx.translate(x+w/2, y+h/2);
ctx.rotate(degrees*Math.PI/180.0);
ctx.translate(-x-w/2, -y-h/2);
ctx.drawImage(image, x, y, w, h);
ctx.restore();
}
NSDictionary *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];
[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];
NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);
// now we can save these to a file
NSString *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];
//and restore them
NSMutableDictionary *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];
WARNING: Long script ahead.
A while ago, I faced a similar problem: from a Tcl script, launch a number of processes, then wait for all of them to finish. Here is a demo script I wrote to solve this problem.
#!/usr/bin/env tclsh
# Launches many processes and wait for them to finish.
# This script will works on systems that has the ps command such as
# BSD, Linux, and OS X
package require Tclx; # For process-management utilities
proc updatePidList {stat} {
global pidList
global allFinished
# Parse the process ID of the just-finished process
lassign $stat processId howProcessEnded exitCode
# Remove this process ID from the list of process IDs
set pidList [lindex [intersect3 $pidList $processId] 0]
set processCount [llength $pidList]
# Occasionally, a child process quits but the signal was lost. This
# block of code will go through the list of remaining process IDs
# and remove those that has finished
set updatedPidList {}
foreach pid $pidList {
if {![catch {exec ps $pid} errmsg]} {
lappend updatedPidList $pid
}
}
set pidList $updatedPidList
# Show the remaining processes
if {$processCount > 0} {
puts "Waiting for [llength $pidList] processes"
} else {
set allFinished 1
puts "All finished"
}
}
# A signal handler that gets called when a child process finished.
# This handler needs to exit quickly, so it delegates the real works to
# the proc updatePidList
proc childTerminated {} {
# Restart the handler
signal -restart trap SIGCHLD childTerminated
# Update the list of process IDs
while {![catch {wait -nohang} stat] && $stat ne {}} {
after idle [list updatePidList $stat]
}
}
#
# Main starts here
#
puts "Main begins"
set NUMBER_OF_PROCESSES_TO_LAUNCH 10
set pidList {}
set allFinished 0
# When a child process exits, call proc childTerminated
signal -restart trap SIGCHLD childTerminated
# Spawn many processes
for {set i 0} {$i < $NUMBER_OF_PROCESSES_TO_LAUNCH} {incr i} {
set childId [exec tclsh child.tcl $i &]
puts "child #$i, pid=$childId"
lappend pidList $childId
after 1000
}
# Do some processing
puts "list of processes: $pidList"
puts "Waiting for child processes to finish"
# Do some more processing if required
# After all done, wait for all to finish before exiting
vwait allFinished
puts "Main ends"
#!/usr/bin/env tclsh
# child script: simulate some lengthy operations
proc randomInteger {min max} {
return [expr int(rand() * ($max - $min + 1) * 1000 + $min)]
}
set duration [randomInteger 10 30]
puts " child #$argv runs for $duration miliseconds"
after $duration
puts " child #$argv ends"
Main begins
child #0, pid=64525
child #0 runs for 17466 miliseconds
child #1, pid=64526
child #1 runs for 14181 miliseconds
child #2, pid=64527
child #2 runs for 10856 miliseconds
child #3, pid=64528
child #3 runs for 7464 miliseconds
child #4, pid=64529
child #4 runs for 4034 miliseconds
child #5, pid=64531
child #5 runs for 1068 miliseconds
child #6, pid=64532
child #6 runs for 18571 miliseconds
child #5 ends
child #7, pid=64534
child #7 runs for 15374 miliseconds
child #8, pid=64535
child #8 runs for 11996 miliseconds
child #4 ends
child #9, pid=64536
child #9 runs for 8694 miliseconds
list of processes: 64525 64526 64527 64528 64529 64531 64532 64534 64535 64536
Waiting for child processes to finish
Waiting for 8 processes
Waiting for 8 processes
child #3 ends
Waiting for 7 processes
child #2 ends
Waiting for 6 processes
child #1 ends
Waiting for 5 processes
child #0 ends
Waiting for 4 processes
child #9 ends
Waiting for 3 processes
child #8 ends
Waiting for 2 processes
child #7 ends
Waiting for 1 processes
child #6 ends
All finished
Main ends
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
All of them have there own uses:
If you have an iterable and need to traverse unconditionally to all of them:
for (iterable_type iterable_element : collection)
If you have an iterable but need to conditionally traverse:
for (Iterator iterator = collection.iterator(); iterator.hasNext();)
If data-structure does not implement iterable:
for (int i = 0; i < collection.length; i++)
Oracle doesn't provide such IIF Function. Instead, try using one of the following alternatives:
SELECT DECODE(EMP_ID, 1, 'True', 'False') from Employee
SELECT CASE WHEN EMP_ID = 1 THEN 'True' ELSE 'False' END from Employee
Look at the static System.Drawing.Printing.PrinterSettings.InstalledPrinters property.
It is a list of the names of all installed printers on the system.
update: Copied material that was on the R wiki at http://rwiki.sciviews.org/doku.php?id=tips:graphics-base:2yaxes, link now broken: also available from the wayback machine
(some material originally by Daniel Rajdl 2006/03/31 15:26)
Please note that there are very few situations where it is appropriate to use two different scales on the same plot. It is very easy to mislead the viewer of the graphic. Check the following two examples and comments on this issue (example1, example2 from Junk Charts), as well as this article by Stephen Few (which concludes “I certainly cannot conclude, once and for all, that graphs with dual-scaled axes are never useful; only that I cannot think of a situation that warrants them in light of other, better solutions.”) Also see point #4 in this cartoon ...
If you are determined, the basic recipe is to create your first plot, set par(new=TRUE)
to prevent R from clearing the graphics device, creating the second plot with axes=FALSE
(and setting xlab
and ylab
to be blank – ann=FALSE
should also work) and then using axis(side=4)
to add a new axis on the right-hand side, and mtext(...,side=4)
to add an axis label on the right-hand side. Here is an example using a little bit of made-up data:
set.seed(101)
x <- 1:10
y <- rnorm(10)
## second data set on a very different scale
z <- runif(10, min=1000, max=10000)
par(mar = c(5, 4, 4, 4) + 0.3) # Leave space for z axis
plot(x, y) # first plot
par(new = TRUE)
plot(x, z, type = "l", axes = FALSE, bty = "n", xlab = "", ylab = "")
axis(side=4, at = pretty(range(z)))
mtext("z", side=4, line=3)
twoord.plot()
in the plotrix
package automates this process, as does doubleYScale()
in the latticeExtra
package.
Another example (adapted from an R mailing list post by Robert W. Baer):
## set up some fake test data
time <- seq(0,72,12)
betagal.abs <- c(0.05,0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(0,1000,2000,3000,4000,5000,6000)
## add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 6) + 0.1)
## Plot first set of data and draw its axis
plot(time, betagal.abs, pch=16, axes=FALSE, ylim=c(0,1), xlab="", ylab="",
type="b",col="black", main="Mike's test data")
axis(2, ylim=c(0,1),col="black",las=1) ## las=1 makes horizontal labels
mtext("Beta Gal Absorbance",side=2,line=2.5)
box()
## Allow a second plot on the same graph
par(new=TRUE)
## Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15, xlab="", ylab="", ylim=c(0,7000),
axes=FALSE, type="b", col="red")
## a little farther out (line=4) to make room for labels
mtext("Cell Density",side=4,col="red",line=4)
axis(4, ylim=c(0,7000), col="red",col.axis="red",las=1)
## Draw the time axis
axis(1,pretty(range(time),10))
mtext("Time (Hours)",side=1,col="black",line=2.5)
## Add Legend
legend("topleft",legend=c("Beta Gal","Cell Density"),
text.col=c("black","red"),pch=c(16,15),col=c("black","red"))
Similar recipes can be used to superimpose plots of different types – bar plots, histograms, etc..
Easier update:
Use field.selectionStart
example in this answer.
Thanks to @commonSenseCode for pointing this out.
Old answer:
Found this solution. Not jquery based but there is no problem to integrate it to jquery:
/*
** Returns the caret (cursor) position of the specified text field (oField).
** Return value range is 0-oField.value.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;
// Return results
return iCaretPos;
}
Yes, you can 'refresh' a Google Map like this:
google.maps.event.trigger(map, 'resize');
This basically sends a signal to your map to redraw it.
Hope that helps!
You need to use entryComponents
under @NgModule
.
This is for dynamically added components that are added using ViewContainerRef.createComponent()
. Adding them to entryComponents tells the offline template compiler to compile them and create factories for them.
The components registered in route configurations are added automatically to entryComponents
as well because router-outlet
also uses ViewContainerRef.createComponent()
to add routed components to the DOM.
So your code will be like
@NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent,
HomeComponent,
DialogResultExampleDialog
],
entryComponents: [DialogResultExampleDialog]
I did not like having to add in the 1 second stall to all of the PerformanceCounter
solutions. Instead I chose to use a WMI
solution. The reason the 1 second wait/stall exists is to allow the reading to be accurate when using a PerformanceCounter
. However if you calling this method often and refreshing this information, I'd advise not to constantly have to incur that delay... even if thinking of doing an async process to get it.
I started with the snippet from here Returning CPU usage in WMI using C# and added a full explanation of the solution on my blog post below:
You can use this QString constructor for conversion from QByteArray to QString:
QString(const QByteArray &ba)
QByteArray data;
QString DataAsString = QString(data);
Like the accepted answer well explained by lhunath, you can use
command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)
Beware than if you use bash you could have some issue.
Let me take the matthew-wilcoxson exemple.
And for those who "seeing is believing", a quick test:
(echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
Personally, when I try, I have this result :
user@computer:~$ (echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
user@computer:~$ Test Out
Test Err
Both message does not appear at the same level. Why Test Out
seem to be put like if it is my previous command ?
Prompt is on a blank line, let me think the process is not finished, and when I press Enter
this fix it.
When I check the content of the files, it is ok, redirection works.
Let take another test.
function outerr() {
echo "out" # stdout
echo >&2 "err" # stderr
}
user@computer:~$ outerr
out
err
user@computer:~$ outerr >/dev/null
err
user@computer:~$ outerr 2>/dev/null
out
Trying again the redirection, but with this function.
function test_redirect() {
fout="stdout.log"
ferr="stderr.log"
echo "$ outerr"
(outerr) > >(tee "$fout") 2> >(tee "$ferr" >&2)
echo "# $fout content :"
cat "$fout"
echo "# $ferr content :"
cat "$ferr"
}
Personally, I have this result :
user@computer:~$ test_redirect
$ outerr
# stdout.log content :
out
out
err
# stderr.log content :
err
user@computer:~$
No prompt on a blank line, but I don't see normal output, stdout.log content seem to be wrong, only stderr.log seem to be ok. If I relaunch it, output can be different...
So, why ?
Because, like explained here :
Beware that in bash, this command returns as soon as [first command] finishes, even if the tee commands are still executed (ksh and zsh do wait for the subprocesses)
So, if you use bash, prefer use the better exemple given in this other answer :
{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
It will fix the previous issues.
Now, the question is, how to retrieve exit status code ?
$?
does not works.
I have no found better solution than switch on pipefail with set -o pipefail
(set +o pipefail
to switch off) and use ${PIPESTATUS[0]}
like this
function outerr() {
echo "out"
echo >&2 "err"
return 11
}
function test_outerr() {
local - # To preserve set option
! [[ -o pipefail ]] && set -o pipefail; # Or use second part directly
local fout="stdout.log"
local ferr="stderr.log"
echo "$ outerr"
{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
# First save the status or it will be lost
local status="${PIPESTATUS[0]}" # Save first, the second is 0, perhaps tee status code.
echo "==="
echo "# $fout content :"
echo "<==="
cat "$fout"
echo "===>"
echo "# $ferr content :"
echo "<==="
cat "$ferr"
echo "===>"
if (( status > 0 )); then
echo "Fail $status > 0"
return "$status" # or whatever
fi
}
user@computer:~$ test_outerr
$ outerr
err
out
===
# stdout.log content :
<===
out
===>
# stderr.log content :
<===
err
===>
Fail 11 > 0
as your service is already setup, simply add a broadcast receiver in your service:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
//action for phone state changed
}
}
};
in your service's onCreate
do this:
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more
registerReceiver(receiver, filter);
and in your service's onDestroy
:
unregisterReceiver(receiver);
and you are good to go to receive broadcast for what ever filters you mention in onCreate
. Make sure to add any permission if required. for e.g.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
You can access the iterator methods directly:
std::vector<int> *intVec;
std::vector<int>::iterator it;
for( it = intVec->begin(); it != intVec->end(); ++it )
{
}
If you want the array-access operator, you'd have to de-reference the pointer. For example:
std::vector<int> *intVec;
int val = (*intVec)[0];
No, inside the views folder is not good.
Look: You must have 3 basic folders on your project:
system // This is CI framework there are not much reasons to touch this files
application //this is where your logic goes, the files that makes the application,
public // this must be your documentroot
For security reasons its better to keep your framework and the application outside your documentroot,(public_html, htdocs, public, www... etc)
Inside your public folder, you should put your public info, what the browsers can see, its common to find the folders: images, js, css; so your structure will be:
|- system/
|- application/
|---- models/
|---- views/
|---- controllers/
|- public/
|---- images/
|---- js/
|---- css/
|---- index.php
|---- .htaccess
Simply use this in Objective-C to dismiss keyboard:
[[UIApplication sharedApplication].keyWindow endEditing:YES];
I used the below dependency. If you are using Selenium then it's good to use all of them as below. Else you will see some errors and then do the reserch and add some more dependencies.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>openxml4j</artifactId>
<version>1.0-beta</version>
</dependency>
It is depends on the case and the usage. Generally, in TypeScript there are no default values for interfaces.
If you don't use the default values
You can declare x
as:
let x: IX | undefined; // declaration: x = undefined
Then, in your init function you can set real values:
x = {
a: 'xyz'
b: 123
c: new AnotherType()
};
In this way, x
can be undefined or defined - undefined
represents that the object is uninitialized, without set the default values, if they are unnecessary. This is loggically better than define "garbage".
If you want to partially assign the object:
You can define the type with optional properties like:
interface IX {
a: string,
b?: any,
c?: AnotherType
}
In this case you have to set only a
. The other types are marked with ?
which mean that they are optional and have undefined
as default value.
In any case you can use undefined
as a default value, it is just depends on your use case.
I found better way for this issue, you can use CSS Animation and make your awesome effect for showing items.
.item {
display: none;
}
.item:hover {
display: block;
animation: fade_in_show 0.5s
}
@keyframes fade_in_show {
0% {
opacity: 0;
transform: scale(0)
}
100% {
opacity: 1;
transform: scale(1)
}
}
I'm using this instead of add leading and trailing margin constraints to the layoutMarginsGuide:
UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
yourView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
[safe.trailingAnchor constraintEqualToAnchor:yourView.trailingAnchor],
[yourView.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor],
[yourView.topAnchor constraintEqualToAnchor:safe.topAnchor],
[safe.bottomAnchor constraintEqualToAnchor:yourView.bottomAnchor]
]];
Please also check the option for lower version of ios 11 from Krunal's answer.
The certification installation step whatever mentioned here is correct https://stackoverflow.com/a/35200795/865220
But if you are having a pain of individually having to enable SSL Proxy for each and every new url like me, then to enable for all host names just enter * into the host and port names list in the SSL Proxying Settings like this:
ES-6 way to get title case of a word or entire line.
ex. input = 'hEllo' --> result = 'Hello'
ex. input = 'heLLo woRLd' --> result = 'Hello World'
const getTitleCase = (str) => {
if(str.toLowerCase().indexOf(' ') > 0) {
return str.toLowerCase().split(' ').map((word) => {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
else {
return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
}
}
For this particular case, if using re
module is overkill, how about using split
(or rsplit
) method as
se='</html>'
z.write(article.split(se)[0]+se)
For example,
#!/usr/bin/python
article='''<html>Larala
Ponta Monta
</html>Kurimon
Waff Moff
'''
z=open('out.txt','w')
se='</html>'
z.write(article.split(se)[0]+se)
outputs out.txt
as
<html>Larala
Ponta Monta
</html>
git fetch
git checkout HEAD path/to/your/dir/or/file
Where "path/...
" in (3) starts at the directory just below the repo root containing your ".../file
"
NOTE that instead of "HEAD", the hash code of a specific commit may be used, and then you will get the revision (file) or revisions (dir) specific to that commit.
Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux
instead of Other.
After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.
Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.
Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.
Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.
In VirtualBox screen, go to Devices>USB devices. Select your dongle.
Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.
Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.
Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .
I've just had the same problem after upgrading to mac os Big Sur
Linus solution worked for me
Hit enter as there is no password. Enter the following commands:
mysql> SET PASSWORD for 'root'@'localhost' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'127.0.0.1' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'::1' = password('enteryourpassword');
That’s it, I keep the passwords the same to keep things simple. If you want to check the user’s table to see that the info has been updated just enter the additional commands as shown below. This is a good option to check that you have indeed entered the same password for all hosts.
Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.
https://jsfiddle.net/mvora/mrLmkxmo/
/******** PUT THIS CODE IN ONE JS FILE *******/
var secondFileFuntion = function(){
this.name = 'XYZ';
}
secondFileFuntion.prototype.getSurname = function(){
return 'ABC';
}
var secondFileObject = new secondFileFuntion();
/******** Till Here *******/
/******** PUT THIS CODE IN SECOND JS FILE *******/
function firstFileFunction(){
var name = secondFileObject.name;
var surname = secondFileObject.getSurname()
alert(name);
alert(surname );
}
firstFileFunction();
If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.
Just take care of sequence of including these files in index.html
Try something like this:
$link = @new mysqli($this->host, $this->user, $this->pass)
$statement = $link->prepare($sqlStatement);
if(!$statement)
{
$this->debug_mode('query', 'error', '#Query Failed<br/>' . $link->error);
return false;
}
The below answer is in reference to the latest ng-bootstrap
Install
npm install --save @ng-bootstrap/ng-bootstrap
app.module.ts
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [
...
],
imports: [
...
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Component Controller
import { TemplateRef, ViewChild } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-app-registration',
templateUrl: './app-registration.component.html',
styleUrls: ['./app-registration.component.css']
})
export class AppRegistrationComponent implements OnInit {
@ViewChild('editModal') editModal : TemplateRef<any>; // Note: TemplateRef
constructor(private modalService: NgbModal) { }
openModal(){
this.modalService.open(this.editModal);
}
}
Component HTML
<ng-template #editModal let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Edit Form</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="dateOfBirth">Date of birth</label>
<div class="input-group">
<input id="dateOfBirth" class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #dp="ngbDatepicker">
<div class="input-group-append">
<button class="btn btn-outline-secondary calendar" (click)="dp.toggle()" type="button"></button>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close()">Save</button>
</div>
</ng-template>
If intake_date is some common date format you can use date()
and strtotime()
$mysqlDate = date('Y-m-d H:i:s', strtotime($_POST['intake_date']));
However, this will only work if the date format is accepted by strtotime()
. See it's doc page for supported formats.
This will read a csv file and it includes a csv line splitter that handles double quotes and it can read even if excel has it open.
public List<Dictionary<string, string>> LoadCsvAsDictionary(string path)
{
var result = new List<Dictionary<string, string>>();
var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.IO.StreamReader file = new System.IO.StreamReader(fs);
string line;
int n = 0;
List<string> columns = null;
while ((line = file.ReadLine()) != null)
{
var values = SplitCsv(line);
if (n == 0)
{
columns = values;
}
else
{
var dict = new Dictionary<string, string>();
for (int i = 0; i < columns.Count; i++)
if (i < values.Count)
dict.Add(columns[i], values[i]);
result.Add(dict);
}
n++;
}
file.Close();
return result;
}
private List<string> SplitCsv(string csv)
{
var values = new List<string>();
int last = -1;
bool inQuotes = false;
int n = 0;
while (n < csv.Length)
{
switch (csv[n])
{
case '"':
inQuotes = !inQuotes;
break;
case ',':
if (!inQuotes)
{
values.Add(csv.Substring(last + 1, (n - last)).Trim(' ', ','));
last = n;
}
break;
}
n++;
}
if (last != csv.Length - 1)
values.Add(csv.Substring(last + 1).Trim());
return values;
}
SET @table = 'the_table';
SELECT GROUP_CONCAT(IF(COLUMN_NAME IN ('id'), 0, CONCAT("\`", COLUMN_NAME, "\`"))) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = @table INTO @columns;
SET @s = CONCAT('INSERT INTO ', @table, ' SELECT ', @columns,' FROM ', @table, ' WHERE id=1');
PREPARE stmt FROM @s;
EXECUTE stmt;
In the way that you're doing things, it won't happen. You're changing the background image of the image, which is being blocked by the original image. Changing the height and width also won't happen. To change the src attribute of the image, you would need Javascript or a Javascript Library such as jQuery. You could however, change the image to a simple div (text) box, and have a background image that changes on hover, even though the div box itself will be empty. Here's how.
<div id="emptydiv"></div>
#emptydiv {
background-image: url("LibraryHover.png");
height: 70px;
width: 120px;
}
#emptydiv:hover {
background-image: url("LibraryHoverTrans.png");
height: 700px;
width: 1200px;
}
I hope this is what you're asking for :)
Try this CSS:
body {
margin: 0;
padding: 0;
}
.logo {
float: left;
}
/* ~~ Top Navigation Bar ~~ */
#navigation-container {
width: 1200px;
margin: 0 auto;
height: 70px;
}
.navigation-bar {
background-color: #352d2f;
height: 70px;
width: 100%;
}
#navigation-container img {
float: left;
}
#navigation-container ul {
padding: 0px;
margin: 0px;
text-align: center;
display:inline-block;
}
#navigation-container li {
list-style-type: none;
padding: 0px;
height: 24px;
margin-top: 4px;
margin-bottom: 4px;
display: inline;
}
#navigation-container li a {
color: white;
font-size: 16px;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
text-decoration: none;
line-height: 70px;
padding: 5px 15px;
opacity: 0.7;
}
#menu {
float: right;
}
This is task for which anonymous types are very well suited. You can return objects of a type that is created automatically by the compiler, inferred from usage.
The syntax is of this form:
new { Property1 = value1, Property2 = value2, ... }
For your case, try something like the following:
var listObject = getData();
var catNames = listObject.Select(i =>
new { CatName = i.category_name, Item1 = i.item1, Item2 = i.item2 })
.Distinct().OrderByDescending(s => s).ToArray();
I wanted to answer to the following question which is a little bit different than this:
Best way to print messages on multiple lines
He wanted to show lines from repeated characters too. He wanted this output:
----------------------------------------
# Operator Micro-benchmarks
# Run_mode: short
# Num_repeats: 5
# Num_runs: 1000
----------------------------------------
You can create those lines inside f-strings with a multiplication, like this:
run_mode, num_repeats, num_runs = 'short', 5, 1000
s = f"""
{'-'*40}
# Operator Micro-benchmarks
# Run_mode: {run_mode}
# Num_repeats: {num_repeats}
# Num_runs: {num_runs}
{'-'*40}
"""
print(s)
What variables do you want to print? If you mean QStrings, those need to be converted to c-Strings. Try:
std::cout << myString.toAscii().data();
You can look into the regex module (the fuzzy section). I don't know if you can get the actual differences, but at least you can specify allowed number of different types of changes like insert, delete, and substitutions:
import regex
sequence = 'afrykanerskojezyczny'
queries = [ 'afrykanerskojezycznym', 'afrykanerskojezyczni',
'nieafrykanerskojezyczni' ]
for q in queries:
m = regex.search(r'(%s){e<=2}'%q, sequence)
print 'match' if m else 'nomatch'
Im a bit confused about this part "TO_DATE(TO_CHAR(CURRENT_DATE, 'YYYY-MM-DD'),'YYYY-MM-DD')". What were you trying to do with this clause ? The format that you are displaying in your result is the default format when you run the basic query of getting date from DUAL. Other than that, i did this in your query and it retrieved the previous day 'SELECT (CURRENT_DATE - 1) FROM Dual'. Do let me know if it works out for you and if not then do tell me about the problem. Thanks and all the best.
Another approach is to use the . (dot
) command in combination with I.
vendor_
)I find this technique is often faster than the visual block mode for small numbers of additions and has the added benefit that if you don't need to insert the text on every single line in a range you can easily skip them by pressing extra j's.
Note that for large number of contiguous additions, the block approach or macro will likely be superior.
Convert the batch file to an exe. Try Bat To Exe Converter or Online Bat To Exe Converter, and choose the option to run it as a ghost application, i.e. no window.
ViewGroup class provides API for child views management in run-time, allowing to add/remove views as well.
Some other links on the subject:
Android, add new view without XML Layout
Android Runtime Layout Tutorial
http://developer.android.com/reference/android/view/View.html
http://developer.android.com/reference/android/widget/LinearLayout.html
There is another way to convert Python scripts to .exe files. You can compile Python programs into C++ programs, which can be natively compiled just like any other C++ program.
I too get this error sometimes when I dismiss dialog and finish activity from onPostExecute method. I guess sometimes activity gets finished before dialog successfully dismisses.
Simple, yet effective solution that works for me
@Override
protected void onPostExecute(MyResult result) {
try {
if ((this.mDialog != null) && this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.mDialog = null;
}
}
Firstly said, I try to force all my users to use Chrome when printing because other browsers create different layouts.
An answer from this question recommends:
@page {
size: 210mm 297mm;
/* Chrome sets own margins, we change these printer settings */
margin: 27mm 16mm 27mm 16mm;
}
However, I ended up using this CSS for all my pages to be printed:
@media print
{
@page {
size: A4; /* DIN A4 standard, Europe */
margin:0;
}
html, body {
width: 210mm;
/* height: 297mm; */
height: 282mm;
font-size: 11px;
background: #FFF;
overflow:visible;
}
body {
padding-top:15mm;
}
}
Special case: Long Tables
When I needed to print a table over several pages, the margin:0
with the @page
was leading to bleeding edges:
I could solve this thanks to this answer with:
table { page-break-inside:auto }
tr { page-break-inside:avoid; page-break-after:auto }
thead { display:table-header-group; }
tfoot { display:table-footer-group; }
Plus setting the top-bottom-margins for @page
:
@page {
size: auto;
margin: 20mm 0 10mm 0;
}
body {
margin:0;
padding:0;
}
Result:
I would rather prefer a solution that is concise and works with all browser. For now, I hope the information above can help some developers with similar issues.
Create an environment.plist
file in ~/Library/LaunchAgents/
with this content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>my.startup</string>
<key>ProgramArguments</key>
<array>
<string>sh</string>
<string>-c</string>
<string>
launchctl setenv PRODUCTS_PATH /Users/mortimer/Projects/my_products
launchctl setenv ANDROID_NDK_HOME /Applications/android-ndk
launchctl setenv PATH $PATH:/Applications/gradle/bin
</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
You can add many launchctl
commands inside the <string></string>
block.
The plist
will activate after system reboot. You can also use launchctl load ~/Library/LaunchAgents/environment.plist
to launch it immediately.
[Edit]
The same solution works in El Capitan too.
Xcode 7.0+ doesn't evaluate environment variables by default. The old behaviour can be enabled with this command:
defaults write com.apple.dt.Xcode UseSanitizedBuildSystemEnvironment -bool NO
[Edit]
There a couple of situations where this doesn't quite work. If the computer is restarted and "Reopen windows when logging back in" is selected, the reopened windows may not see the variables (Perhaps they are opened before the agent is run). Also, if you log in via ssh, the variables will not be set (so you'll need to set them in ~/.bash_profile). Finally, this doesn't seem to work for PATH on El Capitan and Sierra. That needs to be set via 'launchctl config user path ...' and in /etc/paths.
In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)
Here are the steps:
Step 1: Create services running in background.
Step 2: You require following permission in Manifest file too:
android.permission.ACCESS_FINE_LOCATION
Step 3: Write code:
final LocationManager manager = (LocationManager)context.getSystemService (Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
Toast.makeText(context, "GPS is disabled!", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "GPS is enabled!", Toast.LENGTH_LONG).show();
Step 4: Or simply you can check using:
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Step 5: Run your services continuously to monitor connection.
I had a same problem when creating a promise object inside my class. By changing target name to "es5" from "es6" solved my issue.
Not a direct answer to your question, though I thing it's worth mentioning it, because your question seems like fitting in the general case of "getting things by name in a key-value storage".
If you are not tight to the way "peoples" is implemented, a more JavaScript-ish way of getting the right guy might be :
var peoples = {
"bob": { "dinner": "pizza" },
"john": { "dinner": "sushi" },
"larry" { "dinner": "hummus" }
};
// If people is implemented this way, then
// you can get values from their name, like :
var theGuy = peoples["john"];
// You can event get directly to the values
var thatGuysPrefferedDinner = peoples["john"].dinner;
Hope if this is not the answer you wanted, it might help people interested in that "key/value" question.
When I got this error, I backed up my entire project folder. Then I did something like
$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master
...depending on your branch name (if it's not master).
Then I did git pull --rebase
. After that, I replaced the pulled files with my backed-up project's files. Now I am ready to commit my changes again and push.
Select * from
(
Select ROW_NUMBER() OVER ( order by Id) as 'Row_Number', *
from tbl_Contact_Us
) as tbl
Where tbl.Row_Number = 5
I know this question is pretty old but if someone like me comes here looking for an answer then this might help. I have been able to overcome the above error with this.
1) Remove the below piece of code from the plugin maven-surefire-plugin
<reuseForks>true</reuseForks>
<argLine>-Xmx2048m</argLine>
2) Add the below goal:
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
I know this is an old thread but it was the first I found when searching. The += solution did not work for me. The code that I did get to work is as below.
#this bit creates the CSV if it does not already exist
$headers = "Name", "Primary Type"
$psObject = New-Object psobject
foreach($header in $headers)
{
Add-Member -InputObject $psobject -MemberType noteproperty -Name $header -Value ""
}
$psObject | Export-Csv $csvfile -NoTypeInformation
#this bit appends a new row to the CSV file
$bName = "My Name"
$bPrimaryType = "My Primary Type"
$hash = @{
"Name" = $bName
"Primary Type" = $bPrimaryType
}
$newRow = New-Object PsObject -Property $hash
Export-Csv $csvfile -inputobject $newrow -append -Force
I was able to use this as a function to loop through a series of arrays and enter the contents into the CSV file.
It works in powershell 3 and above.
You can use "translateX(-100%)" and "text-align: right" if your absolute element is "display: inline-block"
<div class="box">
<div class="absolute-right"></div>
</div>
<style type="text/css">
.box{
text-align: right;
}
.absolute-right{
display: inline-block;
position: absolute;
}
/*The magic:*/
.absolute-right{
-moz-transform: translateX(-100%);
-ms-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
-o-transform: translateX(-100%);
transform: translateX(-100%);
}
</style>
You will get absolute-element aligned to the right relative its parent
Since not all of my clients use authenticated SMTP accounts, I resorted to using the SMTP account only if app key values are supplied in web.config file.
Here is the VB code:
sSMTPUser = ConfigurationManager.AppSettings("SMTPUser")
sSMTPPassword = ConfigurationManager.AppSettings("SMTPPassword")
If sSMTPUser.Trim.Length > 0 AndAlso sSMTPPassword.Trim.Length > 0 Then
NetClient.Credentials = New System.Net.NetworkCredential(sSMTPUser, sSMTPPassword)
sUsingCredentialMesg = "(Using Authenticated Account) " 'used for logging purposes
End If
NetClient.Send(Message)
lambda
is an anonymous function, not an arbitrary function. The parameter being accepted would be the variable you're working with, and the column in which you're sorting it on.
In General a function to return string after substring is
function getStringAfterSubstring(parentString, substring) {_x000D_
return parentString.substring(parentString.indexOf(substring) + substring.length)_x000D_
}_x000D_
_x000D_
function getStringBeforeSubstring(parentString, substring) {_x000D_
return parentString.substring(0, parentString.indexOf(substring))_x000D_
}_x000D_
console.log(getStringAfterSubstring('abcxyz123uvw', '123'))_x000D_
console.log(getStringBeforeSubstring('abcxyz123uvw', '123'))
_x000D_
Try to minimize the use of <br>
as much as you possibly can. HTML is supposed to carry content and structure, <br>
is neither. A simple workaround is to wrap your input elements in <p>
elements, like so:
<form name="publish" id="publish" action="publishprocess.php" method="post">
<p><input type="text" id="title" name="title" size="60" maxlength="110" value="<?php echo $title ?>" /> - Title</p>
<p><input type="text" id="contact" name="contact" size="24" maxlength="30" value="<?php echo $contact ?>" /> - Contact</p>
<p>Task description (you may include task description, requirements on bidders, time requirements, etc):</p>
<p><textarea name="detail" id="detail" rows="7" cols="60" style="font-family:Arial, Helvetica, sans-serif"><?php echo $detail ?></textarea></p>
<p><input type="text" id="price" name="price" size="10" maxlength="20" value="<?php echo $price ?>" /> - Price</p>
<p><input class="tagvalidate" type="text" id="tag" name="tag" size="40" maxlength="60" value="<?php echo $tag ?>" /> - Skill or Knowledge Tags</p>
<p>Combine multiple words into single-words, space to separate up to 3 tags (example:photoshop quantum-physics computer-programming)</p>
<p>District Restriction:<?php echo $locationtext.$cityname; ?></p>
<p><input type="submit" id="submit" value="Submit" /></p>
</form>
When using NOT IN you should ensure that none of the values are NULL:
SELECT mac, creation_date
FROM logs
WHERE logs_type_id=11
AND mac NOT IN (
SELECT mac
FROM consols
WHERE mac IS NOT NULL -- add this
)
I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.
https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable
Because all attempts to print the argument I placed in my variable failed, here my 2 bytes for this question:
std::string dump_name;
(stuff..)
if(argc>2)
{
dump_name.assign(argv[2]);
fprintf(stdout, "ARGUMENT %s", dump_name.c_str());
}
Note the use of assign, and also the need for the c_str() function call.
Get ahold of BeanUtils from Spring http://static.springsource.org/spring/docs/3.0.x/javadoc-api/
Probably the Apache variation (commons beans) has similar functionality.
You can use a very nice tool called Stetho
by adding this to build.gradle
file:
compile 'com.facebook.stetho:stetho:1.4.1'
And initialized it inside your Application
or Activity
onCreate()
method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Stetho.initializeWithDefaults(this);
setContentView(R.layout.activity_main);
}
Then you can view the db records in chrome in the address:
chrome://inspect/#devices
For more details you can read my post: How to view easily your db records
You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" />
control doesn't handle that.
If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change
event then strip the filename portion and save the path somewhere--but that's about as good as it gets.
Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.
var count = $('.' + myclassname).length;
To answer the question first we need to take a look at the purpose of a dictionary and underlying technology.
Dictionary
is the list of KeyValuePair<Tkey, Tvalue>
where each value is represented by its unique key. Let's say we have a list of your favorite foods. Each value (food name) is represented by its unique key (a position = how much you like this food).
Example code:
Dictionary<int, string> myDietFavorites = new Dictionary<int, string>()
{
{ 1, "Burger"},
{ 2, "Fries"},
{ 3, "Donuts"}
};
Let's say you want to stay healthy, you've changed your mind and you want to replace your favorite "Burger" with salad. Your list is still a list of your favorites, you won't change the nature of the list. Your favorite will remain number one on the list, only it's value will change. This is when you call this:
/*your key stays 1, you only replace the value assigned to this key
you alter existing record in your dictionary*/
myDietFavorites[1] = "Salad";
But don't forget you're the programmer, and from now on you finishes your sentences with ; you refuse to use emojis because they would throw compilation error and all list of favorites is 0 index based.
Your diet changed too! So you alter your list again:
/*you don't want to replace Salad, you want to add this new fancy 0
position to your list. It wasn't there before so you can either define it*/
myDietFavorites[0] = "Pizza";
/*or Add it*/
myDietFavorites.Add(0, "Pizza");
There are two possibilities with defining, you either want to give a new definition for something not existent before or you want to change definition which already exists.
Add method allows you to add a record but only under one condition: key for this definition may not exist in your dictionary.
Now we are going to look under the hood. When you are making a dictionary your compiler make a reservation for the bucket (spaces in memory to store your records). Bucket don't store keys in the way you define them. Each key is hashed before going to the bucket (defined by Microsoft), worth mention that value part stays unchanged.
I'll use the CRC32 hashing algorithm to simplify my example. When you defining:
myDietFavorites[0] = "Pizza";
What is going to the bucket is db2dc565 "Pizza" (simplified).
When you alter the value in with:
myDietFavorites[0] = "Spaghetti";
You hash your 0 which is again db2dc565 then you look up this value in your bucket to find if it's there. If it's there you simply rewrite the value assigned to the key. If it's not there you'll place your value in the bucket.
When you calling Add function on your dictionary like:
myDietFavorite.Add(0, "Chocolate");
You hash your 0 to compare it's value to ones in the bucket. You may place it in the bucket only if it's not there.
It's crucial to know how it works especially if you work with dictionaries of string or char type of key. It's case sensitive because of undergoing hashing. So for example "name" != "Name". Let's use our CRC32 to depict this.
Value for "name" is: e04112b1 Value for "Name" is: 1107fb5b
I find it best to just put the default value in the constructor method of the model.
Gender = "Male";
Here is what I do in an activity for buffered reading extend/modify to match your needs
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
EDIT : My answer is perhaps useless if your question is on how to do it outside of an activity. If your question is simply how to read a file from asset then the answer is above.
UPDATE :
To open a file specifying the type simply add the type in the InputStreamReader call as follow.
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
EDIT
As @Stan says in the comment, the code I am giving is not summing up lines. mLine
is replaced every pass. That's why I wrote //process line
. I assume the file contains some sort of data (i.e a contact list) and each line should be processed separately.
In case you simply want to load the file without any kind of processing you will have to sum up mLine
at each pass using StringBuilder()
and appending each pass.
ANOTHER EDIT
According to the comment of @Vincent I added the finally
block.
Also note that in Java 7 and upper you can use try-with-resources
to use the AutoCloseable
and Closeable
features of recent Java.
CONTEXT
In a comment @LunarWatcher points out that getAssets()
is a class
in context
. So, if you call it outside of an activity
you need to refer to it and pass the context instance to the activity.
ContextInstance.getAssets();
This is explained in the answer of @Maneesh. So if this is useful to you upvote his answer because that's him who pointed that out.
public void Linq95()
{
List<Customer> customers = GetCustomerList();
List<Product> products = GetProductList();
var customerNames =
from c in customers
select c.CompanyName;
var productNames =
from p in products
select p.ProductName;
var allNames = customerNames.Concat(productNames);
Console.WriteLine("Customer and product names:");
foreach (var n in allNames)
{
Console.WriteLine(n);
}
}
You can have multiple CSS declarations for the same properties by separating them with commas:
.abc, .xyz {
margin-left: 20px;
}
You can use "ImageBackground" component on React Native.
<ImageBackground
source={yourSourceFile}
style={{width: '100%', height: '100%'}}
>
<....yourContent...>
</ImageBackground>
Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.
import cv2
img = cv2.imread('1.jpg', 1)
path = '/tmp'
cv2.imwrite(str(path) + 'waka.jpg',img)
cv2.waitKey(0)
I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.
Example:
import os
final_path = os.path.join(path_1,path_2,path_3......)
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
cv2.waitKey(0)
that code works fine on both Windows and Ubuntu :)
For windows 8.1 & python 2.7 , I fixed the problem by following below steps
1 . Download and install graphviz-2.38.msi https://graphviz.gitlab.io/_pages/Download/Download_windows.html
2 . Set the path variable
Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit add 'C:\Program Files (x86)\Graphviz2.38\bin'
position:fixed
implies that, well, the modal window will remain fixed relative to the viewpoint. I agree with your assessment that it's appropriate in this scenario, with that in mind why don'y you add a scrollbar to the modal window itself?
If so, correct max-height
and overflow
properties should do the trick.
I am using microsoft's Android emulator with Android Studio. I have an AMD FX8350. The ARM one in android studio is terribly slow.
The only issue is that it requires Hyper-V which is not available on windows 10 Home.
Its a really quick emulator and it is free. The best emulator I have used.
For upgrade code retrieval: How can I find the Upgrade Code for an installed MSI file?
The information below has grown considerably over time and may have become a little too elaborate. How to get product codes quickly? (four approaches):
Use the Powershell "one-liner"
Scroll down for screenshot and step-by-step. Disclaimer also below - minor or moderate risks depending on who you ask. Works OK for me. Any self-repair triggered by this option should generally be possible to cancel. The package integrity checks triggered does add some event log "noise" though. Note! IdentifyingNumber
is the ProductCode
(WMI peculiarity).
get-wmiobject Win32_Product | Sort-Object -Property Name |Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize
Quick start of Powershell: hold Windows key, tap R, type in "powershell" and press Enter
Use VBScript
(script on github.com)Described below under "Alternative Tools" (section 3). This option may be safer than Powershell for reasons explained in detail below. In essence it is (much) faster and not capable of triggering MSI self-repair since it does not go through WMI (it accesses the MSI COM API directly - at blistering speed). However, it is more involved than the Powershell option (several lines of code).
Registry Lookup
Some swear by looking things up in the registry. Not my recommended approach - I like going through proper APIs (or in other words: OS function calls). There are always weird exceptions accounted for only by the internals of the API-implementation:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall
Original MSI File / WiX Source
You can find the Product Code
in the Property table
of any MSI file (and any other property as well). However, the GUID could conceivably (rarely) be overridden by a transform applied at install time and hence not match the GUID the product is registered under (approach 1 and 2 above will report the real product code - that is registered with Windows - in such rare scenarios).
You need a tool to view MSI files. See towards the bottom of the following answer for a list of free tools you can download (or see quick option below): How can I compare the content of two (or more) MSI files?
UPDATE: For convenience and need for speed :-), download SuperOrca without delay and fuss from this direct-download hotlink - the tool is good enough to get the job done - install, open MSI and go straight to the Property table and find the ProductCode
row (please always virus check a direct-download hotlink - obviously - you can use virustotal.com to do so - online scan utilizing dozens of anti-virus and malware suites to scan what you upload).
Orca is Microsoft's own tool, it is installed with Visual Studio and the Windows SDK. Try searching for
Orca-x86_en-us.msi
- underProgram Files (x86)
and install the MSI if found.
- Current path:
C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x86
- Change version numbers as appropriate
And below you will find the original answer which "organically grew" into a lot of detail.
Maybe see "Uninstall MSI Packages" section below if this is the task you need to perform.
UPDATE: If you also need the upgrade code, check this answer: How can I find the Upgrade Code for an installed MSI file? (retrieves associated product codes, upgrade codes & product names in a table output - similar to the one below).
- Can't use PowerShell? See "Alternative Tools" section below.
- Looking to uninstall? See "Uninstall MSI packages" section below.
Fire up Powershell (hold down the Windows key, tap R, release the Windows key, type in "powershell" and press OK) and run the command below to get a list of installed MSI package product codes along with the local cache package path and the product name (maximize the PowerShell window to avoid truncated names).
Before running this command line, please read the disclaimer below (nothing dangerous, just some potential nuisances). Section 3 under "Alternative Tools" shows an alternative non-WMI way to get the same information using VBScript. If you are trying to uninstall a package there is a section below with some sample msiexec.exe command lines:
get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize
The output should be similar to this:
Note! For some strange reason the "ProductCode" is referred to as "IdentifyingNumber" in WMI. So in other words - in the picture above the IdentifyingNumber is the ProductCode.
If you need to run this query remotely against lots of remote computer, see "Retrieve Product Codes From A Remote Computer" section below.
DISCLAIMER (important, please read before running the command!): Due to strange Microsoft design, any WMI call to
Win32_Product
(like the PowerShell command below) will trigger a validation of the package estate. Besides being quite slow, this can in rare cases trigger an MSI self-repair. This can be a small package or something huge - like Visual Studio. In most cases this does not happen - but there is a risk. Don't run this command right before an important meeting - it is not ever dangerous (it is read-only), but it might lead to a long repair in very rare cases (I think you can cancel the self-repair as well - unless actively prevented by the package in question, but it will restart if you call Win32_Product again and this will persist until you let the self-repair finish - sometimes it might continue even if you do let it finish: How can I determine what causes repeated Windows Installer self-repair?).And just for the record: some people report their event logs filling up with MsiInstaller EventID 1035 entries (see code chief's answer) - apparently caused by WMI queries to the Win32_Product class (personally I have never seen this). This is not directly related to the Powershell command suggested above, it is in context of general use of the WIM class Win32_Product.
You can also get the output in list form (instead of table):
get-wmiobject -class Win32_Product
In this case the output is similar to this:
In theory you should just be able to specify a remote computer name as part of the command itself. Here is the same command as above set up to run on the machine "RemoteMachine" (-ComputerName RemoteMachine
section added):
get-wmiobject Win32_Product -ComputerName RemoteMachine | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize
This might work if you are running with domain admin rights on a proper domain. In a workgroup environment (small office / home network), you probably have to add user credentials directly to the WMI calls to make it work.
Additionally, remote connections in WMI are affected by (at least) the Windows Firewall, DCOM settings, and User Account Control (UAC) (plus any additional non-Microsoft factors - for instance real firewalls, third party software firewalls, security software of various kinds, etc...). Whether it will work or not depends on your exact setup.
UPDATE: An extensive section on remote WMI running can be found in this answer: How can I find the Upgrade Code for an installed MSI file?. It appears a firewall rule and suppression of the UAC prompt via a registry tweak can make things work in a workgroup network environment. Not recommended changes security-wise, but it worked for me.
PowerShell requires the .NET framework to be installed (currently in version 3.5.1 it seems? October, 2017). The actual PowerShell application itself can also be missing from the machine even if .NET is installed. Finally I believe PowerShell can be disabled or locked by various system policies and privileges.
If this is the case, you can try a few other ways to retrieve product codes. My preferred alternative is VBScript - it is fast and flexible (but can also be locked on certain machines, and scripting is always a little more involved than using tools).
wbemtest.exe
.wbemtest.exe
(Hold down the Windows key, tap R, release the Windows key, type in "wbemtest.exe" and press OK).SELECT IdentifyingNumber,Name,Version FROM Win32_Product
and click "Use" (or equivalent - the tool will be localized).WMIExplorer.exe
SELECT IdentifyingNumber,Name,Version FROM Win32_Product
and press Execute.msiinfo.csv
.' Retrieve all ProductCodes (with ProductName and ProductVersion)
Set fso = CreateObject("Scripting.FileSystemObject")
Set output = fso.CreateTextFile("msiinfo.csv", True, True)
Set installer = CreateObject("WindowsInstaller.Installer")
On Error Resume Next ' we ignore all errors
For Each product In installer.ProductsEx("", "", 7)
productcode = product.ProductCode
name = product.InstallProperty("ProductName")
version=product.InstallProperty("VersionString")
output.writeline (productcode & ", " & name & ", " & version)
Next
output.Close
I can't think of any further general purpose options to retrieve product codes at the moment, please add if you know of any. Just edit inline rather than adding too many comments please.
You can certainly access this information from within your application by calling the MSI automation interface (COM based) OR the C++ MSI installer functions (Win32 API). Or even use WMI queries from within your application like you do in the samples above using
PowerShell
,wbemtest.exe
orWMIExplorer.exe
.
If what you want to do is to uninstall the MSI package you found the product code for, you can do this as follows using an elevated command prompt (search for cmd.exe, right click and run as admin):
Option 1: Basic, interactive uninstall without logging (quick and easy):
msiexec.exe /x {00000000-0000-0000-0000-00000000000C}
Quick Parameter Explanation:
/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall
You can also enable (verbose) logging and run in silent mode if you want to, leading us to option 2:
Option 2: Silent uninstall with verbose logging (better for batch files):
msiexec.exe /x {00000000-0000-0000-0000-00000000000C} /QN /L*V "C:\My.log" REBOOT=ReallySuppress
Quick Parameter Explanation:
/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall
/QN = run completely silently
/L*V "C:\My.log"= verbose logging at specified path
REBOOT=ReallySuppress = avoid unexpected, sudden reboot
There is a comprehensive reference for MSI uninstall here (various different ways to uninstall MSI packages): Uninstalling an MSI file from the command line without using msiexec. There is a plethora of different ways to uninstall.
If you are writing a batch file, please have a look at section 3 in the above, linked answer for a few common and standard uninstall command line variants.
And a quick link to msiexec.exe (command line options) (overview of the command line for msiexec.exe from MSDN). And the Technet version as well.
UPDATE: please find a new answer on how to find the upgrade code for installed packages instead of manually looking up the code in MSI files. For installed packages this is much more reliable. If the package is not installed, you still need to look in the MSI file (or the source file used to compile the MSI) to find the upgrade code. Leaving in older section below:
If you want to get the UpgradeCode or other MSI properties, you can open the cached installation MSI for the product from the location specified by "LocalPackage" in the image show above (something like: C:\WINDOWS\Installer\50c080ae.msi
- it is a hex file name, unique on each system). Then you look in the "Property table" for UpgradeCode (it is possible for the UpgradeCode to be redefined in a transform - to be sure you get the right value you need to retrieve the code programatically from the system - I will provide a script for this shortly. However, the UpgradeCode found in the cached MSI is generally correct).
To open the cached MSI files, use Orca or another packaging tool. Here is a discussion of different tools (any of them will do): What installation product to use? InstallShield, WiX, Wise, Advanced Installer, etc. If you don't have such a tool installed, your fastest bet might be to try Super Orca (it is simple to use, but not extensively tested by me).
UPDATE: here is a new answer with information on various free products you can use to view MSI files: How can I compare the content of two (or more) MSI files?
If you have Visual Studio installed, try searching for Orca-x86_en-us.msi
- under Program Files (x86)
- and install it (this is Microsoft's own, official MSI viewer and editor). Then find Orca in the start menu. Go time in no time :-). Technically Orca is installed as part of Windows SDK (not Visual Studio), but Windows SDK is bundled with the Visual Studio install. If you don't have Visual Studio installed, perhaps you know someone who does? Just have them search for this MSI and send you (it is a tiny half mb file) - should take them seconds. UPDATE: you need several CAB files as well as the MSI - these are found in the same folder where the MSI is found. If not, you can always download the Windows SDK (it is free, but it is big - and everything you install will slow down your PC). I am not sure which part of the SDK installs the Orca MSI. If you do, please just edit and add details here.
Similar topics (for reference and easy access - I should clean this list up):
For IE8 & IE9 you need to use XDomainRequest (XDR). If you look below you'll see it's in a sort of similar formatting as $.ajax. As far as my research has got me I can't get this cross-domain working in IE6 & 7 (still looking for a work-around for this). XDR first came out in IE8 (it's in IE9 also). So basically first, I test for 6/7 and do no AJAX.
IE10+ is able to do cross-domain normally like all the other browsers (congrats Microsoft... sigh)
After that the else if tests for 'XDomainRequest in window (apparently better than browser sniffing) and does the JSON AJAX request that way, other wise the ELSE does it normally with $.ajax.
Hope this helps!! Took me forever to get this all figured out originally
Information on the XDomainRequest object
// call with your url (with parameters)
// 2nd param is your callback function (which will be passed the json DATA back)
crossDomainAjax('http://www.somecrossdomaincall.com/?blah=123', function (data) {
// success logic
});
function crossDomainAjax (url, successCallback) {
// IE8 & 9 only Cross domain JSON GET request
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var xdr = new XDomainRequest(); // Use Microsoft XDR
xdr.open('get', url);
xdr.onload = function () {
var dom = new ActiveXObject('Microsoft.XMLDOM'),
JSON = $.parseJSON(xdr.responseText);
dom.async = false;
if (JSON == null || typeof (JSON) == 'undefined') {
JSON = $.parseJSON(data.firstChild.textContent);
}
successCallback(JSON); // internal function
};
xdr.onerror = function() {
_result = false;
};
xdr.send();
}
// IE7 and lower can't do cross domain
else if (navigator.userAgent.indexOf('MSIE') != -1 &&
parseInt(navigator.userAgent.match(/MSIE ([\d.]+)/)[1], 10) < 8) {
return false;
}
// Do normal jQuery AJAX for everything else
else {
$.ajax({
url: url,
cache: false,
dataType: 'json',
type: 'GET',
async: false, // must be set to false
success: function (data, success) {
successCallback(data);
}
});
}
}
Pure js solution for newcomers or anyone else.
var scrollAmount = 150;
var element = document.getElementById("elem");
element.addEventListener("click", scrollPage);
function scrollPage() {
var currentPositionOfPage = window.scrollY;
window.scrollTo(0, currentPositionOfPage + scrollAmount);
}
If you include the following code at the top of your script, matplotlib
will run inline when in an IPython
environment (like jupyter, hydrogen atom plugin...), and it will still work if you launch the script directly via command line (matplotlib
won't run inline, and the charts will open in a pop-ups as usual).
from IPython import get_ipython
ipy = get_ipython()
if ipy is not None:
ipy.run_line_magic('matplotlib', 'inline')
Well, there are different implementations for different browsers.
In my mind, the simplest and most elegant solution is using CSS calc(). Unfortunately, this method is unavailable in ie8 and less, and also not available in android browsers and mobile opera. If you're using separate methods for that, however, you can try this: http://jsfiddle.net/uRskD/
The markup:
<div id="header"></div>
<div id="body"></div>
<div id="footer"></div>
And the CSS:
html, body {
height: 100%;
margin: 0;
}
#header {
background: #f0f;
height: 20px;
}
#footer {
background: #f0f;
height: 20px;
}
#body {
background: #0f0;
min-height: calc(100% - 40px);
}
My secondary solution involves the sticky footer method and box-sizing. This basically allows for the body element to fill 100% height of its parent, and includes the padding in that 100% with box-sizing: border-box;
. http://jsfiddle.net/uRskD/1/
html, body {
height: 100%;
margin: 0;
}
#header {
background: #f0f;
height: 20px;
position: absolute;
top: 0;
left: 0;
right: 0;
}
#footer {
background: #f0f;
height: 20px;
position: absolute;
bottom: 0;
left: 0;
right: 0;
}
#body {
background: #0f0;
min-height: 100%;
box-sizing: border-box;
padding-top: 20px;
padding-bottom: 20px;
}
My third method would be to use jQuery to set the min-height of the main content area. http://jsfiddle.net/uRskD/2/
html, body {
height: 100%;
margin: 0;
}
#header {
background: #f0f;
height: 20px;
}
#footer {
background: #f0f;
height: 20px;
}
#body {
background: #0f0;
}
And the JS:
$(function() {
headerHeight = $('#header').height();
footerHeight = $('#footer').height();
windowHeight = $(window).height();
$('#body').css('min-height', windowHeight - headerHeight - footerHeight);
});
A particularly interesting case is when you compare
java.util.Arrays$ArrayList<[[name,value,type], [name1,value1,type1]]>
and
java.util.Collections$UnmodifiableCollection<[[name,value,type], [name1,value1,type1]]>
So far, the only solution I see is to change both of them into sets
assertEquals(new HashSet<CustomAttribute>(customAttributes), new HashSet<CustomAttribute>(result.getCustomAttributes()));
Or I could compare them element by element.
Here's the complete clean and optimised code in JAVA 8
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/*Take input from user*/
Scanner sc = new Scanner(System.in);
int n =0;
n = sc.nextInt();
int arr[] = new int[n];
//////////////mean code starts here//////////////////
int sum = 0;
for(int i=0;i<n; i++)
{
arr[i] = sc.nextInt();
sum += arr[i];
}
System.out.println((double)sum/n);
//////////////mean code ends here//////////////////
//////////////median code starts here//////////////////
Arrays.sort(arr);
int val = arr.length/2;
System.out.println((arr[val]+arr[val-1])/2.0);
//////////////median code ends here//////////////////
//////////////mode code starts here//////////////////
int maxValue=0;
int maxCount=0;
for(int i=0; i<n; ++i)
{
int count=0;
for(int j=0; j<n; ++j)
{
if(arr[j] == arr[i])
{
++count;
}
if(count > maxCount)
{
maxCount = count;
maxValue = arr[i];
}
}
}
System.out.println(maxValue);
//////////////mode code ends here//////////////////
}
}
Check out this page which has an example of how to do it.
In Java 9, you can now use Matcher#results()
to get a Stream<MatchResult>
which you can use to get a list/array of matches.
import java.util.regex.Pattern;
import java.util.regex.MatchResult;
String[] matches = Pattern.compile("your regex here")
.matcher("string to search from here")
.results()
.map(MatchResult::group)
.toArray(String[]::new);
// or .collect(Collectors.toList())
Use this, 100% guaranteed:-
vr {
margin-left: 20px;
margin-right: 20px;
height: 50px;
border: 0;
border-left: 1px solid #cccccc;
display: inline-block;
vertical-align: bottom;
}
You probably want the next transformation for you pixels:
pixels = map(list, image.getdata())
You can either
fig, ax = plt.subplots() #create figure and axes
candlestick(ax, quotes, ...)
or
candlestick(plt.gca(), quotes) #get the axis when calling the function
The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot
The accepted answer works if you set the JSON as a key/value pair in the form-data
panel (See the image hereunder)
Nevertheless, I am wondering if it is a very clean way to design an API. If it is mandatory for you to upload both image and JSON in a single call maybe it is ok but if you could separate the routes (one for image uploading, the other for JSON body with a proper content-type header), it seems better.
You might need to grep Foobar directory like:
find . -name "file.ext"| grep "FooBar" | xargs -i cp -p "{}" .
In Very simple words,
Blank is different than null.
null is purely database-related, whereas blank is validation-related(required in form).
If null=True
, Django will store empty values as NULL in the database
. If a field has blank=True
, form validation will allow entry of an empty value
. If a field has blank=False, the field will be required.
number_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
number_string = number_string.split(',')
number_string = [int(i) for i in number_string]
Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.
Writing that much data to a file is going to take a while.
You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).
You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?
You should also write a function to do the calculation; you could use an inline
function in C99 or later (or C++). The repetition in the code is excruciating to behold.
You should also use C99 notation for main()
, with the explicit return type (and preferably void
for the argument list when you are not using argc
or argv
):
int main(void)
Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 };
(thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static
in front of the functions, and the main array; file
becomes a local to main
; error check the fopen()
, etc.).
I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.
#include <stdio.h>
#define lambda 2.0
#define g 1.0
#define F0 1.0
#define h 0.1
#define e 0.00001
enum { ROWS = 1000, COLS = 10000 };
static double F[ROWS][COLS];
static void Inicio(double D[ROWS][COLS])
{
for (int i = 399; i < 600; i++) // Magic numbers!!
D[i][0] = F0;
}
enum { R = ROWS - 1 };
static inline int ko(int k, int n)
{
int rv = k + n;
if (rv >= R)
rv -= R;
else if (rv < 0)
rv += R;
return(rv);
}
static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
int ks2 = ko(k, -2);
int ks1 = ko(k, -1);
int kp1 = ko(k, +1);
int kp2 = ko(k, +2);
A[k][i] = A[k][i-1]
+ e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
+ 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
+ e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}
static void Iteration(double A[ROWS][COLS])
{
for (int i = 1; i < COLS; i++)
{
for (int k = 0; k < R; k++)
calculate_value(i, k, A);
A[999][i] = A[0][i];
}
}
int main(void)
{
FILE *file = fopen("P2.txt","wt");
if (file == 0)
return(1);
Inicio(F);
Iteration(F);
for (int i = 0; i < COLS; i++)
{
for (int j = 0; j < ROWS; j++)
{
fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
}
}
fclose(file);
return(0);
}
This program writes to P2.txt
instead of P1.txt
. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:
Original Modified
6.334s 6.367s
6.241s 6.231s
6.315s 10.778s
6.378s 6.320s
6.388s 6.293s
6.285s 6.268s
6.387s 10.954s
6.377s 6.227s
8.888s 6.347s
6.304s 6.286s
6.258s 10.302s
6.975s 6.260s
6.663s 6.847s
6.359s 6.313s
6.344s 6.335s
7.762s 6.533s
6.310s 9.418s
8.972s 6.370s
6.383s 6.357s
However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for
loop became:
for (int i = COLS - 1; i < COLS; i++)
the timings were vastly reduced and very much more consistent:
Original Modified
0.168s 0.165s
0.145s 0.165s
0.165s 0.166s
0.164s 0.163s
0.151s 0.151s
0.148s 0.153s
0.152s 0.171s
0.165s 0.165s
0.173s 0.176s
0.171s 0.165s
0.151s 0.169s
The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.
Try this it works
<ul class="sub-menu" type="none">
<li class="sub-menu-list" ng-repeat="menu in list.components">
<a class="sub-menu-link">
{{ menu.component }}
</a>
</li>
</ul>
Try this command:
@echo off
cls
:loop
echo RAINBOW
color 0
echo RAINBOW
color 1
echo RAINBOW
color 2
echo RAINBOW
color 3
echo RAINBOW
color 4
echo RAINBOW
color 5
echo RAINBOW
color 6
echo RAINBOW
color 8
echo RAINBOW
color 9
echo RAINBOW
color A
echo RAINBOW
color B
echo RAINBOW
color C
echo RAINBOW
color D
echo RAINBOW
color E
echo RAINBOW
goto loop
This should create color changing text go in a loop.
Edit: You can change the words rainbow to whatever you want.
export default
is used to create local registration for Vue component.
Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e
Regex is unnecessary for this. Just use some_string.split(' ', 1)[0]
or some_string.partition(' ')[0]
.
Fully fleshed out example with arrows for only the red edges:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.25) for node in G.nodes()]
# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]
# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'),
node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()
No, there is no way to specify defaults. I believer this is done on purpose to enhance readability, at the cost of a little more time (and, hopefully, thought) on the writer's end.
I think the proper approach to having a "default" is to have a new function which supplies that default to the more generic function. Having this, your code becomes clearer on your intent. For example:
func SaySomething(say string) {
// All the complicated bits involved in saying something
}
func SayHello() {
SaySomething("Hello")
}
With very little effort, I made a function that does a common thing and reused the generic function. You can see this in many libraries, fmt.Println
for example just adds a newline to what fmt.Print
would otherwise do. When reading someone's code, however, it is clear what they intend to do by the function they call. With default values, I won't know what is supposed to be happening without also going to the function to reference what the default value actually is.
You can try these. 1. stringify your JSON Object before calling the server action via ajax 2. deserialize the string in the action then use the data as a dictionary.
Javascript sample below (sending the JSON Object
$.ajax(
{
type: 'POST',
url: 'TheAction',
data: { 'data': JSON.stringify(theJSONObject)
}
})
Action (C#) sample below
[HttpPost]
public JsonResult TheAction(string data) {
string _jsonObject = data.Replace(@"\", string.Empty);
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, string> jsonObject = serializer.Deserialize<Dictionary<string, string>>(_jsonObject);
return Json(new object{status = true});
}
I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:
Try using BigInteger class, it works.
int Val=-32768;
String Hex=Integer.toHexString(Val);
//int FirstAttempt=Integer.parseInt(Hex,16); // Error "Invalid Int"
//int SecondAttempt=Integer.decode("0x"+Hex); // Error "Invalid Int"
BigInteger i = new BigInteger(Hex,16);
System.out.println(i.intValue());
Assuming:
(unsigned long)
you mean unsigned 32-bit integer,then you just need to add 2**32 (or 1 << 32)
to the negative value.
For example, apply this to -1:
>>> -1
-1
>>> _ + 2**32
4294967295L
>>> bin(_)
'0b11111111111111111111111111111111'
Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.
Nobody but you can say what your hidden assumptions are, though. If, for example, you have 1's-complement representations in mind, then you need to apply the ~
prefix operator instead. Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").
And to duplicate what the platform C compiler does, you can use the ctypes
module:
>>> import ctypes
>>> ctypes.c_ulong(-1) # stuff Python's -1 into a C unsigned long
c_ulong(4294967295L)
>>> _.value
4294967295L
C's unsigned long
happens to be 4 bytes on the box that ran this sample.
If you are inserting into a single table, you can write your query like this (maybe only in MySQL):
INSERT INTO table1 (First, Last)
VALUES
('Fred', 'Smith'),
('John', 'Smith'),
('Michael', 'Smith'),
('Robert', 'Smith');
Put your Thread.sleep
in a try catch block
try {
//thread to sleep for the specified number of milliseconds
Thread.sleep(100);
} catch ( java.lang.InterruptedException ie) {
System.out.println(ie);
}
<select ng-model="option" ng-options="o for o in options">
$scope.option will be equal to 'var1' after change, even you see value="0" in generated html
It's better to use change()
after setting select value.
$("div.id_100 select").val("val2").change();
By doing this, the code will close to changing select by user, the explanation is included in JS Fiddle:
Since .NET 3.0, you can simply use *yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*)
.
This will give you the point 0, 0 of your button, but towards the container. (You can also give an other point that 0, 0)
I don't think that has any meaning in SQL. You might be looking at Prepared Statements in JDBC or something. In that case, the question marks are placeholders for parameters to the statement.
I would would wrap the <ul>
with a <div ng-cloak>
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
As others have responded, the key you are trying to parse doesn't have the proper PKCS#8 headers which Oracle's PKCS8EncodedKeySpec
needs to understand it. If you don't want to convert the key using openssl pkcs8
or parse it using JDK internal APIs you can prepend the PKCS#8 header like this:
static final Base64.Decoder DECODER = Base64.getMimeDecoder();
private static byte[] buildPKCS8Key(File privateKey) throws IOException {
final String s = new String(Files.readAllBytes(privateKey.toPath()));
if (s.contains("--BEGIN PRIVATE KEY--")) {
return DECODER.decode(s.replaceAll("-----\\w+ PRIVATE KEY-----", ""));
}
if (!s.contains("--BEGIN RSA PRIVATE KEY--")) {
throw new RuntimeException("Invalid cert format: "+ s);
}
final byte[] innerKey = DECODER.decode(s.replaceAll("-----\\w+ RSA PRIVATE KEY-----", ""));
final byte[] result = new byte[innerKey.length + 26];
System.arraycopy(DECODER.decode("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKY="), 0, result, 0, 26);
System.arraycopy(BigInteger.valueOf(result.length - 4).toByteArray(), 0, result, 2, 2);
System.arraycopy(BigInteger.valueOf(innerKey.length).toByteArray(), 0, result, 24, 2);
System.arraycopy(innerKey, 0, result, 26, innerKey.length);
return result;
}
Once that method is in place you can feed it's output to the PKCS8EncodedKeySpec
constructor like this: new PKCS8EncodedKeySpec(buildPKCS8Key(privateKey));
In bootstrap 4 use "autoHide : true"
$('#datepicker1').datepicker({
autoHide: true,
format: 'mm-yyyy',
endDate: new Date()
});
The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.
Examples:
// firstName has a hard-coded value of "hello world"
string firstName = "hello world";
// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();
A hard-coded constant[1]:
float areaOfCircle(int radius)
{
float area = 0;
area = 3.14*radius*radius; // 3.14 is a hard-coded value
return area;
}
Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.
- Hard Coding “Hard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.
The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.- Soft Coding
If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.
In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.
In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.
Sources and Citations:
1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid
Further Reading:
Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding
I hope this can help someone in the future.
You can use the Google Geocoding API, as said before, I had to do some work with this recently, I hope this helps:
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script type="text/javascript">
function initialize() {
var address = (document.getElementById('my-address'));
var autocomplete = new google.maps.places.Autocomplete(address);
autocomplete.setTypes(['geocode']);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
});
}
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Latitude: "+results[0].geometry.location.lat());
alert("Longitude: "+results[0].geometry.location.lng());
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input type="text" id="my-address">
<button id="getCords" onClick="codeAddress();">getLat&Long</button>
</body>
</html>
Now this has also an autocomlpete function which you can see in the code, it fetches the address from the input and gets auto completed by the API while typing.
Once you have your address hit the button and you get your results via alert as required. Please also note this uses the latest API and it loads the 'places' library (when calling the API uses the 'libraries' parameter).
Hope this helps, and read the documentation for more information, cheers.
Edit #1: Fiddle
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
You may use the typescript getter method for this scenario. Like this
public get height() {
return window.innerHeight;
}
public get width() {
return window.innerWidth;
}
And use that in template like this:
<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768
}"></section>
Print the value
console.log(this.height, this.width);
You won't need any event handler to check for resizing of window, this method will check for size every time automatically.
<section [ngClass]="{'class1': expression1, 'class2': expression2,
'class3': expression3}">
Don't forget to add single quotes around class names.
I've only used jdom. It's pretty easy.
Go here for documentation and to download it: http://www.jdom.org/
If you have a very very large document then it's better not to read it all into memory, but use a SAX parser which calls your methods as it hits certain tags and attributes. You have to then create a state machine to deal with the incoming calls.
You can use URL encoding to encode the newline as %0A
.
mailto:[email protected]?subject=test&body=type%20your%0Amessage%20here
While the above appears to work in many cases, user olibre points out that the RFC governing the mailto URI scheme specifies that %0D%0A
(carriage return + line feed) should be used instead of %0A
(line feed). See also: Newline Representations.
I discovered SqlBulkCopy is an easy way to do this, and does not require a stored procedure to be written in SQL Server.
Here is an example of how I implemented it:
// take note of SqlBulkCopyOptions.KeepIdentity , you may or may not want to use this for your situation.
using (var bulkCopy = new SqlBulkCopy(_connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
// my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
foreach (DataColumn col in table.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = destinationTableName;
bulkCopy.WriteToServer(table);
}
Make sure you specify pass header=None
and add usecols=[3,6]
for the 4th and 7th columns.
i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:
your jQuery script needs to be after the elements you are referring to !
so your script needs to be after the html-code you want to access!
seems like jQuery can't access it otherwise.
You have to register the annotation binding for Jackson in your spring-mvc-config.xml, for example :
<!-- activates annotation driven binding -->
<mvc:annotation-driven ignoreDefaultModelOnRedirect="true" validator="validator">
<mvc:message-converters>
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
Then in your controller you can use :
@RequestMapping(value = "/your_url", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
You may remove the System.out
line. It is added for debug purposes.
WebDriver driver_;
public void waitForPageLoad() {
Wait<WebDriver> wait = new WebDriverWait(driver_, 30);
wait.until(new Function<WebDriver, Boolean>() {
public Boolean apply(WebDriver driver) {
System.out.println("Current Window State : "
+ String.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState")));
return String
.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState"))
.equals("complete");
}
});
}
The accepted answer via git merge will get the job done but leaves a messy commit hisotry, correct way should be 'rebase' via the following steps(assuming you want to keep your feature branch in sycn with develop before you do the final push before PR).
1 git fetch
from your feature branch (make sure the feature branch you are working on is update to date)
2 git rebase origin/develop
3 if any conflict shall arise, resolve them one by one
4 use git rebase --continue
once all conflicts are dealt with
5 git push --force
If you want to be real smart, at the command line type:
echo svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service >CreateService.cmd
Then you have CreateService.cmd
that you can run whenever you want (.cmd
is just another extension for .bat
files)
This is my solution.. i hope it helps anyone. It's written on the fly instead of copypasted so forgive me for any mistakes.
$("#btn").on("click", function(ev){
ev.preventDefault();
dialog.dialog("open");
dialog.find(".btnConfirm").on("click", function(){
// trigger click under different namespace so
// click handler will not be triggered but native
// functionality is preserved
$("#btn").trigger("click.confirmed");
}
dialog.find(".btnCancel").on("click", function(){
dialog.dialog("close");
}
});
Personally I prefer this solution :)
edit: Sorry.. i really shouldve explained it more in detail. I like it because in my opinion its an elegant solution. When user clicks the button which needs to be confirmed first the event is canceled as it has to be. When the confirmation button is clicked the solution is not to simulate a link click but to trigger the same native jquery event (click) upon the original button which would have triggered if there was no confirmation dialog. The only difference being a different event namespace (in this case 'confirmed') so that the confirmation dialog is not shown again. Jquery native mechanism can then take over and things can run as expected. Another advantage being it can be used for buttons and hyperlinks. I hope i was clear enough.
For SQL Server 2012:
SELECT name, modify_date, create_date, type
FROM sys.procedures
WHERE name like '%XXX%'
ORDER BY modify_date desc
In xaml
<TextBlock Text="{Binding CelsiusTemp}" />
In ViewModel
, this way setting the value also works:
public string CelsiusTemp
{
get { return string.Format("{0}°C", _CelsiusTemp); }
set
{
value = value.Replace("°C", "");
_CelsiusTemp = value;
}
}
Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/
Html:
<div id="content">
<iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>
Relevant parts of CSS:
div#content {
position: fixed;
top: 80px;
left: 40px;
bottom: 25px;
min-width: 200px;
width: 40%;
background: black;
}
div#content iframe {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
}
Should be easy to find in the javadocs...
byte[] byteArr = new byte[] { 0xC, 0xA, 0xF, 0xE };
InputStream is = new ByteArrayInputStream(byteArr);
Just delete key:
HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration
Or run in command line:
reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this worked for me in case of Class Extends Frame
EDIT
Disregard - you can't use ItemOf (that's what I get for typing before I test). I'd strikethrough the text if I could figure out how...or maybe I'll simply delete the answer, since it was ultimately wrong and useless.
END EDIT
You can use the ItemOf(string)
property in the XmlAttributesCollection to see if the attribute exists. It returns null if it's not found.
foreach (XmlNode xNode in nodeListName)
{
if (xNode.ParentNode.Attributes.ItemOf["split"] != null)
{
parentSplit = xNode.ParentNode.Attributes["split"].Value;
}
}
You'll have to benchmark, obviously, but over JDBC issuing multiple inserts will be much faster if you use a PreparedStatement rather than a Statement.
You can use a BehaviorSubject
for communicating between different components throughout the app. You can define a data sharing service containing the BehaviorSubject
to which you can subscribe and emit changes.
Define a data sharing service
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataSharingService {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}
Add the DataSharingService
in your AppModule
providers entry.
Next, import the DataSharingService
in your <app-header>
and in the component where you perform the sign-in operation. In <app-header>
subscribe to the changes to isUserLoggedIn
subject:
import { DataSharingService } from './data-sharing.service';
export class AppHeaderComponent {
// Define a variable to use for showing/hiding the Login button
isUserLoggedIn: boolean;
constructor(private dataSharingService: DataSharingService) {
// Subscribe here, this will automatically update
// "isUserLoggedIn" whenever a change to the subject is made.
this.dataSharingService.isUserLoggedIn.subscribe( value => {
this.isUserLoggedIn = value;
});
}
}
In your <app-header>
html template, you need to add the *ngIf
condition e.g.:
<button *ngIf="!isUserLoggedIn">Login</button>
<button *ngIf="isUserLoggedIn">Sign Out</button>
Finally, you just need to emit the event once the user has logged in e.g:
someMethodThatPerformsUserLogin() {
// Some code
// .....
// After the user has logged in, emit the behavior subject changes.
this.dataSharingService.isUserLoggedIn.next(true);
}
Another solution might be the following. Create a dictionary out of the list with item as key and index as value, and then print the dictionary keys.
>>> lst = [1, 3, 4, 2, 1, 21, 1, 32, 21, 1, 6, 5, 7, 8, 2]
>>>
>>> dict_enum = {item:index for index, item in enumerate(lst)}
>>> print dict_enum.keys()
[32, 1, 2, 3, 4, 5, 6, 7, 8, 21]
You could use mapvalues()
from the plyr package.
Initial data:
dat <- data.frame(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"))
> dat
HouseType
1 Semi
2 Single
3 Row
4 Single
5 Apartment
6 Apartment
7 Row
Lookup / crosswalk table:
lookup <- data.frame(type_text = c("Semi", "Single", "Row", "Apartment"), type_num = c(1, 2, 3, 4))
> lookup
type_text type_num
1 Semi 1
2 Single 2
3 Row 3
4 Apartment 4
Create the new variable:
dat$house_type_num <- plyr::mapvalues(dat$HouseType, from = lookup$type_text, to = lookup$type_num)
Or for simple replacements you can skip creating a long lookup table and do this directly in one step:
dat$house_type_num <- plyr::mapvalues(dat$HouseType,
from = c("Semi", "Single", "Row", "Apartment"),
to = c(1, 2, 3, 4))
Result:
> dat
HouseType house_type_num
1 Semi 1
2 Single 2
3 Row 3
4 Single 2
5 Apartment 4
6 Apartment 4
7 Row 3
This is a mistake:
m.check(side);
That code has to go inside a function. Your class definition can only contain declarations and functions.
Classes don't "run", they provide a blueprint for how to make an object.
The line Message m;
means that an Orderbook
will contain Message
called m
, if you later create an Orderbook
.
You can iterate DataTable
like this:
private void button1_Click(object sender, EventArgs e)
{
for(int i = 0; i< dt.Rows.Count;i++)
for (int j = 0; j <dt.Columns.Count ; j++)
{
object o = dt.Rows[i].ItemArray[j];
//if you want to get the string
//string s = o = dt.Rows[i].ItemArray[j].ToString();
}
}
Depending on the type of the data in the DataTable
cell, you can cast the object to whatever you want.
This should work:
[ int(x) for x in "40 1".split(" ") ]
The issue is that, even though you removed the files, they are still present in previous revisions. That's the whole point of git, is that even if you delete something, you can still get it back by accessing the history.
What you are looking to do is called rewriting history, and it involved the git filter-branch
command.
GitHub has a good explanation of the issue on their site. https://help.github.com/articles/remove-sensitive-data
To answer your question more directly, what you basically need to run is this command with unwanted_filename_or_folder
replaced accordingly:
git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch unwanted_filename_or_folder' --prune-empty
This will remove all references to the files from the active history of the repo.
Next step, to perform a GC cycle to force all references to the file to be expired and purged from the packfile. Nothing needs to be replaced in these commands.
git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
# or, for older git versions (e.g. 1.8.3.1) which don't support --stdin
# git update-ref $(git for-each-ref --format='delete %(refname)' refs/original)
git reflog expire --expire=now --all
git gc --aggressive --prune=now
When working with Visual Studio 2013 and VB.NET I found that you can quite easily customize the menu and add the "New Window" command - there is no need to mess with the registry!
God only knows why Microsoft chose not to include the command for some languages...?