There are plenty of good answers but I created a template header I use that is quite concise and easy to use.
To add an iterator to your class it is only necessary to write a small class to represent the state of the iterator with 7 small functions, of which 2 are optional:
#include <iostream>
#include <vector>
#include "iterator_tpl.h"
struct myClass {
std::vector<float> vec;
// Add some sane typedefs for STL compliance:
STL_TYPEDEFS(float);
struct it_state {
int pos;
inline void begin(const myClass* ref) { pos = 0; }
inline void next(const myClass* ref) { ++pos; }
inline void end(const myClass* ref) { pos = ref->vec.size(); }
inline float& get(myClass* ref) { return ref->vec[pos]; }
inline bool cmp(const it_state& s) const { return pos != s.pos; }
// Optional to allow operator--() and reverse iterators:
inline void prev(const myClass* ref) { --pos; }
// Optional to allow `const_iterator`:
inline const float& get(const myClass* ref) const { return ref->vec[pos]; }
};
// Declare typedef ... iterator;, begin() and end() functions:
SETUP_ITERATORS(myClass, float&, it_state);
// Declare typedef ... reverse_iterator;, rbegin() and rend() functions:
SETUP_REVERSE_ITERATORS(myClass, float&, it_state);
};
Then you can use it as you would expect from an STL iterator:
int main() {
myClass c1;
c1.vec.push_back(1.0);
c1.vec.push_back(2.0);
c1.vec.push_back(3.0);
std::cout << "iterator:" << std::endl;
for (float& val : c1) {
std::cout << val << " "; // 1.0 2.0 3.0
}
std::cout << "reverse iterator:" << std::endl;
for (auto it = c1.rbegin(); it != c1.rend(); ++it) {
std::cout << *it << " "; // 3.0 2.0 1.0
}
}
I hope it helps.
I was/am in the same boat as you for different reasons (partly educational, partly constraints). I had to re-write all the containers of the standard library and the containers had to conform to the standard. That means, if I swap out my container with the stl version, the code would work the same. Which also meant that I had to re-write the iterators.
Anyway, I looked at EASTL. Apart from learning a ton about containers that I never learned all this time using the stl containers or through my undergraduate courses. The main reason is that EASTL is more readable than the stl counterpart (I found this is simply because of the lack of all the macros and straight forward coding style). There are some icky things in there (like #ifdefs for exceptions) but nothing to overwhelm you.
As others mentioned, look at cplusplus.com's reference on iterators and containers.
Performance wise there is no difference. The only purpose of having const_iterator
over iterator
is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:
std::vector<int> integers{ 3, 4, 56, 6, 778 };
If we were to read & write the members of a container we will use iterator:
for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
{*it = 4; std::cout << *it << std::endl; }
If we were to only read the members of the container integers
you might wanna use const_iterator which doesn't allow to write or modify members of container.
for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
{ cout << *it << endl; }
NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.
on command line
example$:python
>>> import scipy
>>> scipy.__version__
'0.9.0'
The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.
You want HttpRuntime.AppDomainAppPath
.
If you're in an HTTP request, you can also call Server.MapPath("~/Whatever")
.
When we use an array, we are really using a pointer to the first element in the array. Hence, this condition if( iar1 == iar2 )
actually compares two addresses. Those pointers do not address the same object.
I think the best approach is to use a combination, Your second approach seems to be an elegant solution where browsers are involved.
So depending on the how the call is made. (whether its a browser or a web service call) you can use a combination of the two, with sending a URL to the browser and sending raw data to any other web service client.
The question was posted long time ago, many answers pool the target periodically and produces unnecessary waste of resources if the target is unchanged. In addition, most answers do not block the program while waiting for changes as required by the original post.
We can now apply a solution that is purely event-driven.
The solution uses onClick event to deliver event triggered by value change.
The solution can be run on modern browsers that support Promise and async/await. If you are using Node.js, consider EventEmitter as a better solution.
<!-- This div is the trick. -->_x000D_
<div id="trick" onclick="onTrickClick()" />_x000D_
_x000D_
<!-- Someone else change the value you monitored. In this case, the person will click this button. -->_x000D_
<button onclick="changeValue()">Change value</button>_x000D_
_x000D_
<script>_x000D_
_x000D_
// targetObj.x is the value you want to monitor._x000D_
const targetObj = {_x000D_
_x: 0,_x000D_
get x() {_x000D_
return this._x;_x000D_
},_x000D_
set x(value) {_x000D_
this._x = value;_x000D_
// The following line tells your code targetObj.x has been changed._x000D_
document.getElementById('trick').click();_x000D_
}_x000D_
};_x000D_
_x000D_
// Someone else click the button above and change targetObj.x._x000D_
function changeValue() {_x000D_
targetObj.x = targetObj.x + 1;_x000D_
}_x000D_
_x000D_
// This is called by the trick div. We fill the details later._x000D_
let onTrickClick = function () { };_x000D_
_x000D_
// Use Promise to help you "wait". This function is called in your code._x000D_
function waitForChange() {_x000D_
return new Promise(resolve => {_x000D_
onTrickClick = function () {_x000D_
resolve();_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// Your main code (must be in an async function)._x000D_
(async () => {_x000D_
while (true) { // The loop is not for pooling. It receives the change event passively._x000D_
await waitForChange(); // Wait until targetObj.x has been changed._x000D_
alert(targetObj.x); // Show the dialog only when targetObj.x is changed._x000D_
await new Promise(resolve => setTimeout(resolve, 0)); // Making the dialog to show properly. You will not need this line in your code._x000D_
}_x000D_
})();_x000D_
_x000D_
</script>
_x000D_
- What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)?
- Is this even the right approach? ie. should I not write functions that take an object as an argument, but rather, write member functions? (But even if so, please answer the original question.)
No, references cannot be null (unless Undefined Behavior has already happened, in which case all bets are already off). Whether you should write a method or non-method depends on other factors.
- Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?
If you need to represent "no object", then pass a pointer to the function, and let that pointer be NULL:
int silly_sum(int const* pa=0, int const* pb=0, int const* pc=0) {
/* Take up to three ints and return the sum of any supplied values.
Pass null pointers for "not supplied".
This is NOT an example of good code.
*/
if (!pa && (pb || pc)) return silly_sum(pb, pc);
if (!pb && pc) return silly_sum(pa, pc);
if (pc) return silly_sum(pa, pb) + *pc;
if (pa && pb) return *pa + *pb;
if (pa) return *pa;
if (pb) return *pb;
return 0;
}
int main() {
int a = 1, b = 2, c = 3;
cout << silly_sum(&a, &b, &c) << '\n';
cout << silly_sum(&a, &b) << '\n';
cout << silly_sum(&a) << '\n';
cout << silly_sum(0, &b, &c) << '\n';
cout << silly_sum(&a, 0, &c) << '\n';
cout << silly_sum(0, 0, &c) << '\n';
return 0;
}
If "no object" never needs to be represented, then references work fine. In fact, operator overloads are much simpler because they take overloads.
You can use something like boost::optional.
I can't comment on the top answer, but a swift implementation would be:
self.tableView.reloadSections([0], with: UITableViewRowAnimation.fade)
you could include as many sections as you want to update in the first argument for reloadSections.
Other animations available from the docs: https://developer.apple.com/reference/uikit/uitableviewrowanimation
fade The inserted or deleted row or rows fade into or out of the table view.
right The inserted row or rows slide in from the right; the deleted row or rows slide out to the right.
left The inserted row or rows slide in from the left; the deleted row or rows slide out to the left.
top The inserted row or rows slide in from the top; the deleted row or rows slide out toward the top.
bottom The inserted row or rows slide in from the bottom; the deleted row or rows slide out toward the bottom.
case none The inserted or deleted rows use the default animations.
middle The table view attempts to keep the old and new cells centered in the space they did or will occupy. Available in iPhone 3.2.
automatic The table view chooses an appropriate animation style for you. (Introduced in iOS 5.0.)
var defaultsettings = {
ajaxsettings: {
...
},
uisettings: {
...
}
};
You'll need to join twice:
SELECT home.*, away.*, g.network, g.date_start
FROM game AS g
INNER JOIN team AS home
ON home.importid = g.home
INNER JOIN team AS away
ON away.importid = g.away
ORDER BY g.date_start DESC
LIMIT 7
A working solution in pure CSS:
The trick is to suppose there's a dom element after the text-field.
/*_x000D_
* The trick is here:_x000D_
* this selector says "take the first dom element after_x000D_
* the input text (+) and set its before content to the_x000D_
* value (:before)._x000D_
*/_x000D_
input#myTextField + *:before {_x000D_
content: "";_x000D_
}
_x000D_
<input id="myTextField" class="mystyle" type="text" value="someValue" />_x000D_
<!--_x000D_
There's maybe something after a input-text_x000D_
Does'nt matter what it is (*), I use it._x000D_
-->_x000D_
<span></span>
_x000D_
(*) Limited solution, though:
But in most cases, we know our code so this solution seems efficient and 100% CSS and 0% jQuery.
Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError
that implements the LocalizedError
protocol.
struct DisplayableError: Error, LocalizedError {
let errorDescription: String?
init(_ description: String) {
errorDescription = description
}
}
Usage for throwing:
throw DisplayableError("Out of pixie dust.")
Usage for display:
let messageToDisplay = error.localizedDescription
The @
disables echo for that one command. Without it, the echo start eclipse.exe
line would print both the intended start eclipse.exe
and the echo start eclipse.exe
line.
The echo off
turns off the by-default command echoing.
So @echo off
silently turns off command echoing, and only output the batch author intended to be written is actually written.
Go to Preferences -> Accounts, remove your account and add it again. Then try uploading again and wait a few minutes.
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name) # Write inside file
f.close() # Close file
# Method 2shush
with open("Path/To/Your/File.txt", "w") as f: # Opens file and casts as f
f.write("Hello World form " + f.name) # Writing
# File closed automatically
You can use Array.push()
for appending elements to an array.
For deleting, it is best to use this.$delete(array, index)
for reactive objects.
Vue.delete( target, key )
: Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
Make use of case-insensitve matching using stripos()
:
if (stripos($string,$stringToSearch) !== false) {
echo 'true';
}
The answer
$scope.$watch('$viewContentLoaded',
function() {
$timeout(function() {
//do something
},0);
});
is the only one that works in most scenarios I tested. In a sample page with 4 components all of which build HTML from a template, the order of events was
$document ready
$onInit
$postLink
(and these 3 were repeated 3 more times in the same order for the other 3 components)
$viewContentLoaded (repeated 3 more times)
$timeout execution (repeated 3 more times)
So a $document.ready() is useless in most cases since the DOM being constructed in angular may be nowhere near ready.
But more interesting, even after $viewContentLoaded fired, the element of interest still could not be found.
Only after the $timeout executed was it found. Note that even though the $timeout was a value of 0, nearly 200 milliseconds elapsed before it executed, indicating that this thread was held off for quite a while, presumably while the DOM had angular templates added on a main thread. The total time from the first $document.ready() to the last $timeout execution was nearly 500 milliseconds.
In one extraordinary case where the value of a component was set and then the text() value was changed later in the $timeout, the $timeout value had to be increased until it worked (even though the element could be found during the $timeout). Something async within the 3rd party component caused a value to take precedence over the text until sufficient time passed. Another possibility is $scope.$evalAsync, but was not tried.
I am still looking for that one event that tells me the DOM has completely settled down and can be manipulated so that all cases work. So far an arbitrary timeout value is necessary, meaning at best this is a kludge that may not work on a slow browser. I have not tried JQuery options like liveQuery and publish/subscribe which may work, but certainly aren't pure angular.
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
I was able to fix the error by
A little history of this case and observations:
For completing the answers, Spring MVC uses viewResolver(for example, as axtavt metionned, InternalResourceViewResolver) to get the specific view. Therefore the first step is making sure that a viewResolver is configured.
Secondly, you should pay attention to the url of redirection(redirect or forward). A url starting with "/" means that it's a url absolute in the application. As Jigar says,
return "redirect:/index.html";
should work. If your view locates in the root of the application, Spring can find it. If a url without a "/", such as that in your question, it means a url relative. It explains why it worked before and don't work now. If your page calling "redirect" locates in the root by chance, it works. If not, Spring can't find the view and it doesn't work.
Here is the source code of the method of RedirectView of Spring
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Prepare target URL.
StringBuilder targetUrl = new StringBuilder();
if (this.contextRelative && getUrl().startsWith("/")) {
// Do not apply context path to relative URLs.
targetUrl.append(request.getContextPath());
}
targetUrl.append(getUrl());
// ...
sendRedirect(request, response, targetUrl.toString(), this.http10Compatible);
}
In my case, radio button value is fetched from database and then set into the form. Following code works for me.
$("input[name=name_of_radio_button_fields][value=" + saved_value_comes_from_database + "]").prop('checked', true);
bash -c
works well if the commands you are running are relatively simple. However, if you're trying to run a long series of commands full of control characters, it can get complex.
I successfully got around this by piping my commands into the process from the outside, i.e.
cat script.sh | docker run -i <image> /bin/bash
I you are using java prior to version 1.6 use System.arraycopy()
instead. Or upgrade your environment.
At this point:
for (String[] s : myEntries) {
System.out.println("Next item: " + s);
}
You need to join the array of Strings in a line. Check this post: A method to reverse effect of java String.split()?
It sounds like you're trying to use log4j from "both ends" (the consumer end and the configuration end).
If you want to code against the slf4j api but determine ahead of time (and programmatically) the configuration of the log4j Loggers that the classpath will return, you absolutely have to have some sort of logging adaptation which makes use of lazy construction.
public class YourLoggingWrapper {
private static boolean loggingIsInitialized = false;
public YourLoggingWrapper() {
// ...blah
}
public static void debug(String debugMsg) {
log(LogLevel.Debug, debugMsg);
}
// Same for all other log levels your want to handle.
// You mentioned TRACE and ERROR.
private static void log(LogLevel level, String logMsg) {
if(!loggingIsInitialized)
initLogging();
org.slf4j.Logger slf4jLogger = org.slf4j.LoggerFactory.getLogger("DebugLogger");
switch(level) {
case: Debug:
logger.debug(logMsg);
break;
default:
// whatever
}
}
// log4j logging is lazily constructed; it gets initialized
// the first time the invoking app calls a log method
private static void initLogging() {
loggingIsInitialized = true;
org.apache.log4j.Logger debugLogger = org.apache.log4j.LoggerFactory.getLogger("DebugLogger");
// Now all the same configuration code that @oers suggested applies...
// configure the logger, configure and add its appenders, etc.
debugLogger.addAppender(someConfiguredFileAppender);
}
With this approach, you don't need to worry about where/when your log4j loggers get configured. The first time the classpath asks for them, they get lazily constructed, passed back and made available via slf4j. Hope this helped!
To Install bash you can do:
RUN apk add --update bash && rm -rf /var/cache/apk/*
If you do not want to add extra size to your image, you can use ash
or sh
that ships with alpine.
Reference: https://github.com/smebberson/docker-alpine/issues/43
To get the selected value of a spinner you can follow this example.
Create a nested class that implements AdapterView.OnItemSelectedListener. This will provide a callback method that will notify your application when an item has been selected from the Spinner.
Within "onItemSelected" method of that class, you can get the selected item:
public class YourItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected = parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Finally, your ItemSelectedListener needs to be registered in the Spinner:
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
Here is what I figured, and this happened recently on Windows 10 after an update was installed. From what I gathered, a Windows Defender update was installed which assumed my "Project.dll"(an asp.net core project) behaved like a virus so it was deleted.
So, one of the first things I suggest you do before you start installing/uninstalling stuffs is to check to confirm your "Project.dll" is where it should be.
Copy it back to the location if it is no longer there.
If you are having difficulty copying the file back add an exclusion to your project folder in windows defender. ( Learn how to do that here. )
This worked for me instantly, and I repeated it across application multiple servers.
Am I missing something? You can just convert offer_date in the comparison:
SELECT *
FROM offers
WHERE to_char(offer_date, 'YYYYMM') = (SELECT to_date(create_date, 'YYYYMM') FROM customers where id = '12345678') AND
offer_rate > 0
Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.
The best way is to print joined string of numbers converted to strings.
print(" ".join(list(map(str,l))))
Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:
import time as t
a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
print(i, end=" ")
print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)
Result:
Time 74344.76 71790.83 196.99 153.99
The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.
Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).
For the odd positions, you probably want:
>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>
I did the test (but it is not your example) and the data does not return them orderly or complete
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = {x.replace('p','') for x in ind}
>>> newind
{'1', '2', '8', '5', '4'}
I proved that this works:
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = [x.replace('p','') for x in ind]
>>> newind
['5', '1', '8', '4', '2', '8']
or
>>> newind = []
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> for x in ind:
... newind.append(x.replace('p',''))
>>> newind
['5', '1', '8', '4', '2', '8']
If you are on Spring Boot then you can directly add following properties in application.properties file to set logging level, customize logging pattern and to store logs in the external file.
These are different logging levels and its order from minimum << maximum.
OFF << FATAL << ERROR << WARN << INFO << DEBUG << TRACE << ALL
# To set logs level as per your need.
logging.level.org.springframework = debug
logging.level.tech.hardik = trace
# To store logs to external file
# Here use strictly forward "/" slash for both Windows, Linux or any other os, otherwise, its won't work.
logging.file=D:/spring_app_log_file.log
# To customize logging pattern.
logging.pattern.file= "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"
Please pass through this link to customize your log more vividly.
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
If you are using Perforce (imported the project as a Perforce project), then .cproject and .project will be located under the root of the PERFORCE project, not on the workspace folder.
Hope this helps :)
I had this problem and its because I wasnt using the latest version of C# (C# 7.3 as of writing this) and I had to change the below internal
access modifier to public
.
internal class Program
{
public static void Main(string[] args)
{
//My Code
}
}
or ammend the .csproj
to use the latest version of C# (this way meant I could still keep the above class as internal
):
<PropertyGroup>
<LangVersion>latest</LangVersion>
<NoWin32Manifest>true</NoWin32Manifest>
</PropertyGroup>
Swift 5.0
func makeTransform(horizontalDegree: CGFloat, verticalDegree: CGFloat, maxVertical: CGFloat,rotateDegree: CGFloat, maxHorizontal: CGFloat) -> CATransform3D {
var transform = CATransform3DIdentity
transform.m34 = 1 / -500
let xAnchor = (horizontalDegree / (2 * maxHorizontal)) + 0.5
let yAnchor = (verticalDegree / (-2 * maxVertical)) + 0.5
let anchor = CGPoint(x: xAnchor, y: yAnchor)
setAnchorPoint(anchorPoint: anchor, forView: self.imgView)
let hDegree = (CGFloat(horizontalDegree) * .pi) / 180
let vDegree = (CGFloat(verticalDegree) * .pi) / 180
let rDegree = (CGFloat(rotateDegree) * .pi) / 180
transform = CATransform3DRotate(transform, vDegree , 1, 0, 0)
transform = CATransform3DRotate(transform, hDegree , 0, 1, 0)
transform = CATransform3DRotate(transform, rDegree , 0, 0, 1)
return transform
}
func setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {
var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y)
var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y)
newPoint = newPoint.applying(view.transform)
oldPoint = oldPoint.applying(view.transform)
var position = view.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
print("Anchor: \(anchorPoint)")
view.layer.position = position
view.layer.anchorPoint = anchorPoint
}
you only need to call the function with your degree. for example:
var transform = makeTransform(horizontalDegree: 20.0 , verticalDegree: 25.0, maxVertical: 25, rotateDegree: 20, maxHorizontal: 25)
imgView.layer.transform = transform
Since nobody so far felt fit to point out why what you're trying doesn't work:
NA == NA
doesn't return TRUE
, it returns NA
(since comparing to undefined values should yield an undefined result). apply
on an atomic vector. You can't use apply
to loop over the elements in a column. a$x
, which is just the column (an atomic vector).I'd fix up 3. to get to a$x[is.na(a$x)] <- 0
You can set your activity to use a specific volume. In your activity, use one of the following:
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
this.setVolumeControlStream(AudioManager.STREAM_RING);
this.setVolumeControlStream(AudioManager.STREAM_ALARM);
this.setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);
this.setVolumeControlStream(AudioManager.STREAM_SYSTEM);
this.setVolumeControlStream(AudioManager.STREAM_VOICECALL);
For a duplicate, here another option with transform, no fieldset ( and rounded border required in the duplicates) :
position or transform can help you too :
_x000D__x000D__x000D__x000D__x000D_* { margin: 0; padding:0; box-sizing:border-box; } .fieldset { border: solid; color: #353fff; border-radius: 1em; margin: 2em 1em 1em; padding:0 1em 1em; } .legend { transform: translatey(-50%); width: max-content; background: white; padding: 0 0.15em; } .fieldset li { list-style-type: " - "; }
_x000D_<div class="fieldset"> <h1 class="legend">Some Title</h1> <ul> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> </ul> </div>
You know that Maven is based on the Convention over Configuration pardigm? so you shouldn't configure things which are the defaults.
All that stuff represents the default in Maven. So best practice is don't define it it's already done.
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
Litmus may help you. It will take screenshots of your webpage(s) in a wide variety of browsers so you can make sure that your site works in all of them. A free alternative (Litmus is a paid service) is Browsershots, but you do get what you pay for. (In some screenshots that Browershots returns, the browser hasn't yet finished loading the webpage...)
Of course, as other people have suggested, buying a Mac is also a good solution (and may be better, depending on the kind of testing you need to do), because then you can test your website yourself in any of the browsers that run under Mac OS X or Windows.
I hate to admit how little I've done an iPhone app for, but I can tell you I won't be doing that again. The guy who said that "simple, one function apps can be done .. [by solo developers]... for $5K" is correct; however, that is still lowball, and presumes almost no project design, graphic design or network backend work.
You can determine if as certain word is found in a cell by using
If InStr(cell.Value, "Word1") > 0 Then
If Word1 is found in the string the InStr()
function will return the location of the first character of Word1 in the string.
After not finding anything to get around "Object must implement IConvertible" exception when using Zyphrax's answer (except for implementing the interface).. I tried something a little bit unconventional and worked for my situation.
Using the Newtonsoft.Json nuget package...
var castedObject = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(myObject), myType);
var validation = {
isEmailAddress:function(str) {
var pattern =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return pattern.test(str); // returns a boolean
},
isNotEmpty:function (str) {
var pattern =/\S+/;
return pattern.test(str); // returns a boolean
},
isNumber:function(str) {
var pattern = /^\d+$/;
return pattern.test(str); // returns a boolean
},
isSame:function(str1,str2){
return str1 === str2;
}
};
alert(validation.isNotEmpty("dff"));
alert(validation.isNumber(44));
alert(validation.isEmailAddress("[email protected]"));
alert(validation.isSame("sf","sf"));
I found this to be helpful:
http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/
public enum Difficulty
{
EASY(0),
MEDIUM(1),
HARD(2);
/**
* Value for this difficulty
*/
public final int Value;
private Difficulty(int value)
{
Value = value;
}
// Mapping difficulty to difficulty id
private static final Map<Integer, Difficulty> _map = new HashMap<Integer, Difficulty>();
static
{
for (Difficulty difficulty : Difficulty.values())
_map.put(difficulty.Value, difficulty);
}
/**
* Get difficulty from value
* @param value Value
* @return Difficulty
*/
public static Difficulty from(int value)
{
return _map.get(value);
}
}
The alternative and easier solution that i also use is to create custom marker layout and convert it into a bitmap.
view_custom_marker.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_marker_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/marker_mask">
<ImageView
android:id="@+id/profile_image"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:contentDescription="@null"
android:src="@drawable/avatar" />
</FrameLayout>
Convert this view into bitmap by using the code below
private Bitmap getMarkerBitmapFromView(@DrawableRes int resId) {
View customMarkerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.view_custom_marker, null);
ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.profile_image);
markerImageView.setImageResource(resId);
customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
customMarkerView.buildDrawingCache();
Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = customMarkerView.getBackground();
if (drawable != null)
drawable.draw(canvas);
customMarkerView.draw(canvas);
return returnedBitmap;
}
Add your custom marker in on Map ready callback.
@Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady() called with");
mGoogleMap = googleMap;
MapsInitializer.initialize(this);
addCustomMarker();
}
private void addCustomMarker() {
Log.d(TAG, "addCustomMarker()");
if (mGoogleMap == null) {
return;
}
// adding a marker on map with image from drawable
mGoogleMap.addMarker(new MarkerOptions()
.position(mDummyLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(R.drawable.avatar))));
}
For more details please follow the link below
To get the number of votes for a specific item, you would use:
vote_count = Item.objects.filter(votes__contest=contestA).count()
If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:
contest = Contest.objects.get(pk=contest_id)
votes = contest.votes_set.select_related()
vote_counts = {}
for vote in votes:
if not vote_counts.has_key(vote.item.id):
vote_counts[vote.item.id] = {
'item': vote.item,
'count': 0
}
vote_counts[vote.item.id]['count'] += 1
This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.
Option Explicit
Const ConnectionStrngAccessPW As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB-PW.accdb;
Jet OLEDB:Database Password=123pass;"
Const ConnectionStrngAccess As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB.accdb;
Persist Security Info=False;"
'C:\Users\BARON\Desktop\Test.accdb
Sub ModifyingExistingDataOnAccessDB()
Dim TableConn As ADODB.Connection
Dim TableData As ADODB.Recordset
Set TableConn = New ADODB.Connection
Set TableData = New ADODB.Recordset
TableConn.ConnectionString = ConnectionStrngAccess
TableConn.Open
On Error GoTo CloseConnection
With TableData
.ActiveConnection = TableConn
'.Source = "SELECT Emp_Age FROM Roster WHERE Emp_Age > 40;"
.Source = "Roster"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
On Error GoTo CloseRecordset
Do Until .EOF
If .Fields("Emp_Age").Value > 40 Then
.Fields("Emp_Age").Value = 40
.Update
End If
.MoveNext
Loop
.MoveFirst
MsgBox "Update Complete"
End With
CloseRecordset:
TableData.CancelUpdate
TableData.Close
CloseConnection:
TableConn.Close
Set TableConn = Nothing
Set TableData = Nothing
End Sub
Sub AddingDataToAccessDB()
Dim TableConn As ADODB.Connection
Dim TableData As ADODB.Recordset
Dim r As Range
Set TableConn = New ADODB.Connection
Set TableData = New ADODB.Recordset
TableConn.ConnectionString = ConnectionStrngAccess
TableConn.Open
On Error GoTo CloseConnection
With TableData
.ActiveConnection = TableConn
.Source = "Roster"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
On Error GoTo CloseRecordset
Sheet3.Activate
For Each r In Range("B3", Range("B3").End(xlDown))
MsgBox "Adding " & r.Offset(0, 1)
.AddNew
.Fields("Emp_ID").Value = r.Offset(0, 0).Value
.Fields("Emp_Name").Value = r.Offset(0, 1).Value
.Fields("Emp_DOB").Value = r.Offset(0, 2).Value
.Fields("Emp_SOD").Value = r.Offset(0, 3).Value
.Fields("Emp_EOD").Value = r.Offset(0, 4).Value
.Fields("Emp_Age").Value = r.Offset(0, 5).Value
.Fields("Emp_Gender").Value = r.Offset(0, 6).Value
.Update
Next r
MsgBox "Update Complete"
End With
CloseRecordset:
TableData.Close
CloseConnection:
TableConn.Close
Set TableConn = Nothing
Set TableData = Nothing
End Sub
You generally want to ignore the SIGPIPE
and handle the error directly in your code. This is because signal handlers in C have many restrictions on what they can do.
The most portable way to do this is to set the SIGPIPE
handler to SIG_IGN
. This will prevent any socket or pipe write from causing a SIGPIPE
signal.
To ignore the SIGPIPE
signal, use the following code:
signal(SIGPIPE, SIG_IGN);
If you're using the send()
call, another option is to use the MSG_NOSIGNAL
option, which will turn the SIGPIPE
behavior off on a per call basis. Note that not all operating systems support the MSG_NOSIGNAL
flag.
Lastly, you may also want to consider the SO_SIGNOPIPE
socket flag that can be set with setsockopt()
on some operating systems. This will prevent SIGPIPE
from being caused by writes just to the sockets it is set on.
It's been awhile since I've done anything with batch files but I think that the following works:
find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done
This is really a proof of concept; clean up as it suits your needs. The key is that find
returns an errorlevel
of 1
if string
is not in file
. We branch to notfound
in this case otherwise we handle the found
case.
It gets a little bit more complicated if you want to add the background to a specific modal. One way of solving that is to add and call something like this function instead of showing the modal directly:
function showModal(selector) {
$(selector).modal('show');
$('.modal-backdrop').addClass('background-backdrop');
}
Any css can then be applied to the background-backdrop
class.
SOLUTION 1
First working solution (tested) useful especially when using @EnableWebMvc:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Autowired
private ObjectMapper objectMapper;// created elsewhere
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// this won't add a 2nd MappingJackson2HttpMessageConverter
// as the SOLUTION 2 is doing but also might seem complicated
converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> {
// check default included objectMapper._registeredModuleTypes,
// e.g. Jdk8Module, JavaTimeModule when creating the ObjectMapper
// without Jackson2ObjectMapperBuilder
((MappingJackson2HttpMessageConverter) c).setObjectMapper(this.objectMapper);
});
}
SOLUTION 2
Of course the common approach below works too (also working with @EnableWebMvc):
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Autowired
private ObjectMapper objectMapper;// created elsewhere
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// this will add a 2nd MappingJackson2HttpMessageConverter
// (additional to the default one) but will work and you
// won't lose the default converters as you'll do when overwriting
// configureMessageConverters(List<HttpMessageConverter<?>> converters)
//
// you still have to check default included
// objectMapper._registeredModuleTypes, e.g.
// Jdk8Module, JavaTimeModule when creating the ObjectMapper
// without Jackson2ObjectMapperBuilder
converters.add(new MappingJackson2HttpMessageConverter(this.objectMapper));
}
Why @EnableWebMvc usage is a problem?
@EnableWebMvc is using DelegatingWebMvcConfiguration
which extends WebMvcConfigurationSupport
which does this:
if (jackson2Present) {
Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
if (this.applicationContext != null) {
builder.applicationContext(this.applicationContext);
}
messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
which means that there's no way of injecting your own ObjectMapper
with the purpose of preparing it to be used for creating the default MappingJackson2HttpMessageConverter
when using @EnableWebMvc.
React ajax debounce and cancellation example solution using React Hooks and reactive programming (RxJS):
import React, { useEffect, useState } from "react";
import { ajax } from "rxjs/ajax";
import { debounceTime, delay, takeUntil } from "rxjs/operators";
import { Subject } from "rxjs/internal/Subject";
const App = () => {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
const [filterChangedSubject] = useState(() => {
// Arrow function is used to init Singleton Subject. (in a scope of a current component)
return new Subject<string>();
});
useEffect(() => {
// Effect that will be initialized once on a react component init.
const subscription = filterChangedSubject
.pipe(debounceTime(200))
.subscribe((filter) => {
if (!filter) {
setLoading(false);
setItems([]);
return;
}
ajax(`https://swapi.dev/api/people?search=${filter}`)
.pipe(
// current running ajax is canceled on filter change.
takeUntil(filterChangedSubject)
)
.subscribe(
(results) => {
// Set items will cause render:
setItems(results.response.results);
},
() => {
setLoading(false);
},
() => {
setLoading(false);
}
);
});
return () => {
// On Component destroy. notify takeUntil to unsubscribe from current running ajax request
filterChangedSubject.next("");
// unsubscribe filter change listener
subscription.unsubscribe();
};
}, []);
const onFilterChange = (e) => {
// Notify subject about the filter change
filterChangedSubject.next(e.target.value);
};
return (
<div>
Cards
{loading && <div>Loading...</div>}
<input onChange={onFilterChange}></input>
{items && items.map((item, index) => <div key={index}>{item.name}</div>)}
</div>
);
};
export default App;
Managed to do it:
b = pd.read_csv('b.dat')
b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
b.groupby(by=[b.index.month, b.index.year])
Or
b.groupby(pd.Grouper(freq='M')) # update for v0.21+
I think what you're trying to do is:
-(void) score2 {
[self score];
}
The [object message]
syntax is the normal way to call a method in objective-c. I think the @selector
syntax is used when the method to be called needs to be determined at run-time, but I don't know objective-c well enough to give you more information on that.
I had this problem with my datasource in WildFly and Tomcat, connecting to a Oracle 10g.
I found that under certain conditions the statement wasn't closed even when the statement.close() was invoked. The problem was with the Oracle Driver we were using: ojdbc7.jar. This driver is intended for Oracle 12c and 11g, and it seems has some issues when is used with Oracle 10g, so I downgrade to ojdbc5.jar and now everything is running fine.
Try following
ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <FOREIGN_KEY_NAME>
Check out https://github.com/derek-watson/jsUri
Uri and query string manipulation in javascript.
This project incorporates the excellent parseUri regular expression library by Steven Levithan. You can safely parse URLs of all shapes and sizes, however invalid or hideous.
I think Michal's answer is the best, but we can take it a step further and dynamically load an Android CSS as per the original question:
var isAndroid = /(android)/i.test(navigator.userAgent);
if (isAndroid) {
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", "/css/android.css");
document.body.appendChild(css);
}
You could try running the "mvn site" command and see what transitive dependencies you have, and then resolve potential conflicts (by ommitting an implicit dependency somewhere). Just a guess (it's a bit difficult to know what the problem could be without seeing your pom info)...
Here is a simple mail sending code with attachment
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword");
string from = "[email protected]";
string to = "[email protected]";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
Read more Sending emails with attachment in C#
SOLUTION: I make a directive for all inputs, number, text, or any, in the app, so you can input a value and change the event. Make for angular 6
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector: 'input[inputType]'
})
export class InputTypeDirective {
constructor(private _el: ElementRef) {}
@Input() inputType: string;
// tipos: number, letter, cuit, tel
@HostListener('input', ['$event']) onInputChange(event) {
if (!event.data) {
return;
}
switch (this.inputType) {
case 'number': {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if (initalValue !== this._el.nativeElement.value) {
event.stopPropagation();
}
break;
}
case 'text': {
const result = event.data.match(/[^a-zA-Z Ññ]*/g);
if (result[0] !== '') {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(
/[^a-zA-Z Ññ]*/g,
''
);
event.stopPropagation();
}
break;
}
case 'tel':
case 'cuit': {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(/[^0-9-]*/g, '');
if (initalValue !== this._el.nativeElement.value) {
event.stopPropagation();
}
}
}
}
}
HTML
<input matInput inputType="number" [formControlName]="field.name" [maxlength]="field.length" [placeholder]="field.label | translate" type="text" class="filter-input">
Instead of using the placeholder text, you'll want to set the actual text
property of the field to MM/YYYY, set the delegate of the text field and listen for this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // update the text of the label }
Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.
public void onRestart() {
super.onRestart();
Intent intent=new Intent();
intent.setClass(act, act.getClass());
finish();
act.startActivity(intent);
}
try to use this ..
See How to Make Dialogs.
You can use:
JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.
private ArrayList ShuffleArrayList(ArrayList source)
{
ArrayList sortedList = new ArrayList();
Random generator = new Random();
while (source.Count > 0)
{
int position = generator.Next(source.Count);
sortedList.Add(source[position]);
source.RemoveAt(position);
}
return sortedList;
}
The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.
This explains the "strange results".
"Better" results can be obtained using the expressions below:
//*[text() = 'qwerty']
The above selects every element in the document that has at least one text-node child with value 'qwerty'.
//*[text() = 'qwerty' and not(text()[2])]
The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.
This solution actually works for me.. go to this pc -> properties -> advanced system settings -> environment variables -> then in system variable create new variable with name ANDROID_SDK_ROOT and value C:\Users{USERNAME(Replace it with your username}\AppData\Local\Android\Sdk
and make sure that if real android mobile using usb debugging is enabled. (very important)
then close cmd and restart it should work.
Just think of it as the "starting point".
In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.
For example
public class IamMain // when export and require this guy
{
public IamMain() // this is "main"
{...}
... // many others such as function, properties, etc.
}
I know this is old question. But maybe this can help you
var jsonStr = '{ "bool": true, "number": 123, "string": "foo bar" }';
JSON.stringify(JSON.parse(jsonStr), null, 2);
JSON.stringify(JSON.parse(jsonStr));
we just can show same label div on hovering like this
<style>
#b {
display: none;
}
#content:hover~#b{
display: block;
}
</style>
Without group by SUM(NVL(regular, 0) + NVL(overtime, 0))
will thrown an error and to avoid this we can simply use NVL(regular, 0) + NVL(overtime, 0)
SQLite doesn't support removing or modifying columns, apparently. But do remember that column data types aren't rigid in SQLite, either.
See also:
You can create an extension function or just use setCompoundDrawablesWithIntrinsicBounds
directly.
fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}
If you need to resize the drawable, you can use this extension function.
textView.leftDrawable(R.drawable.my_icon, R.dimen.icon_size)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
To get really fancy, create a wrapper that allows size and/or color modification.
textView.leftDrawable(R.drawable.my_icon, colorRes = R.color.white)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int = 0, @ColorInt color: Int = 0, @ColorRes colorRes: Int = 0) {
val drawable = drawable(id)
if (sizeRes != 0) {
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
}
if (color != 0) {
drawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
} else if (colorRes != 0) {
val colorInt = ContextCompat.getColor(context, colorRes)
drawable?.setColorFilter(colorInt, PorterDuff.Mode.SRC_ATOP)
}
this.setCompoundDrawables(drawable, null, null, null)
}
In this example, the line do_something_else()
will not be executed if do_not_continue
is True
. Control will return, instead, to whichever function called some_function
.
def some_function():
if do_not_continue:
return # implicitly, this is the same as saying `return None`
do_something_else()
<div id="radio">
<input type="radio" id="radio1" name="radio"/><label for="radio1">Bar Chart</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Pie Chart</label>
<input type="radio" id="radio3" name="radio"/><label for="radio3">Datapoint Chart</label>
</div>
$('#radio input').removeAttr('checked');
// Refresh the jQuery UI buttonset.
$( "#radio" ).buttonset('refresh');
Something none of the other answers touch on is that your first loop is indexing though the list. Whereas the for-each loop is using an Iterator
. Some lists like LinkedList
will iterate faster with an Iterator
versus get(i)
. This is because because link list's iterator keeps track of the current pointer. Whereas each get
in your for i=0 to 9 has to recompute the offset into the linked list. In general, its better to use for-each or an Iterator
because it will be using Collection
s iterator, which in theory is optimized for the collection type.
I had this same issue but found the following that works great:
The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.
Here is what a typical YouTube embed code looks like, with fixed width and height:
<iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw"
frameborder="0" allowfullscreen></iframe>
It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):
<div class="container">
<iframe src="//www.youtube.com/embed/yCOY82UdFrw"
frameborder="0" allowfullscreen class="video"></iframe>
</div>
And use the following CSS:
.container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%;
}
.video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Here is the page I found the solution on:
https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed
Depending on your aspect ratio, you will probably need to adjust the padding-bottom: 56.25%;
to get the height right.
Seems I found the solution. I hadn't properly noticed the keyAt(index)
function.
So I'll go with something like this:
for(int i = 0; i < sparseArray.size(); i++) {
int key = sparseArray.keyAt(i);
// get the object by the key.
Object obj = sparseArray.get(key);
}
I liked Lukasz version, but since urllib and urllparse functions are somewhat awkward to use in this case, I think it's more straightforward to do something like this:
params = urllib.urlencode(params)
if urlparse.urlparse(url)[4]:
print url + '&' + params
else:
print url + '?' + params
The easiest way to create an object in JavaScript is to use the following syntax :
var test = {_x000D_
a : 5,_x000D_
b : 10,_x000D_
f : function(c) {_x000D_
return this.a + this.b + c;_x000D_
}_x000D_
}_x000D_
_x000D_
console.log(test);_x000D_
console.log(test.f(3));
_x000D_
This works great for storing data in a structured way.
For more complex use cases, however, it's often better to create instances of functions :
function Test(a, b) {_x000D_
this.a = a;_x000D_
this.b = b;_x000D_
this.f = function(c) {_x000D_
return this.a + this.b + c;_x000D_
};_x000D_
}_x000D_
_x000D_
var test = new Test(5, 10);_x000D_
console.log(test);_x000D_
console.log(test.f(3));
_x000D_
This allows you to create multiple objects that share the same "blueprint", similar to how you use classes in eg. Java.
This can still be done more efficiently, however, by using a prototype.
Whenever different instances of a function share the same methods or properties, you can move them to that object's prototype. That way, every instance of a function has access to that method or property, but it doesn't need to be duplicated for every instance.
In our case, it makes sense to move the method f
to the prototype :
function Test(a, b) {_x000D_
this.a = a;_x000D_
this.b = b;_x000D_
}_x000D_
_x000D_
Test.prototype.f = function(c) {_x000D_
return this.a + this.b + c;_x000D_
};_x000D_
_x000D_
var test = new Test(5, 10);_x000D_
console.log(test);_x000D_
console.log(test.f(3));
_x000D_
A simple but effective way to do inheritance in JavaScript, is to use the following two-liner :
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
That is similar to doing this :
B.prototype = new A();
The main difference between both is that the constructor of A
is not run when using Object.create
, which is more intuitive and more similar to class based inheritance.
You can always choose to optionally run the constructor of A
when creating a new instance of B
by adding adding it to the constructor of B
:
function B(arg1, arg2) {
A(arg1, arg2); // This is optional
}
If you want to pass all arguments of B
to A
, you can also use Function.prototype.apply()
:
function B() {
A.apply(this, arguments); // This is optional
}
If you want to mixin another object into the constructor chain of B
, you can combine Object.create
with Object.assign
:
B.prototype = Object.assign(Object.create(A.prototype), mixin.prototype);
B.prototype.constructor = B;
function A(name) {_x000D_
this.name = name;_x000D_
}_x000D_
_x000D_
A.prototype = Object.create(Object.prototype);_x000D_
A.prototype.constructor = A;_x000D_
_x000D_
function B() {_x000D_
A.apply(this, arguments);_x000D_
this.street = "Downing Street 10";_x000D_
}_x000D_
_x000D_
B.prototype = Object.create(A.prototype);_x000D_
B.prototype.constructor = B;_x000D_
_x000D_
function mixin() {_x000D_
_x000D_
}_x000D_
_x000D_
mixin.prototype = Object.create(Object.prototype);_x000D_
mixin.prototype.constructor = mixin;_x000D_
_x000D_
mixin.prototype.getProperties = function() {_x000D_
return {_x000D_
name: this.name,_x000D_
address: this.street,_x000D_
year: this.year_x000D_
};_x000D_
};_x000D_
_x000D_
function C() {_x000D_
B.apply(this, arguments);_x000D_
this.year = "2018"_x000D_
}_x000D_
_x000D_
C.prototype = Object.assign(Object.create(B.prototype), mixin.prototype);_x000D_
C.prototype.constructor = C;_x000D_
_x000D_
var instance = new C("Frank");_x000D_
console.log(instance);_x000D_
console.log(instance.getProperties());
_x000D_
Object.create
can be safely used in every modern browser, including IE9+. Object.assign
does not work in any version of IE nor some mobile browsers. It is recommended to polyfill Object.create
and/or Object.assign
if you want to use them and support browsers that do not implement them.
You can find a polyfill for Object.create
here
and one for Object.assign
here.
You have copy this sample code from Here,right?
now, as you can see there property
file they have define, have you done same thing?
if not then add below code in your project with property file for log4j
So the content of log4j.properties file would be as follows:
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
make changes as per your requirement like log
path
Read man sshd_config
for more details, but you can use the AllowUsers
directive in /etc/ssh/sshd_config
to limit the set of users who can login.
e.g.
AllowUsers boris
would mean that only the boris
user could login via ssh.
just use '!' before the pip command in spyder terminal and it will be fine
Eg:
!pip install imutils
Though an old question, but maybe this can be helpful to someone.
I use this way of converting string to int number
var str = "25"; // string
var number = str*1; // number
So, when multiplying by 1, the value does not change, but js automatically returns a number.
But as it is shown below, this should be used if you are sure that the str
is a number(or can be represented as a number), otherwise it will return NaN - not a number.
you can create simple function to use, e.g.
function toNumber(str) {
return str*1;
}
You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href
.
/**
* ??????????????,????????
* English: Calculating the difference between the given time and the current time and then showing the results.
*/
function date2Text(date) {
var milliseconds = new Date() - date;
var timespan = new TimeSpan(milliseconds);
if (milliseconds < 0) {
return timespan.toString() + "??";
}else{
return timespan.toString() + "?";
}
}
/**
* ???????????
* English: Using a function to calculate the time interval
* @param milliseconds ???
*/
var TimeSpan = function (milliseconds) {
milliseconds = Math.abs(milliseconds);
var days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
milliseconds -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(milliseconds / (1000 * 60 * 60));
milliseconds -= hours * (1000 * 60 * 60);
var mins = Math.floor(milliseconds / (1000 * 60));
milliseconds -= mins * (1000 * 60);
var seconds = Math.floor(milliseconds / (1000));
milliseconds -= seconds * (1000);
return {
getDays: function () {
return days;
},
getHours: function () {
return hours;
},
getMinuts: function () {
return mins;
},
getSeconds: function () {
return seconds;
},
toString: function () {
var str = "";
if (days > 0 || str.length > 0) {
str += days + "?";
}
if (hours > 0 || str.length > 0) {
str += hours + "??";
}
if (mins > 0 || str.length > 0) {
str += mins + "??";
}
if (days == 0 && (seconds > 0 || str.length > 0)) {
str += seconds + "?";
}
return str;
}
}
}
You should include the repository where you want to deploy in the distribution management section of the pom.xml
.
Example:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
...
<distributionManagement>
<repository>
<uniqueVersion>false</uniqueVersion>
<id>corp1</id>
<name>Corporate Repository</name>
<url>scp://repo/maven2</url>
<layout>default</layout>
</repository>
...
</distributionManagement>
...
</project>
For logging purposes, I'm afraid there's no nicer way of doing this but to construct the string yourself:
string query = cmd.CommandText;
foreach (SqlParameter p in cmd.Parameters)
{
query = query.Replace(p.ParameterName, p.Value.ToString());
}
If you are simply trying to stop people clicking and are not horrifically worried about security - I have found an absolute placed div with a z-index of 99999 sorts it fine. You can't click or access any of the content because the div is placed over it. Might be a bit simpler and is a CSS only solution until you need to remove it.
In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date
. It is basically backed by the Epoch time in flavor of a long
, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.
In SQL side, there are several standard date and time types, DATE
, TIME
and TIMESTAMP
(at some DB's also called DATETIME
), which are represented in JDBC as java.sql.Date
, java.sql.Time
and java.sql.Timestamp
, all subclasses of java.util.Date
. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.
In contrary to java.util.Date
, the java.sql.Date
contains only information about the date part (year, month, day). The Time
contains only information about the time part (hours, minutes, seconds) and the Timestamp
contains information about the both parts, like as java.util.Date
does.
The normal practice to store a timestamp in the DB (thus, java.util.Date
in Java side and java.sql.Timestamp
in JDBC side) is to use PreparedStatement#setTimestamp()
.
java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);
The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp()
.
Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.
DEMO
In the content area you can provide whatever you want to display in it.
.black_overlay {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 0%;_x000D_
left: 0%;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: black;_x000D_
z-index: 1001;_x000D_
-moz-opacity: 0.8;_x000D_
opacity: .80;_x000D_
filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 25%;_x000D_
left: 25%;_x000D_
width: 50%;_x000D_
height: 50%;_x000D_
padding: 16px;_x000D_
border: 16px solid orange;_x000D_
background-color: white;_x000D_
z-index: 1002;_x000D_
overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
</p>_x000D_
<div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
</div>_x000D_
<div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Containment :- Here to access inner object we have to use outer object. We can reuse the contained object. Aggregation :- Here we can access inner object again and again without using outer object.
Just because I think the other answers pretty much go off on a tangent of whether a football team "is-a" List<FootballPlayer>
or "has-a" List<FootballPlayer>
, which really doesn't answer this question as written.
The OP chiefly asks for clarification on guidelines for inheriting from List<T>
:
A guideline says that you shouldn't inherit from
List<T>
. Why not?
Because List<T>
has no virtual methods. This is less of a problem in your own code, since you can usually switch out the implementation with relatively little pain - but can be a much bigger deal in a public API.
What is a public API and why should I care?
A public API is an interface you expose to 3rd party programmers. Think framework code. And recall that the guidelines being referenced are the ".NET Framework Design Guidelines" and not the ".NET Application Design Guidelines". There is a difference, and - generally speaking - public API design is a lot more strict.
If my current project does not and is not likely to ever have this public API, can I safely ignore this guideline? If I do inherit from List and it turns out I need a public API, what difficulties will I have?
Pretty much, yeah. You may want to consider the rationale behind it to see if it applies to your situation anyway, but if you're not building a public API then you don't particularly need to worry about API concerns like versioning (of which, this is a subset).
If you add a public API in the future, you will either need to abstract out your API from your implementation (by not exposing your List<T>
directly) or violate the guidelines with the possible future pain that entails.
Why does it even matter? A list is a list. What could possibly change? What could I possibly want to change?
Depends on the context, but since we're using FootballTeam
as an example - imagine that you can't add a FootballPlayer
if it would cause the team to go over the salary cap. A possible way of adding that would be something like:
class FootballTeam : List<FootballPlayer> {
override void Add(FootballPlayer player) {
if (this.Sum(p => p.Salary) + player.Salary > SALARY_CAP)) {
throw new InvalidOperationException("Would exceed salary cap!");
}
}
}
Ah...but you can't override Add
because it's not virtual
(for performance reasons).
If you're in an application (which, basically, means that you and all of your callers are compiled together) then you can now change to using IList<T>
and fix up any compile errors:
class FootballTeam : IList<FootballPlayer> {
private List<FootballPlayer> Players { get; set; }
override void Add(FootballPlayer player) {
if (this.Players.Sum(p => p.Salary) + player.Salary > SALARY_CAP)) {
throw new InvalidOperationException("Would exceed salary cap!");
}
}
/* boiler plate for rest of IList */
}
but, if you've publically exposed to a 3rd party you just made a breaking change that will cause compile and/or runtime errors.
TL;DR - the guidelines are for public APIs. For private APIs, do what you want.
Effectively what you're describing are goto statements, which are generally panned pretty heavily. Your second example is far easier to understand.
However, cleaner still would be:
if some_condition:
...
if condition_a:
your_function1()
else:
your_function2()
...
def your_function2():
if condition_b:
# do something
# and then exit the outer if block
else:
# more code here
In C# 8.0 you can get the last item with ^ operator full explanation
List<char> list = ...;
var value = list[^1];
// Gets translated to
var value = list[list.Count - 1];
This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.
This hinges on the fact that the Firebase REST API offers a shallow=true
parameter.
Assume you have a post
object and each one can have a number of comments
:
{
"posts": {
"$postKey": {
"comments": {
...
}
}
}
}
You obviously don't want to fetch all of the comments, just the number of comments.
Assuming you have the key for a post, you can send a GET
request to
https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true
.
This will return an object of key-value pairs, where each key is the key of a comment and its value is true
:
{
"comment1key": true,
"comment2key": true,
...,
"comment9999key": true
}
The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length
).
This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.
Another approach is to use inplace editing inside Ruby (not from the command line):
#!/usr/bin/ruby
def inplace_edit(file, bak, &block)
old_stdout = $stdout
argf = ARGF.clone
argf.argv.replace [file]
argf.inplace_mode = bak
argf.each_line do |line|
yield line
end
argf.close
$stdout = old_stdout
end
inplace_edit 'test.txt', '.bak' do |line|
line = line.gsub(/search1/,"replace1")
line = line.gsub(/search2/,"replace2")
print line unless line.match(/something/)
end
If you don't want to create a backup then change '.bak'
to ''
.
Here is another way to reproduce this error in Python2.7 with numpy:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate(a,b) #note the lack of tuple format for a and b
print(c)
The np.concatenate
method produces an error:
TypeError: only length-1 arrays can be converted to Python scalars
If you read the documentation around numpy.concatenate, then you see it expects a tuple of numpy array objects. So surrounding the variables with parens fixed it:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate((a,b)) #surround a and b with parens, packaging them as a tuple
print(c)
Then it prints:
[1 2 3 4 5 6]
What's going on here?
That error is a case of bubble-up implementation - it is caused by duck-typing philosophy of python. This is a cryptic low-level error python guts puke up when it receives some unexpected variable types, tries to run off and do something, gets part way through, the pukes, attempts remedial action, fails, then tells you that "you can't reformulate the subspace responders when the wind blows from the east on Tuesday".
In more sensible languages like C++ or Java, it would have told you: "you can't use a TypeA where TypeB was expected". But Python does it's best to soldier on, does something undefined, fails, and then hands you back an unhelpful error. The fact we have to be discussing this is one of the reasons I don't like Python, or its duck-typing philosophy.
For windows you can use:
Running Windows command prompt commands in python.
import os
os.system('tzutil /s "Central Standard Time"')
In windows command prompt try:
This gives current timezone:
tzutil /g
This gives a list of timezones:
tzutil /l
This will set the timezone:
tzutil /s "Central America Standard Time"
For further reference: http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/
To delete all objects in a list, you can directly write list = []
Here is example:
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a = []
>>> a
[]
'Use Chrome, invite troubles' - Anonymous. (Just a symbolic reference)
Well, Chrome is notoriously famous for a lot of default security-enabled utilities, and that's where your problem originates from.
This can, however, be undone by 'setting the default email client' (as the default email client is unset), or by setting up the default handler under 'chrome://settings/handlers' (by default, it's set to 'Ignore').
One thing that should be considered is licensing.
Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.
To quote the Sublime Text 2 website:
..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.
The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.
Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.
This licensing requirement is still correct as of Dec 2019.
Install the plugin-proposal-class-properties
npm install @babel/plugin-proposal-class-properties --save-dev
Update your webpack.config.js by adding
'plugins': ['@babel/plugin-proposal-class-properties']}]
Add extra columns as null for the table having less columns like
Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2
Your and
should be a &&
in the where
clause.
where epl.DepartAirportAfter > sd.UTCDepartureTime
and epl.ArriveAirportBy > sd.UTCArrivalTime
should be
where epl.DepartAirportAfter > sd.UTCDepartureTime
&& epl.ArriveAirportBy > sd.UTCArrivalTime
Just had the same error message, but when I was running a package.json with:
"scripts": {
"build": "tsc -p ./src",
}
tsc
is the command to run the TypeScript compiler.
I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install
didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev
) to solve the problem.
You could do it like:
Person.where("name = ? OR age = ?", 'Pearl', 24)
or more elegant, install rails_or gem and do it like:
Person.where(:name => 'Pearl').or(:age => 24)
I figured out an elegant, Rails-like way to do it. First, rename your .scss
file to .scss.erb
, then use syntax like this (example for highlight_js-rails4 gem CSS asset):
@import "<%= asset_path("highlight_js/github") %>";
Why you can't host the file directly via SCSS:
Doing an @import
in SCSS works fine for CSS files as long as you explicitly use the full path one way or another. In development mode, rails s
serves assets without compiling them, so a path like this works...
@import "highlight_js/github.css";
...because the hosted path is literally /assets/highlight_js/github.css
. If you right-click on the page and "view source", then click on the link for the stylesheet with the above @import
, you'll see a line in there that looks like:
@import url(highlight_js/github.css);
The SCSS engine translates "highlight_js/github.css"
to url(highlight_js/github.css)
. This will work swimmingly until you decide to try running it in production where assets are precompiled have a hash injected into the file name. The SCSS file will still resolve to a static /assets/highlight_js/github.css
that was not precompiled and doesn't exist in production.
How this solution works:
Firstly, by moving the .scss
file to .scss.erb
, we have effectively turned the SCSS into a template for Rails. Now, whenever we use <%= ... %>
template tags, the Rails template processor will replace these snippets with the output of the code (just like any other template).
Stating asset_path("highlight_js/github")
in the .scss.erb
file does two things:
rake assets:precompile
task to precompile the appropriate CSS file.This also means that the SCSS engine isn't even parsing the CSS file; it's just hosting a link to it! So there's no hokey monkey patches or gross workarounds. We're serving a CSS asset via SCSS as intended, and using a URL to said CSS asset as Rails intended. Sweet!
The context parameter just sets the value of this
in the iterator function.
var someOtherArray = ["name","patrick","d","w"];
_.each([1, 2, 3], function(num) {
// In here, "this" refers to the same Array as "someOtherArray"
alert( this[num] ); // num is the value from the array being iterated
// so this[num] gets the item at the "num" index of
// someOtherArray.
}, someOtherArray);
Working Example: http://jsfiddle.net/a6Rx4/
It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray
, which is represented by this
since we passed it as the context parameter.
If you do not set the context, then this
will refer to the window
object.
It is easy to write text to a canvas. Lets say that you canvas is declared like below.
<html>
<canvas id="YourCanvas" width="500" height="500">
Your Internet Browser does not support HTML5 (Get a new Browser)
</canvas>
</html>
This part of the code returns a variable into canvas which is a representation of your canvas in HTML.
var c = document.getElementById("YourCanvas");
The following code returns the methods for drawing lines, text, fills to your canvas.
var ctx = canvas.getContext("2d");
<script>
ctx.font="20px Times Roman";
ctx.fillText("Hello World!",50,100);
ctx.font="30px Verdana";
var g = ctx.createLinearGradient(0,0,c.width,0);
g.addColorStop("0","magenta");
g.addColorStop("0.3","blue");
g.addColorStop("1.0","red");
ctx.fillStyle=g; //Sets the fille of your text here. In this case it is set to the gradient that was created above. But you could set it to Red, Green, Blue or whatever.
ctx.fillText("This is some new and funny TEXT!",40,190);
</script>
There is a beginners guide out on Amazon for the kindle http://www.amazon.com/HTML5-Canvas-Guide-Beginners-ebook/dp/B00JSFVY9O/ref=sr_1_4?ie=UTF8&qid=1398113376&sr=8-4&keywords=html5+canvas+beginners that is well worth the money. I purchased it a couple of days ago and it showed me a lot of simple techniques that were very useful.
I would suggest using following
req.param('<param_name>')
req.param("") works as following
Lookup is performed in the following order:
req.params
req.body
req.query
Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.
If eclipse (none of them) doesn't launch at all and there's not even an error message, uninstall Java 8 Updater and reinstall Java 8 from scratch, this should work. Have luck!
If UAC is enabled on the computer, something like this should work:
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
WScript.Quit
End If
'actual code
there are 2 solutions:
visit this jsfiddle
in your css you can add this:
.input-disabled{background-color:#EBEBE4;border:1px solid #ABADB3;padding:2px 1px;}
in your js do something like this:
$('#test').attr('readonly', true);
$('#test').addClass('input-disabled');
Hope this help.
Another way is using hidden input field as mentioned by some of the comments. However bear in mind that, in the backend code, you need to make sure you validate this newly hidden input at correct scenario. Hence I'm not recommend this way as it will create more bugs if its not handle properly.
You should use event.target.value
prop with onChange handler if not you could see :
index.js:1437 Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.
Or If you want to use other handler than onChange, use event.currentTarget.value
NOTE: This is true for the version mentioned in the question, 4.1.1.RELEASE.
Spring MVC handles a ResponseEntity
return value through HttpEntityMethodProcessor
.
When the ResponseEntity
value doesn't have a body set, as is the case in your snippet, HttpEntityMethodProcessor
tries to determine a content type for the response body from the parameterization of the ResponseEntity
return type in the signature of the @RequestMapping
handler method.
So for
public ResponseEntity<Void> taxonomyPackageExists( @PathVariable final String key ) {
that type will be Void
. HttpEntityMethodProcessor
will then loop through all its registered HttpMessageConverter
instances and find one that can write a body for a Void
type. Depending on your configuration, it may or may not find any.
If it does find any, it still needs to make sure that the corresponding body will be written with a Content-Type that matches the type(s) provided in the request's Accept
header, application/xml
in your case.
If after all these checks, no such HttpMessageConverter
exists, Spring MVC will decide that it cannot produce an acceptable response and therefore return a 406 Not Acceptable HTTP response.
With ResponseEntity<String>
, Spring will use String
as the response body and find StringHttpMessageConverter
as a handler. And since StringHttpMessageHandler
can produce content for any media type (provided in the Accept
header), it will be able to handle the application/xml
that your client is requesting.
Spring MVC has since been changed to only return 406 if the body in the ResponseEntity
is NOT null
. You won't see the behavior in the original question if you're using a more recent version of Spring MVC.
In iddy85's solution, which seems to suggest ResponseEntity<?>
, the type for the body will be inferred as Object
. If you have the correct libraries in your classpath, ie. Jackson (version > 2.5.0) and its XML extension, Spring MVC will have access to MappingJackson2XmlHttpMessageConverter
which it can use to produce application/xml
for the type Object
. Their solution only works under these conditions. Otherwise, it will fail for the same reason I've described above.
Add jQuery and make sure only one link for jQuery cause more than one doesn't work...
Swift 3.
Call this function to get the topmost view controller, then have that view controller present.
func topMostController() -> UIViewController {
var topController: UIViewController = UIApplication.shared.keyWindow!.rootViewController!
while (topController.presentedViewController != nil) {
topController = topController.presentedViewController!
}
return topController
}
Usage:
let topVC = topMostController()
let vcToPresent = self.storyboard!.instantiateViewController(withIdentifier: "YourVCStoryboardID") as! YourViewController
topVC.present(vcToPresent, animated: true, completion: nil)
I kept having problems with this, the only solution was to add an image and label as subviews to the uibutton. Then I discovered that the main problem was that I was using a UIButton with title: Attributed. When I changed it to Plain, just setting the titleLabel.text did the trick!
When I get this kind of error I had to update the data type by a notch. For Example, if I have it as "tiny int" change it to "small int" ~ Nita
I tried some of the other answers, and none of them worked quite how I wanted them to. Our situation was very similar where we had a window header and the window was resizable with images in the window body. We wanted to lock the aspect ratio of the resizing without needing to add in calculations to account for the fixed size of the header and still have the image fill the window body.
Below I created a very simple snippet that shows what we ended up doing that seems to work well for our situation and should be compatible across most browsers.
On our window element we added a 20px margin which contributes to positioning relative to other elements on the screen, but does not contribute to the "size" of the window. The window-header is then positioned absolutely (which removes it from the flow of other elements, so it won't cause other elements like the unordered list to be shifted) and its top is positioned -20px which places the header inside of the margin of the window. Finally our ul element is added to the window, and the height can be set to 100% which will cause it to fill the window's body (excluding the margin).
*,*:before,*:after_x000D_
{_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.window_x000D_
{_x000D_
position: relative;_x000D_
top: 20px;_x000D_
left: 50px;_x000D_
margin-top: 20px;_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
}_x000D_
_x000D_
.window-header_x000D_
{_x000D_
position: absolute;_x000D_
top: -20px;_x000D_
height: 20px;_x000D_
border: 2px solid black;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
ul_x000D_
{_x000D_
border: 5px dashed gray;_x000D_
height: 100%;_x000D_
}
_x000D_
<div class="window">_x000D_
<div class="window-header">Hey this is a header</div>_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 2</li>_x000D_
<li>Item 3</li>_x000D_
<li>Item 4</li>_x000D_
<li>Item 5</li>_x000D_
</ul>_x000D_
</div>
_x000D_
After converting your varchar2
date to a true date
datatype, then convert back to varchar2
with the desired mask:
to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW')
If you want the week number in a number
datatype, you can wrap the statement in to_number()
:
to_number(to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW'))
However, you have several week number options to consider:
WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
If you are using SQL Server (starting with vNext) or Azure SQL Database then you can use the below query.
SELECT TRIM(ColumnName) from TableName;
For other SQL SERVER Database you can use the below query.
SELECT LTRIM(RTRIM(ColumnName)) from TableName
LTRIM - Removes spaces from the left
example: select LTRIM(' test ') as trim
= 'test '
RTRIM - Removes spaces from the right
example: select RTRIM(' test ') as trim
= ' test'
I ran into this myself. My recommendation: If you have ownership of the datasource, don't use a List. Use a BindingList. The BindingList has events that fire when items are added or changed, and the DataGridView will automatically update itself when these events are fired.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
Another possible explanation is that you're building against x86. Right-click your Solution and choose Configuration Manager. See if you're building against x86 instead of Any CPU.
It sounds like your service was built against 'Any CPU', causing you errors on 64-bit where you are using COM components. You need to build it for x86
.
The website is probably running as a 32-bit process which is why it can use the component. Building your solution against x86
will force your service to run as 32-bit.
If you want to compare to a string literal you need to put it in (single) quotes:
<xsl:if test="Count != 'N/A'">
try using concatenation of string
Statistics(string date)
{
this->date += date;
}
acually this was a part of a class..
If you don't feel like using Math.Abs * -1 you can you this simple if statement :P
if (x > 0) {
x = -x;
}
Of course you could make this a function like this
function makeNegative(number) {
if (number > 0) {
number = -number;
}
}
makeNegative(-3) => -3 makeNegative(5) => -5
Hope this helps! Math.abs will likely work for you but if it doesn't this little
Because $xml->xpath
always return an array, and strlen
expects a string.
In my experience it may be the result of auto-generation by a string-based tools, where the author did not understand the rules of HTML.
When some developers generate HTML without the use of special XML-oriented tools, they may try to be sure the resulting HTML is valid by taking the approach that everything must be escaped.
Referring to your example, the reason why every occurrence of "
is represented by "
could be because using that approach, you can safely use such "special" characters in both attributes and values.
Another motivation I've seen is where people believe, "We must explicitly show that our symbols are not part of the syntax." Whereas, valid HTML can be created by using the proper string-manipulation tools, see the previous paragraph again.
Here is some pseudo-code loosely based on C#, although it is preferred to use valid methods and tools:
public class HtmlAndXmlWriter
{
private string Escape(string badString)
{
return badString.Replace("&", "&").Replace("\"", """).Replace("'", "'").Replace(">", ">").Replace("<", "<");
}
public string GetHtmlFromOutObject(Object obj)
{
return "<div class='type_" + Escape(obj.Type) + "'>" + Escape(obj.Value) + "</div>";
}
}
It's really very common to see such approaches taken to generate HTML.
No.
Either use verbatim string literals as you have, or escape the "
using backslash.
string test = "He said to me, \"Hello World\" . How are you?";
The string has not changed in either case - there is a single escaped "
in it. This is just a way to tell C# that the character is part of the string and not a string terminator.
preg_replace('#[^\w()/.%\-&]#',"",$string);
This should work:
$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`
Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:
<script type="text/javascript"> $(function() { //jQuery trick to say after all the HTML is parsed. $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); }); </script>
EDIT: This code works for me
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <strong>Choose a base package:</strong> <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942 <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313 <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829 <strong>Choose an add on:</strong> <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0 <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146) <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455) <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764) <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073) <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382) <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691) <strong>Your total is:</strong> <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); </script> </body> </html>
some resources:
ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:
arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]
or using fromELF utility(built in most IDEs such as ADS though):
fromelf -bin -o [binary-output-file] [elf-input-file]
Here is what is going on.
First, the only global variables Python really has are module-scoped variables. You cannot make a variable that is truly global; all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.)
All you have to do to make a module-global variable is just assign to a name.
Imagine a file called foo.py, containing this single line:
X = 1
Now imagine you import it.
import foo
print(foo.X) # prints 1
However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Python's default is to assume that function variables are local. You simply add a global
declaration in your function, before you try to use the global.
def initDB(name):
global __DBNAME__ # add this line!
if __DBNAME__ is None: # see notes below; explicit test for None
__DBNAME__ = name
else:
raise RuntimeError("Database name has already been set.")
By the way, for this example, the simple if not __DBNAME__
test is adequate, because any string value other than an empty string will evaluate true, so any actual database name will evaluate true. But for variables that might contain a number value that might be 0, you can't just say if not variablename
; in that case, you should explicitly test for None
using the is
operator. I modified the example to add an explicit None
test. The explicit test for None
is never wrong, so I default to using it.
Finally, as others have noted on this page, two leading underscores signals to Python that you want the variable to be "private" to the module. If you ever do an import * from mymodule
, Python will not import names with two leading underscores into your name space. But if you just do a simple import mymodule
and then say dir(mymodule)
you will see the "private" variables in the list, and if you explicitly refer to mymodule.__DBNAME__
Python won't care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you don't want them rebinding that name to some value of their own.
It is considered best practice in Python not to do import *
, but to minimize the coupling and maximize explicitness by either using mymodule.something
or by explicitly doing an import like from mymodule import something
.
EDIT: If, for some reason, you need to do something like this in a very old version of Python that doesn't have the global
keyword, there is an easy workaround. Instead of setting a module global variable directly, use a mutable type at the module global level, and store your values inside it.
In your functions, the global variable name will be read-only; you won't be able to rebind the actual global variable name. (If you assign to that variable name inside your function it will only affect the local variable name inside the function.) But you can use that local variable name to access the actual global object, and store data inside it.
You can use a list
but your code will be ugly:
__DBNAME__ = [None] # use length-1 list as a mutable
# later, in code:
if __DBNAME__[0] is None:
__DBNAME__[0] = name
A dict
is better. But the most convenient is a class instance, and you can just use a trivial class:
class Box:
pass
__m = Box() # m will contain all module-level values
__m.dbname = None # database name global in module
# later, in code:
if __m.dbname is None:
__m.dbname = name
(You don't really need to capitalize the database name variable.)
I like the syntactic sugar of just using __m.dbname
rather than __m["DBNAME"]
; it seems the most convenient solution in my opinion. But the dict
solution works fine also.
With a dict
you can use any hashable value as a key, but when you are happy with names that are valid identifiers, you can use a trivial class like Box
in the above.
For editing use
vi galfit.feedme //if user has file editing permissions
or
sudo vi galfit.feedme //if user doesn't have file editing permissions
For inserting
Press i //Do required editing
For exiting
Press Esc
:wq //for exiting and saving
:q! //for exiting without saving
For checking type conversions in version 3, you can go to their github and check into the different liquibase types and check the method toDatabaseDataType. For example, for Boolean, you can check here:
For version 2.0.x, the conversion seems to be into database specific classes. For example, for Mysql:
There is also a vectorized implementation, which allows to use 4 numpy arrays instead of scalar values for coordinates:
def distance(s_lat, s_lng, e_lat, e_lng):
# approximate radius of earth in km
R = 6373.0
s_lat = s_lat*np.pi/180.0
s_lng = np.deg2rad(s_lng)
e_lat = np.deg2rad(e_lat)
e_lng = np.deg2rad(e_lng)
d = np.sin((e_lat - s_lat)/2)**2 + np.cos(s_lat)*np.cos(e_lat) * np.sin((e_lng - s_lng)/2)**2
return 2 * R * np.arcsin(np.sqrt(d))
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
Here's the way to extend to variable args when you don't have the args hard coded (although they are still technically hard coded in this example, but should be easy to figure out how to extend...):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int argcount = 3;
const char* args[] = {"1", "2", "3"};
const char* binary_name = "mybinaryname";
char myoutput_array[5000];
sprintf(myoutput_array, "%s", binary_name);
for(int i = 0; i < argcount; ++i)
{
strcat(myoutput_array, " ");
strcat(myoutput_array, args[i]);
}
system(myoutput_array);
I had similar issue, this is how it was solved
xyz@ip :~/formsProject_SVN$ svn resolved formsProj/templates/search
Resolved conflicted state of 'formsProj/templates/search'
Now update your project
xyz@ip:~/formsProject_SVN$ svn update
Updating '.':
Select: (mc) keep affected local moves, (r) mark resolved (breaks moves), (p) postpone, (q) quit resolution, (h) help: r (select "r" option to resolve)
Resolved conflicted state of 'formsProj/templates/search'
Summary of conflicts: Tree conflicts: 0 remaining (and 1 already resolved)
[print(a) for a in list]
will give a bunch of None types at the end though it prints out all the items
This is already implemented in the runtime libs.
public static String calc(InputStream is) {
String output;
int read;
byte[] buffer = new byte[8192];
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] hash = digest.digest();
BigInteger bigInt = new BigInteger(1, hash);
output = bigInt.toString(16);
while ( output.length() < 32 ) {
output = "0"+output;
}
}
catch (Exception e) {
e.printStackTrace(System.err);
return null;
}
return output;
}
In a JEE6+ environment one could also use JAXB DataTypeConverter:
import javax.xml.bind.DatatypeConverter;
String hash = DatatypeConverter.printHexBinary(
MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
You can also use as many classes as needed on a tag, but an id must be unique to the document. Also be careful of using too many divs, when another more semantic tag can do the job.
<p id="unique" class="x y z">Styled paragraph</p>
Another cause for this might be case-insensitive file systems. If you have multiple folders in your repo on the same level whose names only differ by case, you will get hit by this. Browse the source repository using its web interface (e.g. GitHub or VSTS) to make sure.
For more information: https://stackoverflow.com/a/2016426/67824
The <<
part is wrong, use <
instead:
$ ./manage.py shell < myscript.py
You could also do:
$ ./manage.py shell
...
>>> execfile('myscript.py')
For python3 you would need to use
>>> exec(open('myscript.py').read())
Just change the application id in build.gradle
applicationId "yourpackageName"
For changing application label, in manifest
<application
android:label="@string/app_name"
... />
No, there isn't any.
The list of comparison operators are listed here.
For your requirement the best option would be regular expressions.
An rvalue reference is a type that behaves much like the ordinary reference X&, with several exceptions. The most important one is that when it comes to function overload resolution, lvalues prefer old-style lvalue references, whereas rvalues prefer the new rvalue references:
void foo(X& x); // lvalue reference overload
void foo(X&& x); // rvalue reference overload
X x;
X foobar();
foo(x); // argument is lvalue: calls foo(X&)
foo(foobar()); // argument is rvalue: calls foo(X&&)
So what is an rvalue? Anything that is not an lvalue. An lvalue being an expression that refers to a memory location and allows us to take the address of that memory location via the & operator.
It is almost easier to understand first what rvalues accomplish with an example:
#include <cstring>
class Sample {
int *ptr; // large block of memory
int size;
public:
Sample(int sz=0) : ptr{sz != 0 ? new int[sz] : nullptr}, size{sz}
{
if (ptr != nullptr) memset(ptr, 0, sz);
}
// copy constructor that takes lvalue
Sample(const Sample& s) : ptr{s.size != 0 ? new int[s.size] :\
nullptr}, size{s.size}
{
if (ptr != nullptr) memcpy(ptr, s.ptr, s.size);
std::cout << "copy constructor called on lvalue\n";
}
// move constructor that take rvalue
Sample(Sample&& s)
{ // steal s's resources
ptr = s.ptr;
size = s.size;
s.ptr = nullptr; // destructive write
s.size = 0;
cout << "Move constructor called on rvalue." << std::endl;
}
// normal copy assignment operator taking lvalue
Sample& operator=(const Sample& s)
{
if(this != &s) {
delete [] ptr; // free current pointer
size = s.size;
if (size != 0) {
ptr = new int[s.size];
memcpy(ptr, s.ptr, s.size);
} else
ptr = nullptr;
}
cout << "Copy Assignment called on lvalue." << std::endl;
return *this;
}
// overloaded move assignment operator taking rvalue
Sample& operator=(Sample&& lhs)
{
if(this != &s) {
delete [] ptr; //don't let ptr be orphaned
ptr = lhs.ptr; //but now "steal" lhs, don't clone it.
size = lhs.size;
lhs.ptr = nullptr; // lhs's new "stolen" state
lhs.size = 0;
}
cout << "Move Assignment called on rvalue" << std::endl;
return *this;
}
//...snip
};
The constructor and assignment operators have been overloaded with versions that take rvalue references. Rvalue references allow a function to branch at compile time (via overload resolution) on the condition "Am I being called on an lvalue or an rvalue?". This allowed us to create more efficient constructor and assignment operators above that move resources rather copy them.
The compiler automatically branches at compile time (depending on the whether it is being invoked for an lvalue or an rvalue) choosing whether the move constructor or move assignment operator should be called.
Summing up: rvalue references allow move semantics (and perfect forwarding, discussed in the article link below).
One practical easy-to-understand example is the class template std::unique_ptr. Since a unique_ptr maintains exclusive ownership of its underlying raw pointer, unique_ptr's can't be copied. That would violate their invariant of exclusive ownership. So they do not have copy constructors. But they do have move constructors:
template<class T> class unique_ptr {
//...snip
unique_ptr(unique_ptr&& __u) noexcept; // move constructor
};
std::unique_ptr<int[] pt1{new int[10]};
std::unique_ptr<int[]> ptr2{ptr1};// compile error: no copy ctor.
// So we must first cast ptr1 to an rvalue
std::unique_ptr<int[]> ptr2{std::move(ptr1)};
std::unique_ptr<int[]> TakeOwnershipAndAlter(std::unique_ptr<int[]> param,\
int size)
{
for (auto i = 0; i < size; ++i) {
param[i] += 10;
}
return param; // implicitly calls unique_ptr(unique_ptr&&)
}
// Now use function
unique_ptr<int[]> ptr{new int[10]};
// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(\
static_cast<unique_ptr<int[]>&&>(ptr), 10);
cout << "output:\n";
for(auto i = 0; i< 10; ++i) {
cout << new_owner[i] << ", ";
}
output:
10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
static_cast<unique_ptr<int[]>&&>(ptr)
is usually done using std::move
// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(std::move(ptr),0);
An excellent article explaining all this and more (like how rvalues allow perfect forwarding and what that means) with lots of good examples is Thomas Becker's C++ Rvalue References Explained. This post relied heavily on his article.
A shorter introduction is A Brief Introduction to Rvalue References by Stroutrup, et. al
To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:
In child add:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
In parent add:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
Use IsNull
SELECT recordid, MIN(startdate), MAX(IsNull(enddate, Getdate()))
FROM tmp
GROUP BY recordid
I've modified MIN in the second instruction to MAX
I am using Visual Studio 2013 and I have the same issue but it occurs when I try to open a solution that was made using Visual Studio 2010.
The solution for me is to open the solution file (.sln), using notepad and change this line:
[# Visual Studio 2010]
to this:
[# Visual Studio 2013]
If you are on Windows, use ipconfig to get the local IPv4 address, and then specify that under your Apache configuration file: httpd.conf, like:
Listen: 10.20.30.40:80
Restart your Apache server and test it from other computer on the network.
Check out the apache config files. For Debian/Ubuntu theyre in /etc/apache2/sites-available/
for RedHat/CentOS/etc they're in /etc/httpd/conf.d/
. If you've just installed it, the file in there is probably named default
.
Make sure that the config file in there is pointing to the correct folder and then make sure your scripts are located there.
The line you're looking for in those files is DocumentRoot /path/to/directory
.
For a blank install, your php files most likely needs to be in /var/www/
.
What you'll also need to do is find your php.ini file, probably located at /etc/php5/apache2/php.ini
or /etc/php.ini
and find the entry for display_errors
and switch it to On
.
To add a very important note on what Mark S. has mentioned in his post. In the specific SQL Script that has been mentioned in the question you can NEVER mention two different file groups for storing your data rows and the index data structure.
The reason why is due to the fact that the index being created in this case is a clustered Index on your primary key column. The clustered index data and the data rows of your table can NEVER be on different file groups.
So in case you have two file groups on your database e.g. PRIMARY and SECONDARY then below mentioned script will store your row data and clustered index data both on PRIMARY file group itself even though I've mentioned a different file group ([SECONDARY]
) for the table data. More interestingly the script runs successfully as well (when I was expecting it to give an error as I had given two different file groups :P). SQL Server does the trick behind the scene silently and smartly.
CREATE TABLE [dbo].[be_Categories](
[CategoryID] [uniqueidentifier] ROWGUIDCOL NOT NULL CONSTRAINT [DF_be_Categories_CategoryID] DEFAULT (newid()),
[CategoryName] [nvarchar](50) NULL,
[Description] [nvarchar](200) NULL,
[ParentID] [uniqueidentifier] NULL,
CONSTRAINT [PK_be_Categories] PRIMARY KEY CLUSTERED
(
[CategoryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [SECONDARY]
GO
NOTE: Your index can reside on a different file group ONLY if the index being created is non-clustered in nature.
The below script which creates a non-clustered index will get created on [SECONDARY]
file group instead when the table data already resides on [PRIMARY]
file group:
CREATE NONCLUSTERED INDEX [IX_Categories] ON [dbo].[be_Categories]
(
[CategoryName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Secondary]
GO
You can get more information on how storing non-clustered indexes on a different file group can help your queries perform better. Here is one such link.
Enumerable.First
returns the element instead of an index. In both cases you will get an exception if no matching element appears in the list (your original code will throw an IndexOutOfBoundsException
when you try to get the item at index -1, but First
will throw an InvalidOperationException
).
MyList.First(item => string.Equals("foo", item.name)).value
There is no need to use angular http, you can get with js native functions
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
// on the first then you will return blob from response_x000D_
return await fetch(url).then(r => r.blob())_x000D_
.then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
_x000D_
return new File([blob], fileName+'.'+ blob.type.split('/')[1]) ;_x000D_
});_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
// with file reader you will transform the file in a data url file;_x000D_
var reader = new FileReader();_x000D_
reader.readAsDataURL(file);_x000D_
reader.onloadend = () => {_x000D_
_x000D_
// just putting the data url to img element_x000D_
document.querySelector('#image').src = reader.result ;_x000D_
}_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
Check this query, i created this query to check whether the check in date over lap with any reservation dates
SELECT * FROM tbl_ReservedRooms
WHERE NOT ('@checkindate' NOT BETWEEN fromdate AND todate
AND '@checkoutdate' NOT BETWEEN fromdate AND todate)
this will retrun the details which are overlaping , to get the not overlaping details then remove the 'NOT' from the query
'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'. For example, If an integer uses 32 bits, it has up to 10 decimal digits. So your code should look like:
int i;
char s[11];
...
sprintf(s,"%ld", i);
If you just want to add a string to it, the simple answer is:
ListBox.Items.Add("some text");
if location == a2:
img = Image.open("picture.jpg")
Img.show
Make sure the name of the image is in parantheses this should work
In the mixins of the Bootstrap sources Sass files, remove all $border
references (not in the outline variant).
@mixin button-variant($color, $background, $border){
$active-background: darken($background, 10%);
//$active-border: darken($border, 12%);
color: $color;
background-color: $background;
//border-color: $border;
@include box-shadow($btn-box-shadow);
[...]
}
Or simply code you own _customButton.scss mixin.
Try something like the following if you want to use pure JavaScript:
document.getElementsByName('link')[0].placeholder='Type here to search';
I had similar issue when I had plenty of extra records in csv file with empty values. If I open csv file in notepad then empty lines looks like this: ,,,, ,,,, ,,,, ,,,,
You can not see those if open in Excel. Please check in Notepad and delete those records
Slot free in NPOI excel indexedcolors from 57+
Color selColor;
var wb = new HSSFWorkbook();
var sheet = wb.CreateSheet("NPOI");
var style = wb.CreateCellStyle();
var font = wb.CreateFont();
var palette = wb.GetCustomPalette();
short indexColor = 57;
palette.SetColorAtIndex(indexColor, (byte)selColor.R, (byte)selColor.G, (byte)selColor.B);
font.Color = palette.GetColor(indexColor).Indexed;
Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.
As a beginner in SQL I find that when using a BEGIN
and END
SSMS usually adds a squiggly line with incorrect syntax near 'END'
to END, simply because there's no content in between yet. If you're just setting up BEGIN
and END
to get started and add the actual query later, then simply add a bogus PRINT
statement so SSMS stops bothering you.
For example:
IF (1=1)
BEGIN
PRINT 'BOGUS'
END
The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:
IF (1=1)
BEGIN
END
#bold{_x000D_
font-weight: bold;_x000D_
}_x000D_
#custom{_x000D_
font-weight: 200;_x000D_
}
_x000D_
<body>_x000D_
<p id="bold"> here is a bold text using css </p>_x000D_
<p id="custom"> here is a custom bold text using css </p>_x000D_
</body>
_x000D_
I hope it's worked
I would use
like 'Express Edition%'
Example:
DECLARE @edition varchar(50);
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)
DECLARE @isExpress bit
if @edition like 'Express Edition%'
set @isExpress = 1;
else
set @isExpress = 0;
print @isExpress
I solve this problem by always using the [h]
option on floats (such as figures) so that they (mostly) go where I place them. Then when I look at the final draft, I adjust the location of the float by moving it in the LaTeX source. Usually that means moving it around the paragraph where it is referenced. Sometimes I need to add a page break at an appropriate spot.
I've found that the default placement of floats is reasonable in LaTeX, but manual adjustments are almost always needed to get things like this just right. (And sometimes it isn't possible for everything to be perfect when there are lots of floats and footnotes.)
The manual for the memoir
class has some good information about how LaTeX places floats and some advice for manipulating the algorithm.
There are at least two ways to do it:
Use nowrap attribute inside the "td" tag:
<th nowrap="nowrap">Really long column heading</th>
Use non-breakable spaces between your words:
<th>Really long column heading</th>
Just making simple to understand for beginners.
Check your git stash list with below command :
git stash list
And then apply with below command:
git stash apply stash@{n}
For example: I am applying my latest stash(latest is always index {0} on top of the stash list).
git stash apply stash@{0}
Here is the shortest solution (One Liner) ES6:
Math.max(...values.map(o => o.y));
Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import
to Tkinter
rather than tkinter
(the difference being the capitalization):
import tkinter as tk
#import Tkinter as tk # for python 2
def create_window():
window = tk.Toplevel(root)
root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()
root.mainloop()
This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.
You don't really need the directive, can achieve it by using the ng-init and ng-checked. below demo link shows how to set the initial value for checkbox in angularjs.
<form>
<div>
Released<input type="checkbox" ng-model="Released" ng-bind-html="ACR.Released" ng-true-value="true" ng-false-value="false" ng-init='Released=true' ng-checked='true' />
Inactivated<input type="checkbox" ng-model="Inactivated" ng-bind-html="Inactivated" ng-true-value="true" ng-false-value="false" ng-init='Inactivated=false' ng-checked='false' />
Title Changed<input type="checkbox" ng-model="Title" ng-bind-html="Title" ng-true-value="true" ng-false-value="false" ng-init='Title=false' ng-checked='false' />
</div>
<br/>
<div>Released value is <b>{{Released}}</b></div>
<br/>
<div>Inactivated value is <b>{{Inactivated}}</b></div>
<br/>
<div>Title value is <b>{{Title}}</b></div>
<br/>
</form>
// Code goes here
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
});
this is my answer. $ cat file > copy_file
Just add data-html="true"
<a href="#" title="Some long text <br/> Second line text \n Third line text" data-html="true">Hover me</a>
Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.
I have tested the suggested solutions, they should all work:
select * from dual where (105 = to_number('105'))
=> delivers one dummy row
select * from dual where (10 = to_number('105'))
=> empty result
select * from dual where ('105' = to_char(105))
=> delivers one dummy row
select * from dual where ('105' = to_char(10))
=> empty result
In Java there is no good reason.
A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:
if (o = null)
will not compile.
The only time this could matter in Java is if the variable is boolean:
int m1(boolean x)
{
if (x = true) // oops, assignment instead of equality
I would suggest not to use seaborn pointplot
for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date
. This allows to set labels to the plots and have them automatically put into a legend with ax.legend()
.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})
f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'
ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")
ax.legend()
plt.gcf().autofmt_xdate()
plt.show()
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')
ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])
ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()
plt.show()
if you have a fixed height footer (for example 712px) you can do this with js like so:
var bgTop = 0;
window.addEventListener("resize",theResize);
function theResize(){
bgTop = winHeight - 712;
document.getElementById("bg").style.marginTop = bgTop+"px";
}
Edit: Jakub Narebski has more git-fu. The following much simpler command works perfectly:
git describe --tags
(Or without the --tags
if you have checked out an annotated tag. My tag is lightweight, so I need the --tags.)
original answer follows:
git describe --exact-match --tags $(git log -n1 --pretty='%h')
Someone with more git-fu may have a more elegant solution...
This leverages the fact that git-log
reports the log starting from what you've checked out. %h
prints the abbreviated hash. Then git describe --exact-match --tags
finds the tag (lightweight or annotated) that exactly matches that commit.
The $()
syntax above assumes you're using bash or similar.
<head>
tags in a HTML page.A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.
.ico
image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
to the <head>
element.Thanks to the efforts of Vincent and work by Joey Hayes, I have this codepen working on android mobile that supports multiple fixed backgrounds
HTML:
<html>
<body>
<nav>Nav to nowhere</nav>
<article>
<section class="bg-img bg-img1">
<div class="content">
<h1>Fixed backgrounds on a mobile browser</h1>
</div>
</section>
<section class="solid">
<h3>Scrolling Foreground Here</h3>
</section>
<section>
<div class="content">
<p>Quid securi etiam tamquam eu fugiat nulla pariatur. Cum ceteris in veneratione tui montes, nascetur mus. Quisque placerat facilisis egestas cillum dolore. Ambitioni dedisse scripsisse iudicaretur. Quisque ut dolor gravida, placerat libero vel,
euismod.
</p>
</div>
</section>
<section class="solid">
<h3>Scrolling Foreground Here</h3>
</section>
<section class="footer">
<div class="content">
<h3>The end is nigh.</h3>
</div>
</section>
</article>
</body>
CSS:
* {
box-sizing: border-box;
}
body {
font-family: "source sans pro";
font-weight: 400;
color: #fdfdfd;
}
body > section >.footer {
overflow: hidden;
}
nav {
position: fixed;
top: 0;
left: 0;
height: 70px;
width: 100%;
background-color: silver;
z-index: 999;
text-align: center;
font-size: 2em;
opacity: 0.8;
}
article {
position: relative;
font-size: 1em;
}
section {
height: 100vh;
padding-top: 5em;
}
.bg-img::before {
position: fixed;
content: ' ';
display: block;
width: 100vw;
min-height: 100vh;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-position: center;
background-size: cover;
z-index: -10;
}
.bg-img1:before {
background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326836/3balls_1280.jpg');
}
.bg-img2::before {
background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326840/icebubble-1280.jpg');
}
.bg-img3::before {
background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326844/soap-bubbles_1280.jpg');
}
h1, h2, h3 {
font-family: lato;
font-weight: 300;
text-transform: uppercase;
letter-spacing: 1px;
}
.content {
max-width: 50rem;
margin: 0 auto;
}
.solid {
min-height: 100vh;
width: 100%;
margin: auto;
border: 1px solid white;
background: rgba(255, 255, 255, 0.6);
}
.footer {
background: rgba(2, 2, 2, 0.5);
}
JS/JQUERY
window.onload = function() {
// Alternate Background Page with scrolling content (Bg Pages are odd#s)
var $bgImg = $('.bg-img');
var $nav = $('nav');
var winh = window.innerHeight;
var scrollPos = 0;
var page = 1;
var page1Bottom = winh;
var page3Top = winh;
var page3Bottom = winh * 3;
var page5Top = winh * 3;
var page5Bottom = winh * 5;
$(window).on('scroll', function() {
scrollPos = Number($(window).scrollTop().toFixed(2));
page = Math.floor(Number(scrollPos / winh) +1);
if (scrollPos >= 0 && scrollPos < page1Bottom ) {
if (! $bgImg.hasClass('bg-img1')) {
removeBg( $bgImg, 2, 3, 1 ); // element, low, high, current
$bgImg.addClass('bg-img1');
}
} else if (scrollPos >= page3Top && scrollPos <= page3Bottom) {
if (! $bgImg.hasClass('bg-img2')) {
removeBg( $bgImg, 1, 3, 2 ); // element, low, high, current
$bgImg.addClass('bg-img2');
}
} else if (scrollPos >= page5Top && scrollPos <= page5Bottom) {
if (! $bgImg.hasClass('bg-img3')) {
removeBg( $bgImg, 1, 2, 3 ); // element, low, high, current
$bgImg.addClass('bg-img3');
}
}
$nav.html("Page# " + page + " window position: " + scrollPos);
});
}
// This function was created to fix a problem where the mouse moves off the
// screen, this results in improper removal of background image class. Fix
// by removing any background class not applicable to current page.
function removeBg( el, low, high, current ) {
if (low > high || low <= 0 || high <= 0) {
console.log ("bad low/high parameters in removeBg");
}
for (var i=low; i<=high; i++) {
if ( i != current ) { // avoid removing class we are trying to add
if (el.hasClass('bg-img' +i )) {
el.removeClass('bg-img' +i );
}
}
}
} // removeBg()
NO, when you are using only one "=" you are assigning the variable.
You must use "==" : You must use "===" :
if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
$("#code").text(data.DATA[0].ID);
}
You could use fonction like .toLowerCase()
to avoid case problem if you want
Try using something like
Creates or overwrites a file in the specified path.
If you wanted just a Date, you can do Date.strptime(invoice.date.to_s, '%s')
where invoice.date
comes in the form of anFixnum
and then converted to a String
.
Use include("class.classname.php");
And class should use <?php //code ?> not <? //code ?>
I find and follow this youtube:
https://www.youtube.com/watch?v=PbW-doAiAvI
Basically, download the tar.gz package, extract into /opt/, and then run the "idea.sh" under bin folder (i.e. /opt/idea-IC-163.7743.44/bin/idea.sh)
Enjoy
Ljava.lang.String;@
is returned where you used string arrays as strings. Employee.getSelectCancel()
does not seem to return a String[]
Locale locale = new Locale(langCode);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.locale = locale;
preferences.setLocalePref(langCode);
context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
Here, langCode is the required language code. You can save the language code as string in sharedPreferences. and you can call this code super.onCreate(savedInstanceState)
in onCreate
.