How about using the Dynamic data template that comes with Visual Studio. This could be hosted on IIS.
Specify the maxrecursion option at the end of the query:
...
from EmployeeTree
option (maxrecursion 0)
That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.
Extension to parse decimal number from string.
Ability to set decimal symbol manually.
public static class StringExtension
{
public static double DoubleParseAdvanced(this string strToParse, char decimalSymbol = ',')
{
string tmp = Regex.Match(strToParse, @"([-]?[0-9]+)([\s])?([0-9]+)?[." + decimalSymbol + "]?([0-9 ]+)?([0-9]+)?").Value;
if (tmp.Length > 0 && strToParse.Contains(tmp))
{
var currDecSeparator = System.Windows.Forms.Application.CurrentCulture.NumberFormat.NumberDecimalSeparator;
tmp = tmp.Replace(".", currDecSeparator).Replace(decimalSymbol.ToString(), currDecSeparator);
return double.Parse(tmp);
}
return 0;
}
}
How to use:
"It's 4.45 O'clock now".DoubleParseAdvanced(); // will return 4.45
"It's 4,45 O'clock now".DoubleParseAdvanced(); // will return 4.45
"It's 4:45 O'clock now".DoubleParseAdvanced(':'); // will return 4.45
You can actually compile and run C code even without the use of nppexec plugins. If you use MingW32 C compiler, use g++ for C++ language and gcc for C language.
Paste this code into the notepad++ run section
cmd /k cd $(CURRENT_DIRECTORY) && gcc $(FILE_NAME) -o $(NAME_PART).exe && $(NAME_PART).exe && pause
It will compile your C code into exe and run it immediately. It's like a build and run feature in CodeBlock. All these are done with some cmd knowledge.
Explanation:
For more info on notepad++ commands, go to
http://docs.notepad-plus-plus.org/index.php/External_Programs
Add this line top of the header
#pragma warning(disable : 4996)
more shorter code to generate component: ng g c component-name
to specify its location: ng g c specific-folder/component-name
Additional info
more shorter code to generate directive: ng g d directive-name
to specify its location: ng g d specific-folder/directive-name
I found a much simpler alternative way to generating soap message. Given a Person Object:
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
private String name;
private int age;
private String address; //setter and getters below
}
Below is a simple Soap Message Generator:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@Slf4j
public class SoapGenerator {
protected static final ObjectMapper XML_MAPPER = new XmlMapper()
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule());
private static final String SOAP_BODY_OPEN = "<soap:Body>";
private static final String SOAP_BODY_CLOSE = "</soap:Body>";
private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";
public static String soapWrap(String xml) {
return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
}
public static String soapUnwrap(String xml) {
return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
}
}
You can use by:
public static void main(String[] args) throws Exception{
Person p = new Person();
p.setName("Test");
p.setAge(12);
String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
log.info("Generated String");
log.info(xml);
}
Press Report error and OK. Next will be enabled.
I created a godmode folder on the desktop. just create a new folder on the desktop and call it GodMode.{ED7BA470-8E54-465E-825C-99712043E01C} it will name the folder as godmode and populate the content with various config options, you can then just type in ENVIRO in the search to find the relevant config option, open it and it opens sysdm.cpl in the advanced tab, you can change the environment variables from there.
mysql 5.6 docs say that CURRENT_TIMESTAMP can be used as default for both TIMESTAMP and DATETIME data types:
http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html
Cross site request forgery (CSRF/XSRF) is when a malicious web page tricks users into performing a request that is not intended for example by using bookmarklets, iframes or just by creating a page which is visually similar enough to fool users.
The Rails CSRF protection is made for "classical" web apps - it simply gives a degree of assurance that the request originated from your own web app. A CSRF token works like a secret that only your server knows - Rails generates a random token and stores it in the session. Your forms send the token via a hidden input and Rails verifies that any non GET request includes a token that matches what is stored in the session.
However an API is usually by definition cross site and meant to be used in more than your web app, which means that the whole concept of CSRF does not quite apply.
Instead you should use a token based strategy of authenticating API requests with an API key and secret since you are verifying that the request comes from an approved API client - not from your own app.
You can deactivate CSRF as pointed out by @dcestari:
class ApiController < ActionController::Base
protect_from_forgery with: :null_session
end
Updated. In Rails 5 you can generate API only applications by using the --api
option:
rails new appname --api
They do not include the CSRF middleware and many other components that are superflouus.
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
The only solution works for me is similar to sowasred2012's answer:
$('body').css('display', 'table').height();
$('body').css('display', 'block');
I have a lot of problem blocks on page, so I change display
property of root element.
And I use display: table;
instead of display: none;
, because none
will reset scrolling offset.
com.sun.tools.javac.util.Pair is an simple implementation of a pair. It can be found in jdk1.7.0_51\lib\tools.jar.
Other than the org.apache.commons.lang3.tuple.Pair, it's not just an interface.
It could be that your default format doesn't match the file extension. You should specify the file format along with the filename, making sure the format matches the extension:
With someWorkbook
.SaveAs "C:\someDirector\Awesome.xlsm", fileformat:=xlOpenXMLWorkbookMacroEnabled
End With
OTOH, I don't see an extension on your .SaveAs filename. Maybe you need to supply one when doing this programmatically. That makes sense--not having to supply an extension from the GUI interface is convenient, but we programmers are expected to write unambiguous code. I suggest adding the extension and the matching format. See this msdn page for a list of file formats. To be honest, I don't recognize a lot o the descripions.
xlExcel8 = 56 is the .xls format
xlExcel12 = 50 is the .xlsb format
xlOpenXMLWorkbook = 51 is the .xlsx format
xlOpenXMLWorkbookMacroEnabled = 52 is the .xlsm format
xlWorkbookDefault is also listed with a value of 51, which puzzles me since I thought the default format could be changed.
Your server tells you exactly what you need : [Hint: SSLProxyEngine]
You need to add that directive to your VirtualHost
before the Proxy
directives :
SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/
As an application distributor, fpm sounds perfect for your needs. There is an example here which shows how to package an app from source. FPM can produce both deb files and RPM files.
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
To get bytes back just:
new BigInteger(bytes).toByteArray()
I had to return a rtf file and this worked for me.
// create a byte array of the file in correct format
byte[] docStream = createDoc(fragments);
return Response
.ok(docStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition","attachment; filename = doc.rtf")
.build();
$('#dbType').change(function(){
var selection = $(this).val();
if(selection == 'other')
{
$('#otherType').show();
}
else
{
$('#otherType').hide();
}
});
Remove lib from Podfile, then pod install
again.
You can follow the image i shared to unstash if u accidentally tapped stashing.
There is an open issue to only print this warning if there was actually something sanitized: https://github.com/angular/angular/pull/10272
I didn't read in detail when this warning is printed when nothing was sanitized.
If you want to copy paste files from Unix to Windows and Windows to Unix just use filezilla with port 22.
\usepackage{array}
in the preamble
then this:
\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}
note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"
In Swift, the == operator is equivalent to Objective C's isEqual: method (it calls the isEqual method instead of just comparing pointers, and there's a new === method for testing that the pointers are the same), so you can just write this as:
if username == "" || password == ""
{
println("Sign in failed. Empty character")
}
One thing I did to overcome this issue was to use a UIButton instead of a UILabel. Then in the Attributes Inspector of the Interface Builder, I used the Edge for the Title as the padding.
If you do not attach the button to an action, when clicked it will not get selected but it will still show the highlight.
You can also do this programmatically with the following code:
UIButton *mButton = [[UIButton alloc] init];
[mButton setTitleEdgeInsets:UIEdgeInsetsMake(top, left, bottom, right)];
[mButton setTitle:@"Title" forState:UIControlStateNormal];
[self.view addSubView:mButton];
This approach gives the same result but sometimes it did not work for some reason that I did not investigate since if possible I use the Interface Builder.
This is still a workaround but it works quite nicely if the highlight doesn't bother you. Hope it is useful
The precision of double
and float
is fixed by their size and the way the IEEE floating point types are implemented.
The number of decimal digits in the output, on the other hand, is a matter of formatting. You are correct that typing the same constant over and over is a bad idea. You should declare a string constant instead, and use its symbolic representation.
private static final String DBL_FMT = "##.####";
Using a symbolic representation would let you change precision in all places the constant is used without searching through your code.
Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.
Derived from book.cls
\def\@endpart{\vfil\newpage
\if@twoside
\null
\thispagestyle{empty}%
\newpage
\fi
\if@tempswa
\twocolumn
\fi}
It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.
\makeatletter
\renewcommand\@endpart{\vfil
\if@twoside
\null
\thispagestyle{empty}%
\newpage
\fi
\if@tempswa
\twocolumn
\fi}
\makeatother
input file element:
<input type="file" id="fileinput" />
get file :
var myFile = $('#fileinput').prop('files');
I restart the IDLE and works for me!
`pip -v` or `pip --v`
However note, if you are using macos catelina which has the zsh (z shell) it might give you a whole bunch of things, so the best option is to try install the version or start as -- pip3
This worked for me:
use <Database>
EXEC sp_change_users_login @Action='update_one', @UserNamePattern='<userLogin>',@LoginName='<userLogin>';
The problem can be visualized with:
SELECT sid FROM sys.sysusers WHERE name = '<userLogin>'
SELECT sid FROM sys.syslogins WHERE name = '<userLogin>';
git show
is more a plumbing command than git log
, and has the same formatting options:
git show -s --format=%B SHA1
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
The term "clone" is ambiguous (though the Java class library includes a Cloneable interface) and can refer to a deep copy or a shallow copy. Deep/shallow copies are not specifically tied to Java but are a general concept relating to making a copy of an object, and refers to how members of an object are also copied.
As an example, let's say you have a person class:
class Person {
String name;
List<String> emailAddresses
}
How do you clone objects of this class? If you are performing a shallow copy, you might copy name and put a reference to emailAddresses
in the new object. But if you modified the contents of the emailAddresses
list, you would be modifying the list in both copies (since that's how object references work).
A deep copy would mean that you recursively copy every member, so you would need to create a new List
for the new Person
, and then copy the contents from the old to the new object.
Although the above example is trivial, the differences between deep and shallow copies are significant and have a major impact on any application, especially if you are trying to devise a generic clone method in advance, without knowing how someone might use it later. There are times when you need deep or shallow semantics, or some hybrid where you deep copy some members but not others.
The difference is an iframe is able to "float" within content in a page, that is you can create an html page and position an iframe within it. This allows you to have a page and place another document directly in it. A frameset
allows you to split the screen into different pages (horizontally and vertically) and display different documents in each part.
Read IFrames security summary.
As thirtydot said, you can use the CSS3 background-size
syntax:
For example:
-o-background-size:35% auto;
-webkit-background-size:35% auto;
-moz-background-size:35% auto;
background-size:35% auto;
However, as also stated by thirtydot, this does not work in IE6, 7 and 8.
See the following links for more information about background-size
:
http://www.w3.org/TR/css3-background/#the-background-size
type=submit
it is a Submit Button type=button
it is just a button, It does not submit your form inputs. and also you don't want to use both of these
updated() should be what you're looking for:
Called after a data change causes the virtual DOM to be re-rendered and patched.
The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.
Instead of opening swagger ui as a file - you put into browser file:///D:/swagger-ui/dist/index.html you can: create iis virtual directory which enables browsing and points to D:/swagger-ui
You could try something like this:
select *
from jobdetails
where job_no like '071[12]%'
Not exactly what you're asking, but it has the same effect, and is flexible in other ways too :)
The post is old but I found a perfect CSS for the purpose and I want to share it.
A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).
div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
}
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
What about a little trickery like NgModel does with NgForm? You have to register your parent as a provider, then load your parent in the constructor of the child.
That way, you don't have to put [sharedList]
on all your children.
// Parent.ts
export var parentProvider = {
provide: Parent,
useExisting: forwardRef(function () { return Parent; })
};
@Component({
moduleId: module.id,
selector: 'parent',
template: '<div><ng-content></ng-content></div>',
providers: [parentProvider]
})
export class Parent {
@Input()
public sharedList = [];
}
// Child.ts
@Component({
moduleId: module.id,
selector: 'child',
template: '<div>child</div>'
})
export class Child {
constructor(private parent: Parent) {
parent.sharedList.push('Me.');
}
}
Then your HTML
<parent [sharedList]="myArray">
<child></child>
<child></child>
</parent>
You can find more information on the subject in the Angular documentation: https://angular.io/guide/dependency-injection-in-action#find-a-parent-component-by-injection
I was facing two issues Issue 1: all fields were coming one after other and Issue 2 white space at the bottom of the page when used to print from popup.
I Resolved this by
making display none to all body * elements most of them go for visibility hidden which creates space so avoid visibility hidden
@media print {
body * {
display:none;
width:auto;
height:auto;
margin:0px;padding:0px;
}
#printSection, #printSection * {
display:inline-block!important;
}
#printSection {
position:absolute;
left:0;
top:0;
margin:0px;
page-break-before: none;
page-break-after: none;
page-break-inside: avoid;
}
#printSection .form-group{
width:100%!important;
float:left!important;
page-break-after: avoid;
}
#printSection label{
float:left!important;
width:200px!important;
display:inline-block!important;
}
#printSection .form-control.search-input{
float:left!important;
width:200px!important;
display: inline-block!important;
}
}
Most of simple problems get complicated because simple functionality like order() in R that gives a statistical result in both and descending order is missing in various python libraries. But if we devise our thinking that all such statistical ordering and parameters in python are easily found in pandas, we can can result sooner than looking in 100 different places. Also, development of R and pandas go hand-in-hand because they were created for same purpose. To solve this problem I use following code that gets me by anywhere:
unique, counts = np.unique(x, return_counts=True)
d = {'unique':unique, 'counts':count} # pass the list to a dictionary
df = pd.DataFrame(d) #dictionary object can be easily passed to make a dataframe
df.sort_values(by = 'count', ascending=False, inplace = True)
df = df.reset_index(drop=True) #optional only if you want to use it further
At Back-end part
Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.
@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})
@ResponseBody
public boolean yourEndpointMethod(
@RequestPart("properties") @Valid ConnectionProperties properties,
@RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}
At front-end :
formData = new FormData();
formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
See in the image (POSTMAN request):
Click to view Postman request in form data for both file and json
Please see the comments.
Code:
import subprocess
class MyLibrary(object):
def execute(self, cmd):
return subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True,)
def list(self):
command = ["ping", "google.com"]
sp = self.execute(command)
status = sp.wait() # will wait for sp to finish
out, err = sp.communicate()
print(out)
return status # 0 is success else error
test = MyLibrary()
print(test.list())
Output:
C:\Users\shita\Documents\Tech\Python>python t5.py
Pinging google.com [142.250.64.78] with 32 bytes of data:
Reply from 142.250.64.78: bytes=32 time=108ms TTL=116
Reply from 142.250.64.78: bytes=32 time=224ms TTL=116
Reply from 142.250.64.78: bytes=32 time=84ms TTL=116
Reply from 142.250.64.78: bytes=32 time=139ms TTL=116
Ping statistics for 142.250.64.78:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 84ms, Maximum = 224ms, Average = 138ms
0
Hiding navigation bar only on first page can be achieved through storyboard as well. On storyboard, goto Navigation Controller Scene->Navigation Bar. And select 'Hidden' property from the Attributes inspector. This will hide navigation bar starting from first viewcontroller until its made visible for the required viewcontroller.
Navigation bar can be set back to visible in ViewController's ViewWillAppear callback.
-(void)viewWillAppear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:YES animated:animated];
[super viewWillAppear:animated];
}
I got this resolution at openshift.com.
Resolution:
This error occurs only on Windows machine with Ruby 2.0.0 version. Until we officially support Ruby 2.0 please downgrade to Ruby 1.9.
On Windows, you can install Ruby 1.9.3 alongside 2.0. Change your %PATH% to
c:\ruby193\
or whatever directory you installed to prior to installing the gem.
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd
, although in practice almost all browsers also support yyyy/mm/dd
as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy
, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split
splits a string on the given delimiter. Then we use parseInt
to convert the strings into numbers, and we use the new Date
constructor to build a Date
from those parts: The third part will be the year, the second part the month, and the first part the day. Date
uses zero-based month numbers, and so we have to subtract one from the month number.
It's a bit verbose, but i've gotten used to using the hidden .SD
variable.
b<-data.table(a=1,b=2,c=3,d=4)
b[,.SD,.SDcols=c(1:2)]
It's a bit of a hassle, but you don't lose out on other data.table features (I don't think), so you should still be able to use other important functions like join tables etc.
If the concrete methods invoke any of the abstract methods that strategy won't work, and you'd want to test each child class behavior separately. Otherwise, extending it and stubbing the abstract methods as you've described should be fine, again provided the abstract class concrete methods are decoupled from child classes.
Here's your problem:
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
Latitude and Longitude are double
-values, because they represent the location in degrees.
By casting them to int
, you're discarding everything behind the comma, which makes a big difference. See "Decimal Degrees - Wiki"
Here's the working code. Works in desktop and mobile browsers. hope it helps. thanks for everyone responding.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Layout</title>
<style type="text/css">
body, html
{
margin: 0; padding: 0; height: 100%; overflow: hidden;
}
#content
{
position:absolute; left: 0; right: 0; bottom: 0; top: 0px;
}
</style>
</head>
<body>
<div id="content">
<iframe width="100%" height="100%" frameborder="0" src="http://cnn.com" />
</div>
</body>
</html>
Kind of a mix:
Set it in your layout file :-
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="new checkbox"
android:background="@drawable/checkbox_background"
android:button="@drawable/checkbox" />
where the @drawable/checkbox will look like:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/checkbox_on_background_focus_yellow" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/checkbox_off_background_focus_yellow" />
<item android:state_checked="false"
android:drawable="@drawable/checkbox_off_background" />
<item android:state_checked="true"
android:drawable="@drawable/checkbox_on_background" />
</selector>
Something like this
<html>
<body style="height:100%; width:100%">
<div id="header" style="position:absolute; top:0px; left:0px; height:200px; right:0px;overflow:hidden;">
</div>
<div id="content" style="position:absolute; top:200px; bottom:200px; left:0px; right:0px; overflow:auto;">
</div>
<div id="footer" style="position:absolute; bottom:0px; height:200px; left:0px; right:0px; overflow:hidden;">
</div>
</body>
</html>
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
You cannot do it because you are already looping on it.
Inorder to avoid this situation use Iterator,which guarentees you to remove the element from list safely ...
List<Object> objs;
Iterator<Object> i = objs.iterator();
while (i.hasNext()) {
Object o = i.next();
//some condition
i.remove();
}
An "id" Specifies a unique id for an element & a class Specifies one or more classnames for an element . So its better to use "Class" instead of "id".
A DECIMAL(9,6) column will convert to float without loss of precision, so CAST(... AS float) will do the trick.
@HLGEM: saying that float is a poor choice for storing numbers and "Never use float" is not correct - you just have to know your numbers, e.g. temperature measurements would go nicely as floats.
@abatishchev and @japongskie: prefixes in front of SQL stored procs and functions are still a good idea, if not required; the links you mentioned only instructs not to use the "sp_" prefix for stored procedures which you shouldn't use, other prefixes are fine e.g. "usp_" or "spBob_"
Reference: "All integers with 6 or fewer significant decimal digits can be converted to an IEEE 754 floating-point value without loss of precision": https://en.wikipedia.org/wiki/Single-precision_floating-point_format
This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:
When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.
$(document).ready(function() { $("input[id$='btnAwesome']").click(function() { // Do client side button click stuff here. }); });
The id$= is doing a regex match for an id ENDING with btnAwesome.
Edit:
Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.
The gist of it is you create a static method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.
$.ajax({ type: "POST", url: "PageName.aspx/MethodName", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Do something interesting here. } });
I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.
A tty is a terminal (it stands for teletype - the original terminals used a line printer for output and a keyboard for input!). A terminal is a basically just a user interface device that uses text for input and output.
A pty is a pseudo-terminal - it's a software implementation that appears to the attached program like a terminal, but instead of communicating directly with a "real" terminal, it transfers the input and output to another program.
For example, when you ssh in to a machine and run ls
, the ls
command is sending its output to a pseudo-terminal, the other side of which is attached to the SSH daemon.
Run
cordova -v
to see the currently running version. Run the npm info command
npm info cordova
for a longer listing that includes the current version along with other available version numbers
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
I would also take a look at CloudMade's developer tools. They offer a beautifully styled OSM base map service, an OpenLayers plugin, and even their own light-weight, very fast JavaScript mapping client. They also host their own routing service, which you mentioned as a possible requirement. They have great documentation and examples.
If you make document dependent on DOCTYPE
(e.g. use named entities) then it will stop being standalone, thus standalone="yes"
won't be allowed in XML declaration.
However standalone XML can be used anywhere, while non-standalone is problematic for XML parsers that don't load externals.
I don't see how this declaration could be a problem, other than for interoperability with software that doesn't support XML, but some horrible regex soup.
The best you can do is import the dynamic library inside a bridging header:
#import <sqlite3.h>
to the topYou will then be able to access all of the c methods like sqlite3_open
from your swift code.
However, you may just want to use FMDB and import that through the bridging header as that is a more object oriented wrapper of sqlite. Dealing with C pointers and structs will be cumbersome in Swift.
With Reference to Anusree answer above and with respect,I am tweeking the code little bit to make sure it works in most of the cases.
Code:
$(document).ready(function () {
$(document).ajaxComplete(function () {
paginate('#myTableId',10);
function paginate(tableName,RecordsPerPage) {
$('#nav').remove();
$(tableName).after('<div id="nav"></div>');
var rowsShown = RecordsPerPage;
var rowsTotal = $(tableName + ' tbody tr').length;
var numPages = rowsTotal / rowsShown;
for (i = 0; i < numPages; i++) {
var pageNum = i + 1;
$('#nav').append('<a href="#" rel="' + i + '">' + pageNum + '</a> ');
}
$(tableName + ' tbody tr').hide();
$(tableName + ' tbody tr').slice(0, rowsShown).show();
$('#nav a:first').addClass('active');
$('#nav a').bind('click', function () {
$('#nav a').removeClass('active');
$(this).addClass('active');
var currPage = $(this).attr('rel');
var startItem = currPage * rowsShown;
var endItem = startItem + rowsShown;
$(tableName + ' tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
css('display', 'table-row').animate({ opacity: 1 }, 300);
});
}
});
});
since the data ex1221new was not given, so I have created a dummy data and added it to a data frame. Also, the question which was asked has few changes in codes like then ggplot package has deprecated the use of
"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()
In my answer,I have stored the plot in mygraph variable and then I have used
mygraph$labels$x="Discharge of materials" #changes x axis title
mygraph$labels$y="Area Affected" # changes y axis title
And the work is done. Below is the complete answer.
install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)
ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) +
scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
plot.title = element_text(color="Blue", size=30, hjust = 0.5),
# change the styling of both the axis simultaneously from this-
axis.title = element_text(color = "Green", size = 20, family="Courier",)
# you can change the axis title from the code below
mygraph$labels$x="Discharge of materials" #changes x axis title
mygraph$labels$y="Area Affected" # changes y axis title
mygraph
Also, you can change the labels title from the same formula used above -
mygraph$labels$size= "N2" #size contains the nitrogen level
Not sure if someone still needs it after 10 years but I solved it using eigenclass.
module UsefulThings
def useful_thing_1
"thing_1"
end
class << self
include UsefulThings
end
end
class A
include UsefulThings
end
class B
extend UsefulThings
end
UsefulThings.useful_thing_1 # => "thing_1"
A.new.useful_thing_1 # => "thing_1"
B.useful_thing_1 # => "thing_1"
A short piece of JavaScript code would do this job:
var numbers = [1,2,3,4];
var totalAmount = 0;
for (var x = 0; x < numbers.length; x++) {
totalAmount += numbers[x];
}
console.log(totalAmount); //10 (1+2+3+4)
Ditch the <a href="...">
. Put the onclick
(all lowercase) handler on the <li>
tag itself.
You may do it simply using python comprehension.
arr = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
]
transpose = [[arr[y][x] for y in range(len(arr))] for x in range(len(arr[0]))]
Without content, the height has no value to calculate the percentage of. The width, however, will take the percentage from the DOM, if no parent is specified. (Using your example) Placing the second div inside the first div, would have rendered a result...example below...
<div id="working">
<div id="not-working"></div>
</div>
The second div would be 30% of the first div's height.
You could do this:
String str = "...";
List<String> elephantList = Arrays.asList(str.split(","));
Basically the .split()
method will split the string according to (in this case) delimiter you are passing and will return an array of strings.
However, you seem to be after a List of Strings rather than an array, so the array must be turned into a list by using the Arrays.asList()
utility. Just as an FYI you could also do something like so:
String str = "...";
ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(","));
But it is usually better practice to program to an interface rather than to an actual concrete implementation, so I would recommend the 1st option.
What would happen, if you want to create many such records ones (to register 10 users, not just one)? I find the following solution (just 5 queryes):
Step I: Create temporary table to store new data.
CREATE TEMPORARY TABLE tmp (id bigint(20) NOT NULL, ...)...;
Next, fill this table with values.
INSERT INTO tmp (username, password, bio, homepage) VALUES $ALL_VAL
Here, instead of $ALL_VAL
you place list of values: ('test1','test1','bio1','home1'),...,('testn','testn','bion','homen')
Step II: Send data to 'user' table.
INSERT IGNORE INTO users (username, password)
SELECT username, password FROM tmp;
Here, "IGNORE" can be used, if you allow some users already to be inside. Optionaly you can use UPDATE similar to step III, before this step, to find whom users are already inside (and mark them in tmp table). Here we suppouse, that username is declared as PRIMARY
in users table.
Step III: Apply update to read all users id from users to tmp table. THIS IS ESSENTIAL STEP.
UPDATE tmp JOIN users ON tmp.username=users.username SET tmp.id=users.id
Step IV: Create another table, useing read id for users
INSERT INTO profiles (userid, bio, homepage)
SELECT id, bio, homepage FROM tmp
I've read http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/ [AngularJS allows us to streamline our controller logic by placing a promise directly on the scope, rather than manually handing the resolved value in a success callback.]
so simply and handy :)
var app = angular.module('myApp', []);
app.factory('Data', function($http,$q) {
return {
getData : function(){
var deferred = $q.defer();
var promise = $http.get('./largeLoad').success(function (response) {
deferred.resolve(response);
});
// Return the promise to the controller
return deferred.promise;
}
}
});
app.controller('FetchCtrl',function($scope,Data){
$scope.items = Data.getData();
});
Hope this help
You can add the TextField
as a child
to a Container
that has a BoxDecoration
with border
property:
new Container(
margin: const EdgeInsets.all(15.0),
padding: const EdgeInsets.all(3.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent)
),
child: Text("My Awesome Border"),
)
Use array_count_values()
function . Check this link http://php.net/manual/en/function.array-count-values.php
In 1.0, the functionality was bound to (
and tab
and shift-tab
, in 2.0 tab
was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab
. (
was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab
.
So press Shift-Tab
.
First you have to ensure that there is a SMTP server listening on port 25.
To look whether you have the service, you can try using TELNET client, such as:
C:\> telnet localhost 25
(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.
$ telnet localhost 25
If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.
If you don't have the service, you can use these:
If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.
Well, there's always the low tech solution of adding logging of the size of your maps when you modify them, then search the logs for which maps are growing beyond a reasonable size.
I had this issue in xcode 6 and there is a way to resolve the resize conflicts. If you select your view, at the bottom you will see an icon that looks like |-Δ-|. If you click on it, you're project will resize for different devices.
Most answers are a bit more complicated than necessary, or don't provide the exact format requested.
select Format(getdate(), 'MMMM dd yyyy') --returns 'October 01 2020', note the leading zero
select Format(getdate(), 'MMMM d yyyy') --returns the desired format with out the leading zero: 'October 1 2020'
If you want a comma, as you normally would, use:
select Format(getdate(), 'MMMM d, yyyy') --returns 'October 1, 2020'
Note: even though there is only one 'd' for the day, it will become a 2 digit day when needed.
I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.
Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.
tl;dr; Do not use this method.
A pragmatic solution is to force MySQL to keep the connection alive:
setInterval(function () {
db.query('SELECT 1');
}, 5000);
I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST
does not occur.
Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID()
and mysql connection have been reset without you being aware about it?
However, this only ensures that connection time out (wait_timeout
and interactive_timeout
) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.
There is a difference between $(this)
and event.target
, and quite a significant one. While this
(or event.currentTarget
, see below) always refers to the DOM element the listener was attached to, event.target
is the actual DOM element that was clicked. Remember that due to event bubbling, if you have
<div class="outer">
<div class="inner"></div>
</div>
and attach click listener to the outer div
$('.outer').click( handler );
then the handler
will be invoked when you click inside the outer div as well as the inner one (unless you have other code that handles the event on the inner div and stops propagation).
In this example, when you click inside the inner div, then in the handler
:
this
refers to the .outer
DOM element (because that's the object to which the handler was attached)event.currentTarget
also refers to the .outer
element (because that's the current target element handling the event)event.target
refers to the .inner
element (this gives you the element where the event originated)The jQuery wrapper $(this)
only wraps the DOM element in a jQuery object so you can call jQuery functions on it. You can do the same with $(event.target)
.
Also note that if you rebind the context of this
(e.g. if you use Backbone it's done automatically), it will point to something else. You can always get the actual DOM element from event.currentTarget
.
If you want a simple Hack:
arrlist.sort((o1, o2) -> {
if (o1.getName() == null) o1.setName("");
if (o2.getName() == null) o2.setName("");
return o1.getName().compareTo(o2.getName());
})
if you want put nulls to end of the list just change this in above metod
return o2.getName().compareTo(o1.getName());
Do you have variables that are associated with these print statements been output? if so, I have found that if the variable has no value then the print statement will not be ouput.
If you are splitting on newline, use splitlines(True)
.
>>> 'line 1\nline 2\nline without newline'.splitlines(True)
['line 1\n', 'line 2\n', 'line without newline']
(Not a general solution, but adding this here in case someone comes here not realizing this method existed.)
With ES6 you can use rest parameters for varagrs
. This takes the argument list and converts it to an array.
function logArgs(...args) {
console.log(args.length)
for(let arg of args) {
console.log(arg)
}
}
Do you want to switch to this??
switch(x) {
case 12:
case 16:
case 19:
//Do something
break;
default:
//Do nothing or something else..
break;
}
The difference between relational and non-relational is exactly that. The relational database architecture provides with constraints objects such as primary keys, foreign keys, etc that allows one to tie two or more tables in a relation. This is good so that we normalize our tables which is to say split information about what the database represents into many different tables, once can keep the integrity of the data.
For example, say you have a series of table that houses information about an employee. You could not delete a record from a table without deleting all the records that pertain to such record from the other tables. In this way you implement data integrity. The non-relational database doesn't provide this constraints constructs that will allow you to implement data integrity.
Unless you don't implement this constraint in the front end application that is utilized to populate the databases' tables, you are implementing a mess that can be compared with the wild west.
void foo(void);
That is the correct way to say "no parameters" in C, and it also works in C++.
But:
void foo();
Means different things in C and C++! In C it means "could take any number of parameters of unknown types", and in C++ it means the same as foo(void)
.
Variable argument list functions are inherently un-typesafe and should be avoided where possible.
Contains information about how to fetch a resource from its location. For example:
http://example.com/mypage.html
ftp://example.com/download.zip
mailto:[email protected]
file:///home/user/file.txt
http://example.com/resource?foo=bar#fragment
/other/link.html
(A relative URL, only useful in the context of another URL)URLs always start with a protocol (http
) and usually contain information such as the network host name (example.com
) and often a document path (/foo/mypage.html
). URLs may have query parameters and fragment identifiers.
Identifies a resource by name. It always starts with the prefix urn:
For example:
urn:isbn:0451450523
to identify a book by its ISBN number.urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66
a globally unique identifierurn:publishing:book
- An XML namespace that identifies the document as a type of book.URNs can identify ideas and concepts. They are not restricted to identifying documents. When a URN does represent a document, it can be translated into a URL by a "resolver". The document can then be downloaded from the URL.
URIs encompasses both URLs, URNs, and other ways to indicate a resource.
An example of a URI that is neither a URL nor a URN would be a data URI such as data:,Hello%20World
. It is not a URL or URN because the URI contains the data. It neither names it, nor tells you how to locate it over the network.
There are also uniform resource citations (URCs) that point to meta data about a document rather than to the document itself. An example of a URC would be an indicator for viewing the source code of a web page: view-source:http://example.com/
. A URC is another type of URI that is neither URL nor URN.
The w3 spec for HTML says that the href
of an anchor tag can contain a URI, not just a URL. You should be able to put in a URN such as <a href="urn:isbn:0451450523">
. Your browser would then resolve that URN to a URL and download the book for you.
Not that I know of, but modern web browser do implement the data URI scheme.
Good question. I've seen lots of places on the web that state this is true. I haven't been able to find any examples of something that is both a URL and a URN. I don't see how it is possible because a URN starts with urn:
which is not a valid network protocol.
No. Both relative and absolute URLs are URLs (and URIs.)
No. Both URLs with and without query parameters are URLs (and URIs.)
No. Both URLs with and without fragment identifiers are URLs (and URIs.)
tel:
URI a URL or a URN?For example tel:1-800-555-5555
. It doesn't start with urn:
and it has a protocol for reaching a resource over a network. It must be a URL.
Yes. The W3C realized that there is a ton of confusion about this. They issued a URI clarification document that says that it is now OK to use URL and URI interchangeably. It is no longer useful to strictly segment URIs into different types such as URL, URN, and URC.
tl;dr: downgrade java by running update-alternatives
My system gradle version was 4.4.1, and the gradle wrapper version was 4.0. After running the command given by several other answers:
gradle wrapper --gradle-version 4.4.1
I still had the same error:
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine java version from '11.0.4'.
It turns out java 11 wasn't supported until gradle 4.8, and my software repositories only had 4.4.1. (Also, upgrading to newer gradle version might have been incompatible with the package I was trying to compile.)
The answer was to downgrade java. My system actually had java8 already installed, and it was easy to switch between java versions by running this command and following the instructions:
sudo update-alternatives --config java
Here I am sharing code that can load image in form of bitmap from and save that image on sdcard gallery in app name folder. You should follow these steps
private Bitmap loadBitmap(String url) {
try {
InputStream in = new java.net.URL(url).openStream();
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
void saveMyImage(String appName, String imageUrl, String imageName) {
Bitmap bmImg = loadBitmap(imageUrl);
File filename;
try {
String path1 = android.os.Environment.getExternalStorageDirectory()
.toString();
File file = new File(path1 + "/" + appName);
if (!file.exists())
file.mkdirs();
filename = new File(file.getAbsolutePath() + "/" + imageName
+ ".jpg");
FileOutputStream out = new FileOutputStream(filename);
bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, appName);
image.put(Images.Media.DISPLAY_NAME, imageName);
image.put(Images.Media.DESCRIPTION, "App Image");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = filename.getParentFile();
image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
.toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
.toLowerCase());
image.put(Images.Media.SIZE, filename.length());
image.put(Images.Media.DATA, filename.getAbsolutePath());
Uri result = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
Toast.makeText(getApplicationContext(),
"File is Saved in " + filename, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.
There are better alternatives for dynamically creating objects using pre compiled lambda. Of course always performance is subjective and it clearly depends on each case if it's worth it or not.
Details about the issue on this article.
Graph is taken from the article and represents time taken in ms per 1000 calls.
Suppose I have the following table T
:
a b
--------
1 abc
1 def
1 ghi
2 jkl
2 mno
2 pqr
And I do the following query:
SELECT a, b
FROM T
GROUP BY a
The output should have two rows, one row where a=1
and a second row where a=2
.
But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.
This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).
Fixing it might look like this:
SELECT a, MAX(b) AS x
FROM T
GROUP BY a
Now it's clear that you want the following result:
a x
--------
1 ghi
2 pqr
is there a possibility that casting a double created via
Math.round()
will still result in a truncated down number
No, round()
will always round your double to the correct value, and then, it will be cast to an long
which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double)
:
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
You can also solve it by jQuery:
var new_width = $('#container').width();
$('#fixed').width(new_width);
This was so helpful to me because my layout was responsive, and the inherit
solution wasn't working with me!
You can use backticks
.
$ echo myfilename-"`date +"%d-%m-%Y"`"
Yields:
myfilename-25-11-2009
Within your .bat file:
set mypath=%cd%
You can now use the variable %mypath%
to reference the file path to the .bat
file. To verify the path is correct:
@echo %mypath%
For example, a file called DIR.bat
with the following contents
set mypath=%cd%
@echo %mypath%
Pause
run from the directory g:\test\bat
will echo that path in the DOS command window.
This worked for me:
find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;
Listen to the change event.
input.onchange = function(e) {
..
};
There's two steps in that process:
a) Grant privileges. As root user execute with this substituting 'password'
with your current root password :
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password';
b) bind to all addresses:
The easiest way is to comment out the line in your my.cnf
file:
#bind-address = 127.0.0.1
and restart mysql
service mysql restart
By default it binds only to localhost, but if you comment the line it binds to all interfaces it finds. Commenting out the line is equivalent to bind-address=*
.
To check where mysql service has binded execute as root:
netstat -tupan | grep mysql
Update For Ubuntu 16:
Config file is (now)
/etc/mysql/mysql.conf.d/mysqld.cnf
(at least on standard Ubuntu 16)
The simplest way to read a cookie I can think is using Regexp like this:
**Replace COOKIE_NAME
with the name of your cookie.
document.cookie.match(/COOKIE_NAME=([^;]*);/)[1]
How does it work?
Cookies are stored in document.cookie
like this: cookieName=cookieValue;cookieName2=cookieValue2;.....
The regex searches the whole cookie string for literaly "COOKIE_NAME="
and captures anything after it that is not a semicolon until it actually finds a semicolon;
Then we use [1]
to get the second item from array, which is the captured group.
It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.
Check this comment by @PaulIrish:
Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.
you can see workarounds to this in this posts:
Install
npm i graph-fs
Use
const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");
directory.clear(); // <--
You have to use querySelectorAll
as you need to select all elements with the said class, again since querySelectorAll
is an array you need to iterate it and add the event handlers
var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener('click', function (event) {
event.preventDefault();
var choice = confirm("sure u want to delete?");
if (choice) {
return true;
}
});
}
You should probably start with a little theory and simple examples such as the midpoint displacement algorithm. You should also learn a little about Perlin Noise if you are interested in generating graphics. I used this to get me started with my final year project on procedural generation.
Fractals are closely related to procedural generation.
Terragen and SpeedTree will show you some amazing possibilities of procedural generation.
Procedural generation is a technique that can be used in any language (it is definitely not restricted to procedural languages such as C, as it can be used in OO languages such as Java, and Logic languages such as Prolog). A good understanding of recursion in any language will strengthen your grasp of Procedural Generation.
As for 'serious' or non-game code, procedural generation techniques have been used to:
Check this basic code to setup html server. its work for me.
var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, html) { if (err) { throw err; } http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(8000); });
EDIT 2020: Most of these are basically just to test resolution stuff, some of them even outdated, sadly, mobile browser development went sideways with desktop (especially in Apple), therefore one can't really "emulate" a real phone with these as mentioned with comment.
To emulate real phones, often the best choice is to download a desktop app which, for Windows, is usually paid/freemium, on Mac just use the Xcode one (but I doubt Mac people are looking for this Q/A).
Freemium online easy to use that I found recently is Appetize.io it seems to really render the screen according to network, but honestly I didn't really dig into whether it also has identical features and indentically missing features as real iOS.
Fine simulator which - unlike resizing browser window to mobile phone dimensions - acts same as a smart phone. Don't be confused that you can't edit address bar in safari - just open deveolper tools (usually F12) and rewrite iframe's source URL to yours.
Link: http://recombu.com/mobile/interactive/ios7-demo/
Seems to work like recombu, but you can open url directly by text input and you can zoom in/out.
Link: http://www.responsimulator.com/
This one seems to process the webpage, but it emulates old iPhone - still handy sometimes.
Link: http://transmog.net/iphone-simulator/mobile-web-browser-emulator.php
Always use google (or other internet searchers) to check for other simulators/emulators and new versions.
Link with example google search for this one:
https://www.google.cz/search?q=online+iphone+emulator
If you open your browser's developer's tools (in Chrome F12), there will probably be an option to toggle device mode (in Chrome it is the little smartphone icon at top-left).
After choosing this option GUI will change and will provide option to select device to simulate (in Chrome it is at the top - select option "Device"), after selecting device, refreshing the page is often adviced to ensure simulator's accuracy.
You can subset using a vector of column names. I strongly prefer this approach over those that treat column names as if they are object names (e.g. subset()
), especially when programming in functions, packages, or applications.
# data for reproducible example
# (and to avoid confusion from trying to subset `stats::df`)
df <- setNames(data.frame(as.list(1:5)), LETTERS[1:5])
# subset
df[c("A","B","E")]
Note there's no comma (i.e. it's not df[,c("A","B","C")]
). That's because df[,"A"]
returns a vector, not a data frame. But df["A"]
will always return a data frame.
str(df["A"])
## 'data.frame': 1 obs. of 1 variable:
## $ A: int 1
str(df[,"A"]) # vector
## int 1
Thanks to David Dorchies for pointing out that df[,"A"]
returns a vector instead of a data.frame, and to Antoine Fabri for suggesting a better alternative (above) to my original solution (below).
# subset (original solution--not recommended)
df[,c("A","B","E")] # returns a data.frame
df[,"A"] # returns a vector
I was searching for a similar simple C++ config file parser and this tutorial website provided me with a basic yet working solution. Its quick and dirty soultion to get the job done.
myConfig.txt
gamma=2.8
mode = 1
path = D:\Photoshop\Projects\Workspace\Images\
The following program reads the previous configuration file:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
int main()
{
double gamma = 0;
int mode = 0;
std::string path;
// std::ifstream is RAII, i.e. no need to call close
std::ifstream cFile("myConfig.txt");
if (cFile.is_open())
{
std::string line;
while (getline(cFile, line))
{
line.erase(std::remove_if(line.begin(), line.end(), isspace),line.end());
if (line[0] == '#' || line.empty()) continue;
auto delimiterPos = line.find("=");
auto name = line.substr(0, delimiterPos);
auto value = line.substr(delimiterPos + 1);
//Custom coding
if (name == "gamma") gamma = std::stod(value);
else if (name == "mode") mode = std::stoi(value);
else if (name == "path") path = value;
}
}
else
{
std::cerr << "Couldn't open config file for reading.\n";
}
std::cout << "\nGamma=" << gamma;
std::cout << "\nMode=" << mode;
std::cout << "\nPath=" << path;
std::getchar();
}
FindByAttributeValue("Attribute-Name", "Attribute-Value");
p.s. if you know exact element-type, you add 3rd parameter (i.e.div, a, p ...etc...
):
FindByAttributeValue("Attribute-Name", "Attribute-Value", "div");
but at first, define this function:
function FindByAttributeValue(attribute, value, element_type) {
element_type = element_type || "*";
var All = document.getElementsByTagName(element_type);
for (var i = 0; i < All.length; i++) {
if (All[i].getAttribute(attribute) == value) { return All[i]; }
}
}
p.s. updated per comments recommendations.
If it is something that you reference but never mutate, then use const
:
declare const bootbox;
It depends on what you want.
console.log("story "+name+" story")
will concatenate the strings together and print that. For me, I use this because it is easier to see what is going on.
Using console.log("story",name,"story")
is similar to concatenation however, it seems to run something like this:
var text = ["story", name, "story"];
console.log(text.join(" "));
This is pushing all of the items in the array together, separated by a space: .join(" ")
There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this hash collision:
>>> hash(1.1)
2040142438
>>> hash(4504.1)
2040142438
Yet it doesn't break the dictionary:
>>> d = { 1.1: 'a', 4504.1: 'b' }
>>> d[1.1]
'a'
>>> d[4504.1]
'b'
Sanity check:
>>> for k,v in d.items(): print(hash(k))
2040142438
2040142438
Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.
(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at hash(1.1) == hash(214748749.8)
.)
Just put your sound file in the Res\raw\siren.mp3
folder, then use this code:
For Custom Sound:
Notification notification = builder.build();
notification.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.siren);
For Default Sound:
notification.defaults |= Notification.DEFAULT_SOUND;
For Custom Vibrate:
long[] vibrate = { 0, 100, 200, 300 };
notification.vibrate = vibrate;
For Default Vibrate:
notification.defaults |= Notification.DEFAULT_VIBRATE;
A negative look ahead is a correct answer, but it can be written more cleanly like:
(\\)(?!.*\\)
This looks for an occurrence of \ and then in a check that does not get matched, it looks for any number of characters followed by the character you don't want to see after it. Because it's negative, it only matches if it does not find a match.
You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.
You're likely best placed to use e.g. jQuery, specifically:
$('html, body').stop().animate({
scrollTop: element.offset().top
}, 1000);
A complete implementation may be:
$('#up, #down').on('click', function(e){
e.preventDefault();
var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
});
Where element
is the target element to scroll to and 1000
is the delay in ms before completion.
The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.
In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:
@(String.IsNullOrEmpty(Model.MaidenName) ? " " : Model.MaidenName)
This would print me " " in my page, respectively generate the source &nbsp;
. Now there is a function Html.Raw(" ")
which is supposed to let you write source code, except in this constellation it throws a compiler error:
Compiler Error Message: CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Web.IHtmlString' and 'string'
So I ended up writing a statement like the following, which is less nice but works even in my case:
@if (String.IsNullOrEmpty(Model.MaidenName)) { @Html.Raw(" ") } else { @Model.MaidenName }
Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.
Use this code fist of your code:
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
This works for me.
Here's a C++ example, based on some of the references. This is quick and dirty, you are better off not re-inventing and using the boost library.
#include "math.h" // for RAND, and rand
double sampleNormal() {
double u = ((double) rand() / (RAND_MAX)) * 2 - 1;
double v = ((double) rand() / (RAND_MAX)) * 2 - 1;
double r = u * u + v * v;
if (r == 0 || r > 1) return sampleNormal();
double c = sqrt(-2 * log(r) / r);
return u * c;
}
You can use a Q-Q plot to examine the results and see how well it approximates a real normal distribution (rank your samples 1..x, turn the ranks into proportions of total count of x ie. how many samples, get the z-values and plot them. An upwards straight line is the desired result).
C++ 11 added initialization lists to allow the following syntax:
std::vector<std::string> v = {"Hello", "World"};
Support for this C++ 11 feature was added in at least GCC 4.4 and only in Visual Studio 2013.
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
INSERT INTO table1 (col1, col2, col3)
SELECT column1, column2, column3
FROM table2
You can create a recursive function like this to do a depth-first traversal of the cars
object.
var findObjectByLabel = function(obj, label) {
if(obj.label === label) { return obj; }
for(var i in obj) {
if(obj.hasOwnProperty(i)){
var foundLabel = findObjectByLabel(obj[i], label);
if(foundLabel) { return foundLabel; }
}
}
return null;
};
which can be called like so
findObjectByLabel(car, "Chevrolet");
It can be done like this:
import numpy as np
# create a random matrix:
A = np.random.normal(size=(5,2))
# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))
In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.
If you installed the command line tools separately, delete them using:
sudo rm -rf /Library/Developer/CommandLineTools
This overloaded version of the save function works for me:
yourDF.save(outputPath, org.apache.spark.sql.SaveMode.valueOf("Overwrite"))
The example above would overwrite an existing folder. The savemode can take these parameters as well (https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/sql/SaveMode.html):
Append: Append mode means that when saving a DataFrame to a data source, if data/table already exists, contents of the DataFrame are expected to be appended to existing data.
ErrorIfExists: ErrorIfExists mode means that when saving a DataFrame to a data source, if data already exists, an exception is expected to be thrown.
Ignore: Ignore mode means that when saving a DataFrame to a data source, if data already exists, the save operation is expected to not save the contents of the DataFrame and to not change the existing data.
You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.
Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.
DELIMITER isn't really a MySQL language command, it's a client command.
DELIMITER $$
/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$
/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count FROM employees where department=the_department;
END$$
/*DELIMITER is set to it's default*/
DELIMITER ;
I think while (true)
is a bit more readable.
while :; do read; done
no waiting for child sleeping process.
So I finally found the solution myself.
Firstly I went into terminal and typed:
mysql -u root -p
This asked for my current password which I typed in and it gave me access to provide more mysql commands. Anything I tried from here gave this error:
ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
This is confusing because I couldn't actually see a way of resetting the password using ALTER USER
statement, but I did find another simple solution:
SET PASSWORD = PASSWORD('xxxxxxxx');
Facebook has a set of open-graph meta tags that it looks at to decide which image to show.
The keys one for the Facebook image are:
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
<meta property="og:image:secure_url" content="https://secure.example.com/ogp.jpg" />
and it should be present inside the <head></head>
tag at the top of your page.
If these tags are not present, it will look for their older method of specifying an image: <link rel="image_src" href="/myimage.jpg"/>
. If neither are present, Facebook will look at the content of your page and choose images from your page that meet its share image criteria: Image must be at least 200px by 200px, have a maximum aspect ratio of 3:1, and in PNG, JPEG or GIF format.
Can I specify multiple images to allow the user to select an image?
Yes, you just need to add multiple image meta tags in the order you want them to appear in. The user will then be presented with an image selector dialog:
I specified the appropriate image meta tags. Why isn't Facebook accepting the changes?
Once a url has been shared, Facebook's crawler, which has a user agent of facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)
, will access your page and cache the meta information. To force Facebook servers to clear the cache, use the Facebook Url Debugger / Linter Tool that they launched in June 2010 to refresh the cache and troubleshoot any meta tag issues on your page.
Also, the images on the page must be publicly accessible to the Facebook crawler. You should specify absolute url's like http://example.com/yourimage.jpg instead of just /yourimage.jpg.
Can I update these meta tags with client side code like Javascript or jQuery? No. Much like search engine crawlers, the Facebook scraper does not execute scripts so whatever meta tags are present when the page is downloaded are the meta tags that are used for image selection.
Adding these tags causes my page to no longer validate. How can I fix this?
You can add the necessary Facebook namespaces to your tag and your page should then pass validation:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://ogp.me/ns#"
xmlns:fb="https://www.facebook.com/2008/fbml">
I found the answer today. Maybe its too late but still I think its a much better one. Check this one https://jsfiddle.net/Amar_newDev/khb2oyru/5/
Try to change the CSS code : <ul> max-width:1%; margin:auto; text-align:left; </ul>
max-width:80% or something like that.
Try experimenting you might find something new.
You can use Jinja's default
:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
if you use an assignment operator but use it in wrong way or in wrong place,
then you'll get this types of errors!
suppose if you type:
p+1=p; you will get the error!!
you will get the same error for this:
if(ch>='a' && ch='z')
as you see can see that I i tried to assign in if() statement!!!
how silly I am!!! right??
ha ha
actually i forgot to give less then(<) sign
if(ch>='a' && ch<='z')
and got the error!!
The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.
Like this:
ggplot() +
geom_line(data=Data1, aes(x=A, y=B), color='green') +
geom_line(data=Data2, aes(x=C, y=D), color='red')
instead of
ggplot(data=Data1, aes(x=A, y=B), color='green') +
geom_line() +
geom_line(data=Data2, aes(x=C, y=D), color='red')
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
You can use this Stopwatch wrapper:
public class Benchmark : IDisposable
{
private readonly Stopwatch timer = new Stopwatch();
private readonly string benchmarkName;
public Benchmark(string benchmarkName)
{
this.benchmarkName = benchmarkName;
timer.Start();
}
public void Dispose()
{
timer.Stop();
Console.WriteLine($"{benchmarkName} {timer.Elapsed}");
}
}
Usage:
using (var bench = new Benchmark($"Insert {n} records:"))
{
... your code here
}
Output:
Insert 10 records: 00:00:00.0617594
For advanced scenarios, you can use BenchmarkDotNet or Benchmark.It or NBench
Does the second query return any results from the 17th, or just from the 18th?
The first query will only return results from the 17th, or midnight on the 18th.
Try this instead
select *
from LOGS
where check_in >= CONVERT(datetime,'2013-10-17')
and check_in< CONVERT(datetime,'2013-10-19')
See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
You need to specify a field in latest(). eg.
obj= Model.objects.filter(testfield=12).latest('testfield')
Or if your model’s Meta specifies get_latest_by, you can leave off the field_name
argument to earliest() or latest()
. Django will use the field specified in get_latest_by
by default.
In two way ssl the client asks for servers digital certificate and server ask for the same from the client. It is more secured as it is both ways, although its bit slow. Generally we dont follow it as the server doesnt care about the identity of the client, but a client needs to make sure about the integrity of server it is connecting to.
This might seem like overkill, but if in another case you were trying to load a canvas from js (like I am doing), you could use a setInterval function and an if statement to constantly check if the canvas has loaded.
//set up the interval
var thisInterval = setInterval(function{
//this if statment checks if the id "thisCanvas" is linked to something
if(document.getElementById("thisCanvas") != null){
//do what you want
//clearInterval() will remove the interval if you have given your interval a name.
clearInterval(thisInterval)
}
//the 500 means that you will loop through this every 500 milliseconds (1/2 a second)
},500)
(In this example the canvas I am trying to load has an id of "thisCanvas")
I tried the approaches given above, but these methods fail when dynamically the height of the content in one of the cols increases, it basically pushes the other cols down.
for me the basic table layout solution worked.
// Apply this to the enclosing row
.row-centered {
text-align: center;
display: table-row;
}
// Apply this to the cols within the row
.col-centered {
display: table-cell;
float: none;
vertical-align: top;
}
You may also want to make sure that your code localizes correctly, or make sure the users are used to the "international" notation. For example, "1,112" actually means different numbers across different countries. In Germany it means the number a little over one, instead of one thousand and something.
Corresponding Wikipedia article is at http://en.wikipedia.org/wiki/Decimal_mark. It seems to be poorly written at this time though. For example as a Chinese I'm not sure where does these description about thousand separator in China come from.
You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:
<body oncopy="return false" oncut="return false" onpaste="return false">
How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers
A more advanced aproach:
How to detect Ctrl+V, Ctrl+C using JavaScript?
Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.
There is a nice form plugin that allows you to send an HTML form asynchroniously.
$(document).ready(function() {
$('#myForm1').ajaxForm();
});
or
$("select").change(function(){
$('#myForm1').ajaxSubmit();
});
to submit the form immediately
Build.Version is the place go to for this data. Here is a code snippet for how to format it.
public String getAndroidVersion() {
String release = Build.VERSION.RELEASE;
int sdkVersion = Build.VERSION.SDK_INT;
return "Android SDK: " + sdkVersion + " (" + release +")";
}
Looks like this "Android SDK: 19 (4.4.4)"
If You would like to perform something like "cd.." option, just type:
os.chdir("..")
it is the same as in Windows cmd: cd.. Of course import os is neccessary (e.g type it as 1st line of your code)
I'm pretty sure you only have to register MappingJacksonHttpMessageConverter
(the easiest way to do that is through <mvc:annotation-driven />
in XML or @EnableWebMvc
in Java)
See:
Here's a working example:
Maven POM
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version><name>json test</name>
<dependencies>
<dependency><!-- spring mvc -->
<groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
</dependency>
<dependency><!-- jackson -->
<groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
</dependency>
</dependencies>
<build><plugins>
<!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
<!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
<version>7.4.0.v20110414</version></plugin>
</plugins></build>
</project>
in folder src/main/webapp/WEB-INF
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet><servlet-name>json</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>json</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
json-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:mvc-context.xml" />
</beans>
in folder src/main/resources:
mvc-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="test.json" />
</beans>
In folder src/main/java/test/json
TestController.java
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(method = RequestMethod.POST, value = "math")
@ResponseBody
public Result math(@RequestBody final Request request) {
final Result result = new Result();
result.setAddition(request.getLeft() + request.getRight());
result.setSubtraction(request.getLeft() - request.getRight());
result.setMultiplication(request.getLeft() * request.getRight());
return result;
}
}
Request.java
public class Request implements Serializable {
private static final long serialVersionUID = 1513207428686438208L;
private int left;
private int right;
public int getLeft() {return left;}
public void setLeft(int left) {this.left = left;}
public int getRight() {return right;}
public void setRight(int right) {this.right = right;}
}
Result.java
public class Result implements Serializable {
private static final long serialVersionUID = -5054749880960511861L;
private int addition;
private int subtraction;
private int multiplication;
public int getAddition() { return addition; }
public void setAddition(int addition) { this.addition = addition; }
public int getSubtraction() { return subtraction; }
public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
public int getMultiplication() { return multiplication; }
public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}
You can test this setup by executing mvn jetty:run
on the command line, and then sending a POST request:
URL: http://localhost:8080/test/math
mime type: application/json
post body: { "left": 13 , "right" : 7 }
I used the Poster Firefox plugin to do this.
Here's what the response looks like:
{"addition":20,"subtraction":6,"multiplication":91}
I believe this could be a simpler way:
public int BusinessDaysUntil(DateTime start, DateTime end, params DateTime[] bankHolidays)
{
int tld = (int)((end - start).TotalDays) + 1; //including end day
int not_buss_day = 2 * (tld / 7); //Saturday and Sunday
int rest = tld % 7; //rest.
if (rest > 0)
{
int tmp = (int)start.DayOfWeek - 1 + rest;
if (tmp == 6 || start.DayOfWeek == DayOfWeek.Sunday) not_buss_day++; else if (tmp > 6) not_buss_day += 2;
}
foreach (DateTime bankHoliday in bankHolidays)
{
DateTime bh = bankHoliday.Date;
if (!(bh.DayOfWeek == DayOfWeek.Saturday || bh.DayOfWeek == DayOfWeek.Sunday) && (start <= bh && bh <= end))
{
not_buss_day++;
}
}
return tld - not_buss_day;
}
string id;
foreach (GridViewRow rows in grd.Rows)
{
TextBox lblStrucID = (TextBox)rows.FindControl("grdtext");
id=lblStrucID.Text
}
Check the 'minSdkVersion' in your build.gradle
The default project creates it with the latest API, so if you're phone is not yet up-dated (e.g. minSdkVersion 21), which is probably your case.
Make sure the minSdkVersion value matches with the device API version or if the device has a higher one.
Example:
defaultConfig {
applicationId 'xxxxxx'
minSdkVersion 16
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
I know this is an old thread, but I landed here when my row deletes were blocked by foreign key constraints. In my case, my table design permitted "NULL" values in the constrained column. In the rows to be deleted, I changed the constrained column value to "NULL" (which does not violate the Foreign Key Constraint) and then deleted all the rows.
First of all you need to give the permission of your Codeigniter folder, It's might be the permission issue and then start your server.
You can use the OpenSSL Command line tool. The following commands should do the trick
openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts
openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts
If you want your file to be password protected etc, then there are additional options.
You can read the entire documentation here.
You shouldn't for security reasons. Especially if cookies are in play here. It leaves you wide open to cookie-based replay attacks.
Either way, you should use Apache control rules to tune it.
Then you can test for HTTPS being enabled and redirect as-needed where needed.
You should redirect to the pay page only using a FORM POST (no get), and accesses to the page without a POST should be directed back to the other pages. (This will catch the people just hot-jumping.)
http://joseph.randomnetworks.com/archives/2004/07/22/redirect-to-ssl-using-apaches-htaccess/
Is a good place to start, apologies for not providing more. But you really should shove everything through SSL.
It's over-protective, but at least you have less worries.
I have found this works ONLY in Chrome (where it's red) and not Safari and all other browsers (where it's green)...
.style {
color: green;
(-bracket-:hack;
color: red;
);
}
From http://mynthon.net/howto/webdev/css-hacks-for-google-chrome.htm
I'm planning to static import the following to allow for the method reference to be used inline:
public static <T> Predicate<T> not(Predicate<T> t) {
return t.negate();
}
e.g.
Stream<String> s = ...;
long nonEmptyStrings = s.filter(not(String::isEmpty)).count();
Update: Starting from Java-11, the JDK offers a similar solution built-in as well.
Check out the instanceof operator.
var isJqueryObject = obj instanceof jQuery
You're essentially running out of memory to run the process smoothly. Options that come to mind:
-Xmx512m
firstHashMap
objects to process at once if possibleString.intern()
on them before putting them into the HashMap
HashMap(int initialCapacity, float loadFactor)
constructor to tune for your caseUse a sub query similar to the below.
UPDATE P
SET extrasPrice = sub.TotalPrice from
BookingPitches p
inner join
(Select PitchID, Sum(Price) TotalPrice
from dbo.BookingPitchExtras
Where [Required] = 1
Group by Pitchid
) as Sub
on p.Id = e.PitchId
where p.BookingId = 1
opacity: 0.99; on wrapper solve webkit bug
Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :
The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.
So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.
Try this easy code:
awk '{printf("%s,",$2)}' File1
After spending about two hours trying to come up with a solution I realized that I had adblockers blocking the call to GA. Once I turned them off I was good to go.
Let me post another implementation, which builds upon the answer of Kinvais, but integrates ideas from the AttributeDict proposed in http://databio.org/posts/python_AttributeDict.html.
The advantage of this version is that it also works for nested dictionaries:
class AttrDict(dict):
"""
A class to convert a nested Dictionary into an object with key-values
that are accessible using attribute notation (AttrDict.attribute) instead of
key notation (Dict["key"]). This class recursively sets Dicts to objects,
allowing you to recurse down nested dicts (like: AttrDict.attr.attr)
"""
# Inspired by:
# http://stackoverflow.com/a/14620633/1551810
# http://databio.org/posts/python_AttributeDict.html
def __init__(self, iterable, **kwargs):
super(AttrDict, self).__init__(iterable, **kwargs)
for key, value in iterable.items():
if isinstance(value, dict):
self.__dict__[key] = AttrDict(value)
else:
self.__dict__[key] = value
Just to add to this:
If you also need to prevent the user to manually type a date in the past, this is a possible solution. This is what we ended up doing (based on @Nicola Peluchetti's answer)
var dateToday = new Date();
$("#myDatePickerInput").change(function () {
var updatedDate = $(this).val();
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, updatedDate, instance.settings);
if (date < dateToday) {
$(this).datepicker("setDate", dateToday);
}
});
What this does is to change the value to today's date if the user manually types a date in the past.
out and ref are exactly the same with the exception that out variables don't have to be initialized before sending it into the abyss. I'm not that smart, I cribbed that from the MSDN library :).
To be more explicit about their use, however, the meaning of the modifier is that if you change the reference of that variable in your code, out and ref will cause your calling variable to change reference as well. In the code below, the ceo variable will be a reference to the newGuy once it returns from the call to doStuff. If it weren't for ref (or out) the reference wouldn't be changed.
private void newEmployee()
{
Person ceo = Person.FindCEO();
doStuff(ref ceo);
}
private void doStuff(ref Person employee)
{
Person newGuy = new Person();
employee = newGuy;
}
In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.
For an array:
var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();
As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.
But as we all know JavaScript is strange, so here are some weird bits:
array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!
This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()
). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.
So what are Objects?
Objects in JavaScript are just like arrays but the "index" can be any string.
var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK
You can even opt to not use the square brackets when working with objects!
console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";
You can go even further and define objects like so:
var newObject = {
a: 2,
};
newObject.a === 2; // true
Eventhough it is an old question, this may help someone.
We can choose multiple files while browsing for a file using "multiple"
<input type="file" name="datafile" size="40" multiple>
I met the same problem even using -ldl
.
Besides this option, source files need to be placed before libraries, see undefined reference to `dlopen'.
Make a sample request to https://http-tools.appspot.com/reflect-http-request/some-unique-id and check what this request contains (request header, request body, request parameters) by its corresponding finder url https://http-tools.appspot.com/reflect-http-request-finder/some-unique-id. You can use any string instead of some-unique-id
, check out https://http-tools.appspot.com for more details.
each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.
For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.
http:..../somelink?componentId=123
would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123
The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.
You're almost there: it's NOW() - INTERVAL 1 DAY
If you want the while loop to stop after some condition, and your foo
command returns non-zero when this condition is met then you can get the loop to break like this:
while foo; do echo 'sleeping...'; sleep 5; done;
For example, if the foo
command is deleting things in batches, and it returns 1 when there is nothing left to delete.
This works well if you have a custom script that needs to run a command many times until some condition. You write the script to exit with 1
when the condition is met and exit with 0
when it should be run again.
For example, say you have a python script batch_update.py
which updates 100 rows in a database and returns 0
if there are more to update and 1
if there are no more. The the following command will allow you to update rows 100 at a time with sleeping for 5 seconds between updates:
while batch_update.py; do echo 'sleeping...'; sleep 5; done;
This solution worked for me.
DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'
FROM sys.dm_exec_sessions
WHERE database_id = db_id('MyDB')
EXEC(@kill);
Below are the reasons of Error: redirect_uri_mismatch issue occurs :
Recommended to use domain URL
You can do it without using plugins.
In the latest version of vscode that I'm using (1.17.0) you can simply open the branch that you want (from the bottom left menu) then press ctrl+shift+p
and type Git: Merge branch
and then choose the other branch that you want to merge from (to the current one)
Edit If you are asking about security, see my addendum at the bottom Edit
PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.
$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);
This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.
Addendum
I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.
Select Into functionality only works for PL/SQL Block, when you use Execute immediate , oracle interprets v_query_str as a SQL Query string so you can not use into .will get keyword missing Exception. in example 2 ,we are using begin end; so it became pl/sql block and its legal.
Yup, this error might as well be "something failed, good luck figuring out what" - In my case it was a wrong username. SQL Server 2019 RC1.
You have to pass parameter sender
and e
to call button event handler in .cs file
btnTest_Click(sender,e);
All You have to do is git push origin master
, where origin
is the default name (alias) of Your remote repository and master
is the remote branch You want to push Your changes to.
You may also want to check these out:
Luckily, the package-info class isn't required. I was able to fix mine problem with iowatiger08 solution.
Here is my fix showing the error message to help join the dots for some.
Error message
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://global.aon.bz/schema/cbs/archive/errorresource/0", local:"errorresource"). Expected elements are <{}errorresource>
Code before fix
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="", propOrder={"error"})
@XmlRootElement(name="errorresource")
public class Errorresource
Code after fix
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="", propOrder={"error"})
@XmlRootElement(name="errorresource", namespace="http://global.aon.bz/schema/cbs/archive/errorresource/0")
public class Errorresource
You can see the namespace added to @XmlRootElement as indicated in the error message.
If you have the program and the core file, you can do the following steps.
1) Run the gdb on the program along with core file
$gdb ./test core
2) type info files and see what different segments are there in the core file.
(gdb)info files
A sample output:
(gdb)info files
Symbols from "/home/emntech/debugging/test".
Local core dump file:
`/home/emntech/debugging/core', file type elf32-i386.
0x0055f000 - 0x0055f000 is load1
0x0057b000 - 0x0057c000 is load2
0x0057c000 - 0x0057d000 is load3
0x00746000 - 0x00747000 is load4
0x00c86000 - 0x00c86000 is load5
0x00de0000 - 0x00de0000 is load6
0x00de1000 - 0x00de3000 is load7
0x00de3000 - 0x00de4000 is load8
0x00de4000 - 0x00de7000 is load9
0x08048000 - 0x08048000 is load10
0x08049000 - 0x0804a000 is load11
0x0804a000 - 0x0804b000 is load12
0xb77b9000 - 0xb77ba000 is load13
0xb77cc000 - 0xb77ce000 is load14
0xbf91d000 - 0xbf93f000 is load15
In my case I have 15 segments. Each segment has start of the address and end of the address. Choose any segment to search data for. For example lets select load11 and search for a pattern. Load11 has start address 0x08049000 and ends at 0x804a000.
3) Search for a pattern in the segment.
(gdb) find /w 0x08049000 0x0804a000 0x8048034
0x804903c
0x8049040
2 patterns found
If you don't have executable file you need to use a program which prints data of all segments of a core file. Then you can search for a particular data at an address. I don't find any program as such, you can use the program at the following link which prints data of all segments of a core or an executable file.
http://emntech.com/programs/printseg.c
For me my vmdk file was accompanied by a vmx file. Opening the vmx file worked for vmware player.
You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:
root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}
#we capture release hash
$curr_os = $os['release']
case $curr_os['major'] {
'7': { .... something }
*: {something}
}
That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.
The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.
To clear a view extending ViewGroup, you just need to use the method removeAllViews()
Just like this (if you have a ViewGroup called myElement
) :
myElement.removeAllViews()
TejaDroid's answer in below link helped me . Can't import org.apache.http.HttpResponse in Android Studio
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
...
}
If you have a self-signed certificate generated by makecert.exe
on a Windows machine, you will get two files: cert.pvk
and cert.cer
. These can be converted to a pfx using pvk2pfx
pvk2pfx
is found in the same location as makecert
(e.g. C:\Program Files (x86)\Windows Kits\10\bin\x86
or similar)
pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx
From Spring Boot 2, you will have to use
--spring.config.additional-location=production.properties
Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.
That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...
What version of the SQL Server engine do you get from SELECT @@VERSION
??