None of the other answers here worked for me, possibly from trying a combination of all of them. I was able to adapt this accepted answer to work with meld. This is now working for me with git 1.9.4, meld 3.14.0, and windows 8.1.
Edit ~/.gitconfig to look like:
[diff]
tool = meld
guitool = meld
[mergetool "meld"]
path = c:/Program Files (x86)/Meld/Meld.exe
[difftool "meld"]
path = c:/Program Files (x86)/Meld/Meld.exe
For Windows 10 I had to put this in my .gitconfig:
[merge]
tool = meld
[mergetool "meld"]
cmd = 'C:/Program Files (x86)/Meld/Meld.exe' $LOCAL $BASE $REMOTE --output=$MERGED
[mergetool]
prompt = false
Everything else you need to know is written in this super answer by mattst further above.
PS: For some reason, this only worked with Meld 3.18.x, Meld 3.20.x gives me an error.
just use echo'd javascript to rid the URL of any variables with a self-submitting, blank form:
<?
if (isset($_GET['your_var'])){
//blah blah blah code
echo "<script type='text/javascript'>unsetter();</script>";
?>
Then make this javascript function:
function unsetter() {
$('<form id = "unset" name = "unset" METHOD="GET"><input type="submit"></form>').appendTo('body');
$( "#unset" ).submit();
}
You can use not filter on top of missing.
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"not": {
"filter": {
"missing": {
"field": "searchField"
}
}
}
}
}
}
If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su
then apt-get install -y wget
https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient
to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.
The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:
final String extensionRemoved = filename.split("\\.")[0];
I hope this helps
There is also Jaunt Java Web Scraping & JSON Querying - http://jaunt-api.com
The following works for me:
?rel=0&fs=0&showinfo=0
The best solution from my experience : https://stackoverflow.com/a/44177688/3118950, which is override the long getItemId()
and return unique ID instead of the default position. In addition to that answer is imported to notice that old fragment will be kept in the fragment manager in case the total amount is less than the page limit and onDetach()
/onDestory()
will not be called when the fragment is replaced.
Actual Answer:
The default deserializer for enums uses .name()
to deserialize, so it's not using the @JsonValue
. So as @OldCurmudgeon pointed out, you'd need to pass in {"event": "FORGOT_PASSWORD"}
to match the .name()
value.
An other option (assuming you want the write and read json values to be the same)...
More Info:
There is (yet) another way to manage the serialization and deserialization process with Jackson. You can specify these annotations to use your own custom serializer and deserializer:
@JsonSerialize(using = MySerializer.class)
@JsonDeserialize(using = MyDeserializer.class)
public final class MyClass {
...
}
Then you have to write MySerializer
and MyDeserializer
which look like this:
MySerializer
public final class MySerializer extends JsonSerializer<MyClass>
{
@Override
public void serialize(final MyClass yourClassHere, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
// here you'd write data to the stream with gen.write...() methods
}
}
MyDeserializer
public final class MyDeserializer extends org.codehaus.jackson.map.JsonDeserializer<MyClass>
{
@Override
public MyClass deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
{
// then you'd do something like parser.getInt() or whatever to pull data off the parser
return null;
}
}
Last little bit, particularly for doing this to an enum JsonEnum
that serializes with the method getYourValue()
, your serializer and deserializer might look like this:
public void serialize(final JsonEnum enumValue, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
gen.writeString(enumValue.getYourValue());
}
public JsonEnum deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
{
final String jsonValue = parser.getText();
for (final JsonEnum enumValue : JsonEnum.values())
{
if (enumValue.getYourValue().equals(jsonValue))
{
return enumValue;
}
}
return null;
}
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
You could do it like this:
<a>
with a class, say "cancel"set up the dialog by acting on all elements with class="cancel":
$('a.cancel').click(function() {
var a = this;
$('#myDialog').dialog({
buttons: {
"Yes": function() {
window.location = a.href;
}
}
});
return false;
});
(plus your other options)
The key points here are:
However, I recommend that you make this a POST instead of a GET, since a cancel action has side effects and thus doesn't comply with GET semantics...
background-image: url("/your-dir/your_image.jpg");
min-height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;}
Kinda surprised nobody's pointed out the direct way to do it, which is easy enough.
double roundToDecimalPlaces(double value, int decimalPlaces)
{
double shift = Math.pow(10,decimalPlaces);
return Math.round(value*shift)/shift;
}
Pretty sure this does not do half-even rounding though.
For what it's worth, half-even rounding is going to be chaotic and unpredictable any time you mix binary-based floating-point values with base-10 arithmetic. I'm pretty sure it cannot be done. The basic problem is that a value like 1.105 cannot be represented exactly in floating point. The floating point value is going to be something like 1.105000000000001, or 1.104999999999999. So any attempt to perform half-even rounding is going trip up on representational encoding errors.
IEEE floating point implementations will do half-rounding, but they do binary half-rounding, not decimal half-rounding. So you're probably ok
Also with dict
a = []
b = {1:'one'}
a.append(dict(b))
print a
b[1]='iuqsdgf'
print a
result
[{1: 'one'}]
[{1: 'one'}]
You found one answer, i.e. eval(parse())
. You can also investigate do.call()
which is often simpler to implement. Keep in mind the useful as.name()
tool as well, for converting strings to variable names.
I figured I'd leave this here for those upgrading to Turbolinks 5: the easiest way to fix your code is to go from:
var ready;
ready = function() {
// Your JS here
}
$(document).ready(ready);
$(document).on('page:load', ready)
to:
var ready;
ready = function() {
// Your JS here
}
$(document).on('turbolinks:load', ready);
Reference: https://github.com/turbolinks/turbolinks/issues/9#issuecomment-184717346
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
I have the following in a types.ts
file for html input, select, and textarea:
export type InputChangeEventHandler = React.ChangeEventHandler<HTMLInputElement>
export type TextareaChangeEventHandler = React.ChangeEventHandler<HTMLTextAreaElement>
export type SelectChangeEventHandler = React.ChangeEventHandler<HTMLSelectElement>
Then import them:
import { InputChangeEventHandler } from '../types'
Then use them:
const updateName: InputChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
const updateBio: TextareaChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
const updateSize: SelectChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
Then apply the functions on your markup (replacing ...
with other necessary props):
<input onChange={updateName} ... />
<textarea onChange={updateName} ... />
<select onChange={updateSize} ... >
// ...
</select>
To highlight spaces, just search for it:
/<space>
Notes:
To highlight spaces & tabs:
/[<space><tab>]
A quick way to remove the highlights is to search for anything else: /asdf
(just type any short list of random characters)
I had this problem and I couldn't find the solution here, so I want to share my solution in case someone else has this problem again.
I had this code:
public void finishAction() {
onDestroy();
finish();
}
and solved the problem by deleting the line "onDestroy();"
public void finishAction() {
finish();
}
The reason I wrote the initial code: I know that when you execute "finish()" the activity calls "onDestroy()", but I'm using threads and I wanted to ensure that all the threads are destroyed before starting the next activity, and it looks like "finish()" is not always immediate. I need to process/reduce a lot of “Bitmap” and display big “bitmaps” and I’m working on improving the use of the memory in my app
Now I will kill the threads using a different method and I’ll execute this method from "onDestroy();" and when I think I need to kill all the threads.
public void finishAction() {
onDestroyThreads();
finish();
}
I had a similar issue where I couldn't connect to a database and tried the recommendations here.
At the end of the day this is what worked for me:
Used the SQL Server Configuration Manager tool to enable the TCP/IP and/or the Named Pipes protocols on the SQL Server client computer.
I am still not sure why or when this was disabled.
A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class ImageButton extends Button {
public void updateImages(final Image selected, final Image unselected) {
final ImageView iv = new ImageView(selected);
this.getChildren().add(iv);
iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(unselected);
}
});
iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(selected);
}
});
super.setGraphic(iv);
}
}
My guess is that you're trying to squeeze a number greater than 99999.99 into your decimal fields. Changing it to (8,3) isn't going to do anything if it's greater than 99999.999 - you need to increase the number of digits before the decimal. You can do this by increasing the precision (which is the total number of digits before and after the decimal). You can leave the scale the same unless you need to alter how many decimal places to store. Try decimal(9,2)
or decimal(10,2)
or whatever.
You can test this by commenting out the insert #temp
and see what numbers the select statement is giving you and see if they are bigger than your column can handle.
head
takes the first lines from a file, and the -n
parameter can be used to specify how many lines should be extracted:
line=$(head -n 1 filename)
The problem in the jsfiddle is that your dummy text is all one word. If you use your lorem ipsum given in the question, then the text wraps fine.
If you want large words to be broken mid-word and wrap around, add this to your .title css:
word-wrap: break-word;
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
This error happens when there are no files inside /src/main/java Just make some empty files inside and the problem will go away.
A side note: lots of version control systems (mercurial for example) do not commit folders if there are no files inside.
ul{list-style-type:none;}
Just set the style of unordered list is none.
For anytone who has worked in ASP as well as more modern languages, the question will provoke a chuckle. In my experience using a custom error handler (set up in IIS to handle the 500;100 errors) is the best option for ASP error handling. This article describes the approach and even gives you some sample code / database table definition.
http://www.15seconds.com/issue/020821.htm
Here is a link to Archive.org's version
It's as simple as is:
WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/some.html");
And your some.html needs to contain something like:
<link rel="stylesheet" type="text/css" href="style.css" />
if you just want to show the file itself:
header('Content-Type: text/plain');
header('Content-Disposition: inline; filename="filename.txt"');
readfile(path);
Most problems are naturally expressed by recursion such as Fibonacci, Merge sorting and quick sorting. In this respect, the code is written for humans, not machines.
Iterative solutions often rely on varying temporary variables which makes the code hard to read. This can be avoided with recursion.
Recursion is not stack friendly. Stack can overflow when the recursion is not well designed or tail optimization is not supported.
You can use css and the :hover pseudo-property. Here is a simple demo. It uses the following css:
a span.tooltip {display:none;}
a:hover span.tooltip {position:absolute;top:30px;left:20px;display:inline;border:2px solid green;}
Note that older browsers have limited support for :hover.
1st Step: Add this content in pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2nd Step : Execute this command line by line.
cd /go/to/myApp
mvn clean
mvn compile
mvn package
java -cp target/myApp-0.0.1-SNAPSHOT.jar go.to.myApp.select.file.to.execute
Can you use default android Crop functionality?
Here is my code
private void performCrop(Uri picUri) {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties here
cropIntent.putExtra("crop", true);
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 128);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
declare:
final int PIC_CROP = 1;
at top.
In onActivity result method, writ following code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PIC_CROP) {
if (data != null) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap selectedBitmap = extras.getParcelable("data");
imgView.setImageBitmap(selectedBitmap);
}
}
}
It is pretty easy for me to implement and also shows darken areas.
Most mocking frameworks (Moq and RhinoMocks included) generate proxy classes as a substitute for your mocked class, and override the virtual methods with behavior that you define. Because of this, you can only mock interfaces, or virtual methods on concrete or abstract classes. Additionally, if you're mocking a concrete class, you almost always need to provide a parameterless constructor so that the mocking framework knows how to instantiate the class.
Why the aversion to creating interfaces in your code?
try
List<TheUser> friends = jsonSerializer.Deserialize<List<TheUser>>(response);
str1 = "Hello"
str2 = "World"
newstr = " ".join((str1, str2))
That joins str1 and str2 with a space as separators. You can also do "".join(str1, str2, ...)
. str.join()
takes an iterable, so you'd have to put the strings in a list or a tuple.
That's about as efficient as it gets for a builtin method.
UIButton extension with Swift 3+ syntax:
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}}
Use it like:
YourButton.setBackgroundColor(color: UIColor.white, forState: .highlighted)
Original Answer: https://stackoverflow.com/a/30604658/3659227
There is not a drawTriangle method neither in Graphics nor Graphics2D. You need to do it by yourself. You can draw three lines using the drawLine
method or use one these methods:
These methods work with polygons. You may change the prefix draw
to fill
when you want to fill the polygon defined by the point set. I inserted the documentation links. Take a look to learn how to use them.
There is the GeneralPath class too. It can be used with Graphics2D, which is capable to draw Shapes. Take a look:
Give them all a name that is the same
For example
<input type="button" value="a" name="btn" onclick="a" />
<input type="button" value="b" name="btn" onclick="b" />
Then in your php use:
$val = $_POST['btn']
Edit, as BalusC said; If you're not going to use onclick for doing any javascript (for example, sending the form) then get rid of it and use type="submit"
In my application also I've experienced an issue like this. I've set top edge inset of tableView zero. Also tried set false
for automaticallyAdjustsScrollViewInsets
. But didn't work.
Finally I got a working solution. I don't know is this the correct way. But implementing heightForHeaderInSection
delegate method worked for me. You have to return a non-zero value to work this (return zero will display same space as before).
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
Float has 32 bit (4 bytes) with 8 places accuracy. Double has 64 bit (8 bytes) with 16 places accuracy.
If you need better accuracy, use Double instead of Float.
As per the http status code definitions a 302 indicates a (temporary) redirect. "The requested resource resides temporarily under a different URI"
If you even plan on merging your branch, I highly suggest you look at this:
I hear Subversion 1.5 builds more of the merge tracking in, I have no experience with that. My project is on 1.4.x and svnmerge.py is a life saver!
public boolean waitForElement(String zoneName, String element, int index, int timeout) {
WebDriverWait wait = new WebDriverWait(appiumDriver, timeout/1000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(element)));
return true;
}
make sure you have mapped the y: drive, or copy all the files to local dir c:/local
c:/local> copy *.* c:/newfile.txt
This should have been a comment, but it wasn't fitting in a comment length, so I posted it as an answer.
All the benefits mentioned in other answers are achievable by simpler means than using maven. If, for-example, you are new to a project, you'll anyway spend more time creating project architecture, joining components, coding than downloading jars and copying them to lib folder. If you are experienced in your domain, then you already know how to start off the project with what libraries. I don't see any benefit of using maven, especially when it poses a lot of problems while automatically doing the "dependency management".
I only have intermediate level knowledge of maven, but I tell you, I have done large projects(like ERPs) without using maven.
Below is the command to run a single test class using gradlew
command line option:
gradlew.bat Connected**your bundleVariant**AndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.example.TestClass
Below example to run class com.example.TestClass
with variant Variant_1
:
gradlew.bat ConnectedVariant_1AndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.example.TestClass
As many have mentioned previously, you must convert each column to string and then use the plus operator to combine two string columns. You can get a large performance improvement by using NumPy.
%timeit df['Year'].values.astype(str) + df.quarter
71.1 ms ± 3.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit df['Year'].astype(str) + df['quarter']
565 ms ± 22.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
The go-uuid
library is NOT RFC4122 compliant. The variant bits are not set correctly. There have been several attempts by community members to have this fixed but pull requests for the fix are not being accepted.
You can generate UUIDs using the Go uuid library I rewrote based on the go-uuid
library. There are several fixes and improvements. This can be installed with:
go get github.com/twinj/uuid
You can generate random (version 4) UUIDs with:
import "github.com/twinj/uuid"
u := uuid.NewV4()
The returned UUID type is an interface and the underlying type is an array.
The library also generates v1 UUIDs and correctly generates v3 and 5 UUIDs. There are several new methods to help with printing and formatting and also new general methods to create UUIDs based off of existing data.
you are a PyCharm User, its good easy to install Flask First open the pycharm press Open Settings(Ctrl+Alt+s) Goto Project Interpreter
Double click pip>>
search bar (top of page) you search the flask and click install package
such Cases in which flask is not shown in pip: Open Manage Repository>> Add(+) >> Add this following url
https://www.palletsprojects.com/p/flask/
Now back to pip, it will show related packages of flask,
select flask>>
install package
I know this is old but this answer still applies to newer Core releases.
If by chance your DbContext
implementation is in a different project than your startup project and you run ef migrations
, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations
know where they're at.
dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]
Both -s
and -p
are optionals that default to the current folder.
For those looking for an answer and the others haven't worked, this might:
If you're using a component within a component (e.g. something like this in the Vue DOM):
App
MyComponent
ADifferentComponent
MyComponent
Here the issue is that MyComponent
is both the parent and child of itself. This throws Vue into a loop, with each component depending on the other.
There's a few solutions to this:
MyComponent
vue.component("MyComponent", MyComponent)
beforeCreate
beforeCreate: function () {
this.$options.components.MyComponent = require('./MyComponent.vue').default
}
import
into a lambda function within the components
objectcomponents: {
MyComponent: () => import('./MyComponent.vue')
}
My preference is the third option, it's the simplest tweak and fixes the issue in my case.
More info: Vue.js Official Docs — Handling Edge Cases: Circular References Between Components
Note: if you choose method's 2 or 3, in my instance I had to use this method in both the parent and child components to stop this issue arising.
The catch is that input elements are inline. We have to make it block (display:block) before positioning it to center : margin : 0 auto. Please see the code below :
<html>
<head>
<style>
div.wrapper {
width: 300px;
height:300px;
border:1px solid black;
}
input[type="text"] {
display: block;
margin : 0 auto;
}
</style>
</head>
<body>
<div class='wrapper'>
<input type='text' name='ok' value='ok'>
</div>
</body>
</html>
But if you have a div which is positioned = absolute then we need to do the things little bit differently.Now see this!
<html>
<head>
<style>
div.wrapper {
position: absolute;
top : 200px;
left: 300px;
width: 300px;
height:300px;
border:1px solid black;
}
input[type="text"] {
position: relative;
display: block;
margin : 0 auto;
}
</style>
</head>
<body>
<div class='wrapper'>
<input type='text' name='ok' value='ok'>
</div>
</body>
</html>
Hoping this can be helpful.Thank you.
You can use this plugin, but for printing purpose i have added some code like
<button onclick="window.print();">Print</button>
and for saving image <button onclick="savePhoto();">Save Picture</button>
function savePhoto() {
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
window.location = img;}
checkout this plugin http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app
for Google Maps v3, you need to trigger the resize event differently:
google.maps.event.trigger(map, "resize");
See the documentation for the resize event (you'll need to search for the word 'resize'): http://code.google.com/apis/maps/documentation/v3/reference.html#event
Update
This answer has been here a long time, so a little demo might be worthwhile & although it uses jQuery, there's no real need to do so.
$(function() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map($("#map-canvas")[0], mapOptions);
// listen for the window resize event & trigger Google Maps to update too
$(window).resize(function() {
// (the 'map' here is the result of the created 'var map = ...' above)
google.maps.event.trigger(map, "resize");
});
});
_x000D_
html,
body {
height: 100%;
}
#map-canvas {
min-width: 200px;
width: 50%;
min-height: 200px;
height: 80%;
border: 1px solid blue;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&dummy=.js"></script>
Google Maps resize demo
<div id="map-canvas"></div>
_x000D_
UPDATE 2018-05-22
With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map
class.
The documentation states
When the map is resized, the map center is fixed
The full-screen control now preserves center.
There is no longer any need to trigger the resize event manually.
source: https://developers.google.com/maps/documentation/javascript/new-renderer
google.maps.event.trigger(map, "resize");
doesn't have any effect starting from version 3.32
The values for the float data type come from having 32 bits in total to represent the number which are allocated like this:
1 bit: sign bit
8 bits: exponent p
23 bits: mantissa
The exponent is stored as p + BIAS
where the BIAS is 127, the mantissa has 23 bits and a 24th hidden bit that is assumed 1. This hidden bit is the most significant bit (MSB) of the mantissa and the exponent must be chosen so that it is 1.
This means that the smallest number you can represent is 01000000000000000000000000000000
which is 1x2^-126 = 1.17549435E-38
.
The largest value is 011111111111111111111111111111111
, the mantissa is 2 * (1 - 1/65536) and the exponent is 127 which gives (1 - 1 / 65536) * 2 ^ 128 = 3.40277175E38
.
The same principles apply to double precision except the bits are:
1 bit: sign bit
11 bits: exponent bits
52 bits: mantissa bits
BIAS: 1023
So technically the limits come from the IEEE-754 standard for representing floating point numbers and the above is how those limits come about
Arrays are special objects in java, they have a simple attribute named length
which is final
.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
- The
public
final
fieldlength
, which contains the number of components of the array.length
may be positive or zero.The
public
methodclone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of theclone
method of an array typeT[]
isT[]
.A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
- All the members inherited from class
Object
; the only method ofObject
that is not inherited is itsclone
method.
Resources:
In your own answer, you effectively do this:
Dim SrcRange As Range ' you should always declare things explicitly
Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")
You're not really "extracting" the range to a variable, you're setting a reference to the range.
In many situations, this can be more efficient as well as more flexible:
Dim Src As Variant
Src= Sheets("Src").Range("A2:A9").Value 'Read range to array
'Here you can add code to manipulate your Src array
'...
Sheets("Dest").Range("A2:A9").Value = Src 'Write array back to another range
I tried everything for hours but the following finally fixed it (I'm on OS X 10.9.4):
Python's sort implementation "timsort" is specifically optimized for lists that contain ordered sections. Plus, it's written in C.
http://bugs.python.org/file4451/timsort.txt
http://en.wikipedia.org/wiki/Timsort
As people have mentioned, it may call the comparison function more times by some constant factor (but maybe call it more times in a shorter period in many cases!).
I would never rely on this, however. – Daniel Nadasi
I believe the Python developers are committed to keeping timsort, or at least keeping a sort that's O(n) in this case.
Generalized sorting (i.e. leaving apart radix sorts from limited value domains)
cannot be done in less than O(n log n) on a serial machine. – Barry Kelly
Right, sorting in the general case can't be faster than that. But since O() is an upper bound, timsort being O(n log n) on arbitrary input doesn't contradict its being O(n) given sorted(L1) + sorted(L2).
I assume that you use distinct like a method call on a list. You need to use the result of the query as datasource for your DropDownList, for example by materializing it via ToList
.
var distinctCategories = product
.Select(m => new {m.CategoryId, m.CategoryName})
.Distinct()
.ToList();
DropDownList1.DataSource = distinctCategories;
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryId";
Another way if you need the real objects instead of the anonymous type with only few properties is to use GroupBy
with an anonymous type:
List<Product> distinctProductList = product
.GroupBy(m => new {m.CategoryId, m.CategoryName})
.Select(group => group.First()) // instead of First you can also apply your logic here what you want to take, for example an OrderBy
.ToList();
A third option is to use MoreLinq's DistinctBy
.
You can use composition instead... this will allow you to access class objects from the static type. But still cant implements interfaces or abstract classes
according to http://www.maketecheasier.com/combine-multiple-pdf-files-with-pdftk/ the command should be
pdftk file1.pdf file2.pdf file3.pdf cat output newfile.pdf
note that you should download windows version of pdftk
Thanks to Novocaine88's answer to use a try catch loop I have successfully received an error message when I caused one.
<?php
$dbhost = "localhost";
$dbname = "pdo";
$dbusername = "root";
$dbpassword = "845625";
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$statement = $link->prepare("INERT INTO testtable(name, lastname, age)
VALUES(?,?,?)");
$statement->execute(array("Bob","Desaunois",18));
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
In the following code instead of INSERT INTO it says INERT.
this is the error I got.
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INERT INTO testtable(name, lastname, age) VALUES('Bob','Desaunoi' at line 1
When I "fix" the issue, it works as it should. Thanks alot everyone!
Beware of circular references when DOM objects are involved:
Memory leak patterns in JavaScript
Keep in mind that memory can only be reclaimed when there are no active references to the object. This is a common pitfall with closures and event handlers, as some JS engines will not check which variables actually are referenced in inner functions and just keep all local variables of the enclosing functions.
Here's a simple example:
function init() {
var bigString = new Array(1000).join('xxx');
var foo = document.getElementById('foo');
foo.onclick = function() {
// this might create a closure over `bigString`,
// even if `bigString` isn't referenced anywhere!
};
}
A naive JS implementation can't collect bigString
as long as the event handler is around. There are several ways to solve this problem, eg setting bigString = null
at the end of init()
(delete
won't work for local variables and function arguments: delete
removes properties from objects, and the variable object is inaccessible - ES5 in strict mode will even throw a ReferenceError
if you try to delete a local variable!).
I recommend to avoid unnecessary closures as much as possible if you care for memory consumption.
Using .replace(/\s+/g,'') works fine;
Example:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.
@RequestParam(required = false)String name
In NetBeans 8 with a Maven-driven project, merely context-click on the jar file list item of the dependency in which you are interested. Choose Download Sources
. Wait a moment and NetBeans will automatically download and install the source code, if available.
Similarly you can choose Download Javadoc
to get the doc locally installed. Then you can context-click some code in the editor and choose to see the JavaDoc.
Why not simply add the following to the beginning of the script
PRINT 'INACTIVE SCRIPT'
RETURN
See sync-request: https://github.com/ForbesLindesay/sync-request
Example:
var request = require('sync-request');
var res = request('GET', 'http://example.com');
console.log(res.getBody());
You can check if the object is produced by JQuery with the jquery
property:
myObject.jquery // 3.3.1
=> return the number of the JQuery version if the object produced by JQuery.
=> otherwise, it returns undefined
I develop a library that I think could help you. It is called icmplib (unrelated to any other code of the same name that can be found on the Internet) and is a pure implementation of the ICMP protocol in Python.
It is completely object oriented and has simple functions such as the classic ping, multiping and traceroute, as well as low level classes and sockets for those who want to develop applications based on the ICMP protocol.
Here are some other highlights:
To install it (Python 3.6+ required):
pip3 install icmplib
Here is a simple example of the ping function:
host = ping('1.1.1.1', count=4, interval=1, timeout=2, privileged=True)
if host.is_alive:
print(f'{host.address} is alive! avg_rtt={host.avg_rtt} ms')
else:
print(f'{host.address} is dead')
Set the "privileged" parameter to False if you want to use the library without root privileges.
You can find the complete documentation on the project page: https://github.com/ValentinBELYN/icmplib
Hope you will find this library useful.
First install setuptools
sudo pip install setuptools
Then install mysql-connector
sudo pip install mysql-connector
If using Python3, then replace pip by pip3
Have a look at the DateTime
class. It should do the calculations correctly and the date formats are compatible with strttotime
. Something like:
$datestring='2011-03-30 first day of last month';
$dt=date_create($datestring);
echo $dt->format('Y-m'); //2011-02
As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined
keyword.
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is undefined
Go to the task manager, kill the java processes and turn the server back on. should work fine.
As I posted in the comment you don't need to use both setTimeout()
and setInterval()
, moreover you have a syntax error too (the one extra }
). Correct your code like this:
(edited to add two functions to force the next/previous image to be shown)
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
</script>
</head>
<body onload = "startTimer()">
<img id="img" src="startpicture.jpg"/>
<button type="button" onclick="displayPreviousImage()">Previous</button>
<button type="button" onclick="displayNextImage()">Next</button>
</body>
</html>
Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
I use buffers like tabs, using the BufExplorer plugin and a few macros:
" CTRL+b opens the buffer list
map <C-b> <esc>:BufExplorer<cr>
" gz in command mode closes the current buffer
map gz :bdelete<cr>
" g[bB] in command mode switch to the next/prev. buffer
map gb :bnext<cr>
map gB :bprev<cr>
With BufExplorer you don't have a tab bar at the top, but on the other hand it saves space on your screen, plus you can have an infinite number of files/buffers open and the buffer list is searchable...
Just incase this helps anyone else also, I was signed into the mac app, command line working fine, but because I then turned on 2FA, my commands were returning the error. I had to sign out of the app, then I could use my Personal access token in my commands as per ele's answer here.
Hopefully that helps someone!
You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).
ContextCompat.getColor(context, R.color.my_color)
As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.
You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:
compile 'com.android.support:support-v4:23.0.1'
Extending the accepted answer for a common usecase. In particular:
View the circles at a natural aspect ratio.
Automatically extend the axes limits to include the newly plotted circles.
Self-contained example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.add_patch(plt.Circle((0, 0), 0.2, color='r', alpha=0.5))
ax.add_patch(plt.Circle((1, 1), 0.5, color='#00ffff', alpha=0.5))
ax.add_artist(plt.Circle((1, 0), 0.5, color='#000033', alpha=0.5))
#Use adjustable='box-forced' to make the plot area square-shaped as well.
ax.set_aspect('equal', adjustable='datalim')
ax.plot() #Causes an autoscale update.
plt.show()
Note the difference between ax.add_patch(..)
and ax.add_artist(..)
: of the two, only the former makes autoscaling machinery take the circle into account (reference: discussion), so after running the above code we get:
See also: set_aspect(..)
documentation.
flexbox
approach:The easiest way how to center a single element vertically and horizontally is to make it a flex item and set its margin to auto
:
If you apply auto margins to a flex item, that item will automatically extend its specified margin to occupy the extra space in the flex container...
.flex-container {_x000D_
height: 150px;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.flex-item {_x000D_
margin: auto;_x000D_
}
_x000D_
<div class="flex-container">_x000D_
<div class="flex-item">_x000D_
This should be centered!_x000D_
</div>_x000D_
</div>
_x000D_
This extension of margins in each direction will push the element exactly to the middle of its container.
The message means that both the packages have functions with the same names. In this particular case, the testthat
and assertive
packages contain five functions with the same name.
R will look through the search
path to find functions, and will use the first one that it finds.
search()
## [1] ".GlobalEnv" "package:assertive" "package:testthat"
## [4] "tools:rstudio" "package:stats" "package:graphics"
## [7] "package:grDevices" "package:utils" "package:datasets"
## [10] "package:methods" "Autoloads" "package:base"
In this case, since assertive
was loaded after testthat
, it appears earlier in the search path, so the functions in that package will be used.
is_true
## function (x, .xname = get_name_in_parent(x))
## {
## x <- coerce_to(x, "logical", .xname)
## call_and_name(function(x) {
## ok <- x & !is.na(x)
## set_cause(ok, ifelse(is.na(x), "missing", "false"))
## }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>
The functions in testthat
are not accessible in the usual way; that is, they have been masked.
You can explicitly provide a package name when you call a function, using the double colon operator, ::
. For example:
testthat::is_true
## function ()
## {
## function(x) expect_true(x)
## }
## <environment: namespace:testthat>
If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE
to library
.
library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time
Alternatively, suppress the message with suppressPackageStartupMessages
:
library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output
If you have altered some of R's startup configuration options (see ?Startup
) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup
should solve most mysteries.
For example, the documentation there says:
Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.
Which implies that when 3rd party packages are loaded via files like .Rprofile
you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.
First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.
library(dplyr)
envs <- search() %>% setNames(., .)
For each environment, get the exported functions (and other variables).
fns <- lapply(envs, ls)
Turn this into a data frame, for easy use with dplyr.
fns_by_env <- data_frame(
env = rep.int(names(fns), lengths(fns)),
fn = unlist(fns)
)
Find cases where the object appears more than once.
fns_by_env %>%
group_by(fn) %>%
tally() %>%
filter(n > 1) %>%
inner_join(fns_by_env)
To test this, try loading some packages with known conflicts (e.g., Hmisc
, AnnotationDbi
).
The conflicted
package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.
library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
## * Hmisc::units
## * base::units
Check for root:
ROOT_UID=0 # Root has $UID 0.
if [ "$UID" -eq "$ROOT_UID" ]
then
echo "You are root."
else
echo "You are just an ordinary user."
fi
exit 0
Tested and running in root.
Here is how I do it in 2018. Who knows, maybe an R newbie will see it one day and fall in love with ggplot2
.
library(ggplot2)
ggplot(data = iris, aes(Petal.Length, Petal.Width, color = Species)) +
geom_point() +
scale_color_manual(values = c("setosa" = "red", "versicolor" = "blue", "virginica" = "yellow"))
Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:
1 Perform face detection(Input an image, output all boxes of detected faces):
from mtcnn.mtcnn import MTCNN
import cv2
face_detector = MTCNN()
img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)
[{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]
2 save all detected faces to separate files:
for i in range(len(detect_boxes)):
box = detect_boxes[i]["box"]
face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)
3 or Draw rectangles of all detected faces:
for box in detect_boxes:
box = box["box"]
pt1 = (box[0], box[1]) # top left
pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)
Actually,,i found a simple answer,, Jst adding the object to String Builder instead of String worked ;)
StringBuilder jsonString= new StringBuilder.append("http://www.json-.com/j/cglqaRcMSW?=4");
JSON json= new JSON(jsonString.toString);
i think i'd try with MAX something like this:
SELECT staff_id, max( date ) from owner.table group by staff_id
then link in your other columns:
select staff_id, site_id, pay_level, latest
from owner.table,
( SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date
You don't need to use a second repository - you can do commands like git checkout
and git commit
on a bare repository, if only you supply a dummy work directory using the --work-tree
option.
Prepare a dummy directory:
$ rm -rf /tmp/empty_directory
$ mkdir /tmp/empty_directory
Create the master
branch without a parent (works even on a completely empty repo):
$ cd your-bare-repository.git
$ git checkout --work-tree=/tmp/empty_directory --orphan master
Switched to a new branch 'master' <--- abort if "master" already exists
Create a commit (it can be a message-only, without adding any files, because what you need is simply having at least one commit):
$ git commit -m "Initial commit" --allow-empty --work-tree=/tmp/empty_directory
$ git branch
* master
Clean up the directory, it is still empty.
$ rmdir /tmp/empty_directory
Tested on git 1.9.1. (Specifically for OP, the posh-git is just a PowerShell wrapper for standard git.)
In Solution Explorer open packages.config and find Microsoft.AspNet.MVC:
package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net461"
From the above we can see it's an Asp.Net MVC 5.2.3 Version.
Moreover packages.config file also helps us to track all the installed packages with their respective versions.
Just add a default value of none
to $inset - so
@mixin box-shadow($top, $left, $blur, $color, $inset: none) { ....
Now when no $inset is passed nothing will be displayed.
I assume you're using GCC. The standard solution would be to profile with gprof.
Be sure to add -pg
to compilation before profiling:
cc -o myprog myprog.c utils.c -g -pg
I haven't tried it yet but I've heard good things about google-perftools. It is definitely worth a try.
Related question here.
A few other buzzwords if gprof
does not do the job for you: Valgrind, Intel VTune, Sun DTrace.
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
It is because generics were added on to java after they made it, so its kinda clunky because the original makers of java thought that when making an array the type would be specified in the making of it. So that does not work with generics so you have to do E[] array=(E[]) new Object[15]; This compiles but it gives a warning.
VanDyke VShell is the best Windows SSH Server I've ever worked with. It is kind of expensive though ($250). If you want a free solution, freeSSHd works okay. The CYGWIN solution is always an option, I've found, however, that it is a lot of work & overhead just to get SSH.
In my case addInterceptor()
didn't work to add HTTP headers to my request, I had to use addNetworkInterceptor()
. Code is as follows:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addNetworkInterceptor(new AddHeaderInterceptor());
And the interceptor code:
public class AddHeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("Authorization", "MyauthHeaderContent");
return chain.proceed(builder.build());
}
}
This and more examples on this gist
Hello in Centos 7 firewall-cmd. Yes correct if you use firewall-cmd --zone=public --add-port=2888/tcp but if you reload firewal firewall-cmd --reload
your config not will be save
you need to add key
firewall-cmd --permanent --zone=public --add-port=2888/tcp
Unfortunately using a list won't work in all situations. A list and an array are actually different and are not 100% interchangeable. It would depend on the circumstances if this would be an acceptable work around.
Many questions get answers if we use .Net Reflector
to see the actual code of SqlConnection
:)
true
and sspi
are the same:
internal class DbConnectionOptions
...
internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
if ((CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true")) || CompareInsensitiveInvariant(stringValue, "yes"))
{
return true;
}
}
...
EDIT 20.02.2018 Now in .Net Core we can see its open source on github! Search for ConvertValueToIntegratedSecurityInternal method:
I wanted to clarify some more use between the ;
and the /
In SQLPLUS:
;
means "terminate the current statement, execute it and store it to the SQLPLUS buffer"<newline>
after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;
), it means, store the statement to the buffer but do not run it./
after entering a statement into the buffer (with a blank <newline>
) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.RUN
or R
is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement./
during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"NOTE: Because ;
are used for PL/SQL to end a statement ;
cannot be used by SQLPLUS to mean "terminate the current statement, execute it and store it to the SQLPLUS buffer" because we want the whole PL/SQL block to be completely in the buffer, then execute it. PL/SQL blocks must end with:
END;
/
This is my solution for your reference:
struct Foo
{
Foo(){}//used to make compiler happy!
Foo(int x){/*...*/}
};
struct Bar
{
Foo foo[3];
Bar()
{
//initialize foo array here:
for(int i=0;i<3;++i)
{
foo[i]=Foo(4+i);
}
}
};
Jquery code which contains simple ajax :
$("#product").on("input", function(event) {
var data=$("#nameform").serialize();
$.post("./__partails/search-productbyCat.php",data,function(e){
$(".result").empty().append(e);
});
});
Html elements you can use any element:
<form id="nameform">
<input type="text" name="product" id="product">
</form>
php Code:
$pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
$Catagoryf=$_POST['product'];
$pricef=$_POST['price'];
$colorf=$_POST['color'];
$stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
$stmtcat->execute(array($Catagoryf));
while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
$iddb=$result['ID'];
$namedb=$result['Name'];
$pricedb=$result['Price'];
$colordb=$result['Color'];
echo "<tr>";
echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>';
echo "<td><pre>$pricedb</pre></td>";
echo "<td><pre> $colordb</pre>";
echo "</tr>";
The easy way
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :) See these examples for simpler transforms. this has left point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
This has right skew point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
In Android, the structure is different from .NET:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Hello!")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Handle Ok
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Handle Cancel
}
})
.create();
Will get you a dialog with two buttons and you handle the button clicks with callbacks. You might be able to write some code to make the syntax more closely resemble .NET, but the dialog lifecycle is pretty intertwined with Activity
, so in the end, it might be more trouble than it's worth. Additional dialog references are here.
Add this to your dependencies in build.gradle
:
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
...
The latest version can be found here
Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project
Take a look at your libraries folder, the library you just added should be in there.
Looks like the DATEFIRST settings is the only way, but it's not possible to make a SET statement in a scalar/table valued function. Therefore, it becomes very error-prone to the colleagues following your code. (become a trap to the others)
In fact, SQL server datepart function should be improved to accept this as parameter instead.
At the meantime, it looks like using the English Name of the week is the safest choice.
<?php
function fWriteFile($sFileName,$sFileContent="No Data",$ROOT)
{
$word = new COM("word.application") or die("Unable to instantiate Word");
//bring it to front
$word->Visible = 1;
//open an empty document
$word->Documents->Add();
//do some weird stuff
$word->Selection->TypeText($sFileContent);
$word->Documents[1]->SaveAs($ROOT."/".$sFileName.".doc");
//closing word
$word->Quit();
//free the object
$word = null;
return $sFileName;
}
?>
<?php
$PATH_ROOT=dirname(__FILE__);
$Return ="<table>";
$Return .="<tr><td>Row[0]</td></tr>";
$Return .="<tr><td>Row[1]</td></tr>";
$sReturn .="</table>";
fWriteFile("test",$Return,$PATH_ROOT);
?>
iloc
works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing
df.iloc[0]
or the last five rows by doing
df.iloc[-5:]
You can also use it on the columns. This retrieves the 3rd column:
df.iloc[:, 2] # the : in the first position indicates all rows
You can combine them to get intersections of rows and columns:
df.iloc[:3, :3] # The upper-left 3 X 3 entries (assuming df has 3+ rows and columns)
On the other hand, .loc
use named indices. Let's set up a data frame with strings as row and column labels:
df = pd.DataFrame(index=['a', 'b', 'c'], columns=['time', 'date', 'name'])
Then we can get the first row by
df.loc['a'] # equivalent to df.iloc[0]
and the second two rows of the 'date'
column by
df.loc['b':, 'date'] # equivalent to df.iloc[1:, 1]
and so on. Now, it's probably worth pointing out that the default row and column indices for a DataFrame
are integers from 0 and in this case iloc
and loc
would work in the same way. This is why your three examples are equivalent. If you had a non-numeric index such as strings or datetimes, df.loc[:5]
would raise an error.
Also, you can do column retrieval just by using the data frame's __getitem__
:
df['time'] # equivalent to df.loc[:, 'time']
Now suppose you want to mix position and named indexing, that is, indexing using names on rows and positions on columns (to clarify, I mean select from our data frame, rather than creating a data frame with strings in the row index and integers in the column index). This is where .ix
comes in:
df.ix[:2, 'time'] # the first two rows of the 'time' column
I think it's also worth mentioning that you can pass boolean vectors to the loc
method as well. For example:
b = [True, False, True]
df.loc[b]
Will return the 1st and 3rd rows of df
. This is equivalent to df[b]
for selection, but it can also be used for assigning via boolean vectors:
df.loc[b, 'name'] = 'Mary', 'John'
List<object>.AddRange(object[])
should do the trick. It will avoid all sorts of useless memory allocation.
You could also use Linq, somewhat like this: object[].Cast<object>().ToList()
Yes, for scalar values, a combination of implode and array_slice will do:
$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));
Or mix it up with array_values
and list
(thanks @nikic) so that it works with all types of values:
list($bar) = array_values(array_slice($array, 0, 1));
private static void getRepeatedNumbers() {
int [] numArray = {2,5,3,8,1,2,8,3,3,1,5,7,8,12,134};
Set<Integer> nums = new HashSet<Integer>();
for (int i =0; i<numArray.length; i++) {
if(nums.contains(numArray[i]))
continue;
int count =1;
for (int j = i+1; j < numArray.length; j++) {
if(numArray[i] == numArray[j]) {
count++;
}
}
System.out.println("The "+numArray[i]+ " is repeated "+count+" times.");
nums.add(numArray[i]);
}
}
If an Activity calls onPause
with a normal broadcast, receiving the Broadcast can be missed. A sticky broadcast can be checked after it was initiated in onResume
.
Sticky broadcasts are deprecated.
See sendStickyBroadcast
documentation.
This method was deprecated in API level 21.
Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
Intent intent = new Intent("some.custom.action");
intent.putExtra("some_boolean", true);
sendStickyBroadcast(intent);
Related post: What is the difference between sendStickyBroadcast and sendBroadcast in Android?
See removeStickyBroadcast(Intent)
, and on API Level 5 +, isInitialStickyBroadcast()
for usage in the Receiver's onReceive
.
Delete any or specific file type(for example ".bak") from a path. See demo code below -
class Program
{
static void Main(string[] args)
{
// Specify the starting folder on the command line, or in
TraverseTree(ConfigurationManager.AppSettings["folderPath"]);
// Specify the starting folder on the command line, or in
// Visual Studio in the Project > Properties > Debug pane.
//TraverseTree(args[0]);
Console.WriteLine("Press any key");
Console.ReadKey();
}
public static void TraverseTree(string root)
{
if (string.IsNullOrWhiteSpace(root))
return;
// Data structure to hold names of subfolders to be
// examined for files.
Stack<string> dirs = new Stack<string>(20);
if (!System.IO.Directory.Exists(root))
{
return;
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.GetDirectories(currentDir);
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
IEnumerable<FileInfo> files = null;
try
{
//get only .bak file
var directory = new DirectoryInfo(currentDir);
DateTime date = DateTime.Now.AddDays(-15);
files = directory.GetFiles("*.bak").Where(file => file.CreationTime <= date);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
foreach (FileInfo file in files)
{
try
{
// Perform whatever action is required in your scenario.
file.Delete();
Console.WriteLine("{0}: {1}, {2} was successfully deleted.", file.Name, file.Length, file.CreationTime);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
Console.WriteLine(e.Message);
continue;
}
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
foreach (string str in subDirs)
dirs.Push(str);
}
}
}
for more reference - https://msdn.microsoft.com/en-us/library/bb513869.aspx
NOTE: This should be considered a discussion rather than an actual answer.
An approximate approach is to operate __main__
in the module you want to create variables. For example there's a b.py
:
#!/usr/bin/env python
# coding: utf-8
def set_vars():
import __main__
print '__main__', __main__
__main__.B = 1
try:
print B
except NameError as e:
print e
set_vars()
print 'B: %s' % B
Running it would output
$ python b.py
name 'B' is not defined
__main__ <module '__main__' from 'b.py'>
B: 1
But this approach only works in a single module script, because the __main__
it import will always represent the module of the entry script being executed by python, this means that if b.py
is involved by other code, the B
variable will be created in the scope of the entry script instead of in b.py
itself. Assume there is a script a.py
:
#!/usr/bin/env python
# coding: utf-8
try:
import b
except NameError as e:
print e
print 'in a.py: B', B
Running it would output
$ python a.py
name 'B' is not defined
__main__ <module '__main__' from 'a.py'>
name 'B' is not defined
in a.py: B 1
Note that the __main__
is changed to 'a.py'
.
In C++ copying the object means cloning. There is no any special cloning in the language.
As the standard suggests, after copying you should have 2 identical copies of the same object.
There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.
You can simply check out a new branch, and then commit:
git checkout -b my_new_branch
git commit
Checking out the new branch will not discard your changes.
Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:
$.ajax({
type: "POST",
url: "index.php",
dataType: "json",
data: JSON.stringify({ paramName: info }),
success: function(msg){
$('.answer').html(msg);
}
});
You just need to make sure you include the JSON2.js file in your page...
git add --all my/awesome/stuff/
works for me. [1]
text/javascript
is obsolete, and application/x-javascript
was experimental (hence the x-
prefix) for a transitional period until application/javascript
could be standardised.
You should use application/javascript
. This is documented in the RFC.
As far a browsers are concerned, there is no difference (at least in HTTP headers). This was just a change so that the text/*
and application/*
MIME type groups had a consistent meaning where possible. (text/*
MIME types are intended for human readable content, JavaScript is not designed to directly convey meaning to humans).
Note that using application/javascript
in the type
attribute of a script element will cause the script to be ignored (as being in an unknown language) in some older browsers. Either continue to use text/javascript
there or omit the attribute entirely (which is permitted in HTML 5).
This isn't a problem in HTTP headers as browsers universally (as far as I'm aware) either ignore the HTTP content-type of scripts entirely, or are modern enough to recognise application/javascript
.
You can read an article i have written for joins in LINQ here
var query =
from u in Repo.T_Benutzer
join bg in Repo.T_Benutzer_Benutzergruppen
on u.BE_ID equals bg.BEBG_BE
into temp
from j in temp.DefaultIfEmpty()
select new
{
BE_User = u.BE_User,
BEBG_BG = (int?)j.BEBG_BG// == null ? -1 : j.BEBG_BG
//, bg.Name
}
The following is the equivalent using extension methods:
var query =
Repo.T_Benutzer
.GroupJoin
(
Repo.T_Benutzer_Benutzergruppen,
x=>x.BE_ID,
x=>x.BEBG_BE,
(o,i)=>new {o,i}
)
.SelectMany
(
x => x.i.DefaultIfEmpty(),
(o,i) => new
{
BE_User = o.o.BE_User,
BEBG_BG = (int?)i.BEBG_BG
}
);
If yes_ans > no_ans and yes_ans > na_ans
You're using column names in a statement (outside of a query). If you want variables, you must declare and assign them.
use this code
private ClipboardManager myClipboard;
private ClipData myClip;
TextView textView;
Button copyText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
textView = (TextView) findViewById(R.id.textview);
copyText = (Button) findViewById(R.id.bCopy);
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
copyText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = textView.getText().toString();
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);
Toast.makeText(getApplicationContext(), "Text Copied",
Toast.LENGTH_SHORT).show();
}
});
}
CSS
body {
background: rgb(204,204,204);
}
page[size="A4"] {
background: white;
width: 21cm;
height: 29.7cm;
display: block;
margin: 0 auto;
margin-bottom: 0.5cm;
box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
@media print {
body, page[size="A4"] {
margin: 0;
box-shadow: 0;
}
}
HTML
<page size="A4"></page>
<page size="A4"></page>
<page size="A4"></page>
Yet another trick (as of v1.6)
A=np.arange(1,10).reshape(3,3)
b=np.arange(3)
np.einsum('ij,i->ij',A,b)
I'm proficient with the numpy broadcasting (newaxis
), but I'm still finding my way around this new einsum
tool. So I had play around a bit to find this solution.
Timings (using Ipython timeit):
einsum: 4.9 micro
transpose: 8.1 micro
newaxis: 8.35 micro
dot-diag: 10.5 micro
Incidentally, changing a i
to j
, np.einsum('ij,j->ij',A,b)
, produces the matrix that Alex does not want. And np.einsum('ji,j->ji',A,b)
does, in effect, the double transpose.
date -j -f "%Y-%m-%d %H:%M:%S" "2020-04-07 00:00:00" "+%s"
It will print the dynamic seconds when without %H:%M:%S
and 00:00:00
.
DT[order(-x)]
works as expected. I have data.table version 1.9.4. Maybe this was fixed in a recent version.
Also, I suggest the setorder(DT, -x)
syntax in keeping with the set* commands like setnames
, setkey
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<fork>true</fork>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
this problem arises when we use vectors in place of scalars for example in a for loop the range should be a scalar, in case you have given a vector in that place you get error. So to avoid the problem use the length of the vector you have used
I believe it is because cell.getCellStyle
initially returns the default cell style which you then change.
Create styles like this and apply them to cells:
cellStyle = (XSSFCellStyle) cell.getSheet().getWorkbook().createCellStyle();
Although as the previous poster noted try and create styles and reuse them.
There is also some utility class in the XSSF library that will avoid the code I have provided and automatically try and reuse styles. Can't remember the class 0ff hand.
var myElem = document.getElementById('myElementId');
if (myElem === null) alert('does not exist!');
You have a lot of reading ahead of you. From compiler errors through exception handling, threading and thread interruptions. But this will do what you want:
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
You can get this error if docker doesn't shut down cleanly. The following answer is for the docker snap package.
Run snap logs docker
and look for the following:
Error starting daemon: pid file found, ensure docker is not running or delete /var/snap/docker/179/run/docker.pid
Deleting that file and restarting docker worked for me.
rm /var/snap/docker/<your-version-number>/run/docker.pid
snap stop docker
snap start docker
Make sure to replace ????<your-version-number>?
with the appropriate version number.
I was experiencing this issue due to the misconfiguration of my Apple Worldwide Developer Relations Certification Authority certificate.
I resolved issue by switching from "Alway Trust" to "Use System Defaults"
Step by Step:
I know i am late to the party but hope this helps someone who will do the same with Class binding
var newEntry = new MyClassObject();
var bindingSource = dataGridView.DataSource as BindingSource;
var myClassObjects = bindingSource.DataSource as List<MyClassObject>;
myClassObjects.Add(newEntry);
bindingSource.DataSource = myClassObjects;
dataGridView.DataSource = null;
dataGridView.DataSource = bindingSource;
dataGridView.Update();
dataGridView.Refresh();
I much prefer to use sprintf
which is available in base R.
sprintf("%0.1f%%", .7293827 * 100)
[1] "72.9%"
I especially like sprintf
because you can also insert strings.
sprintf("People who prefer %s over %s: %0.4f%%",
"Coke Classic",
"New Coke",
.999999 * 100)
[1] "People who prefer Coke Classic over New Coke: 99.9999%"
It's especially useful to use sprintf
with things like database configurations; you just read in a yaml file, then use sprintf to populate a template without a bunch of nasty paste0
's.
This pattern is especially useful for rmarkdown reports, when you have a lot of text and a lot of values to aggregate.
Setup / aggregation:
library(data.table) ## for aggregate
approval <- data.table(year = trunc(time(presidents)),
pct = as.numeric(presidents) / 100,
president = c(rep("Truman", 32),
rep("Eisenhower", 32),
rep("Kennedy", 12),
rep("Johnson", 20),
rep("Nixon", 24)))
approval_agg <- approval[i = TRUE,
j = .(ave_approval = mean(pct, na.rm=T)),
by = president]
approval_agg
# president ave_approval
# 1: Truman 0.4700000
# 2: Eisenhower 0.6484375
# 3: Kennedy 0.7075000
# 4: Johnson 0.5550000
# 5: Nixon 0.4859091
Using sprintf
with vectors of text and numbers, outputting to cat
just for newlines.
approval_agg[, sprintf("%s approval rating: %0.1f%%",
president,
ave_approval * 100)] %>%
cat(., sep = "\n")
#
# Truman approval rating: 47.0%
# Eisenhower approval rating: 64.8%
# Kennedy approval rating: 70.8%
# Johnson approval rating: 55.5%
# Nixon approval rating: 48.6%
Finally, for my own selfish reference, since we're talking about formatting, this is how I do commas with base R:
30298.78 %>% round %>% prettyNum(big.mark = ",")
[1] "30,299"
Good question. Yes, one can do this more efficiently. Your CPU can extract both the quotient and the remainder of the ratio of two integers in a single operation. In <stdlib.h>
, the function that exposes this CPU operation is called div()
. In your psuedocode, you'd use it something like this:
function to_tuple(x):
qr = div(x, 1000)
ms = qr.rem
qr = div(qr.quot, 60)
s = qr.rem
qr = div(qr.quot, 60)
m = qr.rem
h = qr.quot
A less efficient answer would use the /
and %
operators separately. However, if you need both quotient and remainder, anyway, then you might as well call the more efficient div()
.
UPDATED
For python 3, you should use items()
instead of iteritems()
PYTHON 2
for attr, value in k.__dict__.iteritems():
print attr, value
PYTHON 3
for attr, value in k.__dict__.items():
print(attr, value)
This will print
'names', [a list with names]
'tweet', [a list with tweet]
'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';
Try using an SVG file, it seems to have better browser compatibility, and won't break your responsive designs.
I tried the CSS transform, and had much trouble with the transform-origin; and ended up going with an SVG file. It took like 10 minutes, and I could control it a bit with CSS too.
You can use Inkscape to make the SVG if you don't have Adobe Illustrator.
I had the same issue on a Windows 10 PC. I copied the project from my old computer to the new one, both 64 bits, and I installed the Oracle Client 64 bit on the new machine. I got the same error message, but after trying many solutions to no effect, what actually worked for me was this: In your Visual Studio (mine is 2017) go to Tools > Options > Projects and Solutions > Web Projects
On that page, check the option that says: Use the 64 bit version of IIS Express for Websites and Projects
My solution, only need to call this method.
public static void dropColumn(SQLiteDatabase db, String tableName, String[] columnsToRemove) throws java.sql.SQLException {
List<String> updatedTableColumns = getTableColumns(db, tableName);
updatedTableColumns.removeAll(Arrays.asList(columnsToRemove));
String columnsSeperated = TextUtils.join(",", updatedTableColumns);
db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");
db.execSQL("CREATE TABLE " + tableName + " (" + columnsSeperated + ");");
db.execSQL("INSERT INTO " + tableName + "(" + columnsSeperated + ") SELECT "
+ columnsSeperated + " FROM " + tableName + "_old;");
db.execSQL("DROP TABLE " + tableName + "_old;");
}
And auxiliary method to get the columns:
public static List<String> getTableColumns(SQLiteDatabase db, String tableName) {
ArrayList<String> columns = new ArrayList<>();
String cmd = "pragma table_info(" + tableName + ");";
Cursor cur = db.rawQuery(cmd, null);
while (cur.moveToNext()) {
columns.add(cur.getString(cur.getColumnIndex("name")));
}
cur.close();
return columns;
}
Html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="x" content="xx" />
vs Php:
<?php header('Content-type: text/html; charset=ISO-8859-1'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta name="x" content="xx" />
You are looking for the DateTime.Parse()
method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime
typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact
(MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
If the format is that simple (a space separates the number from the rest) then
int(str1.split()[0])
would do it
It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.
@Request/View/Flow/Session/ApplicationScoped
A @RequestScoped
bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped
bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null
/void
without any navigation/redirect. A @FlowScoped
bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped
bean lives as long as the established HTTP session. An @ApplicationScoped
bean lives as long as the web application runs. Note that the CDI @Model
is basically a stereotype for @Named @RequestScoped
, so same rules apply.
Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped
for simple and non-ajax forms/presentations. Use @ViewScoped
for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped
for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped
for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped
for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.
Abusing an @ApplicationScoped
bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped
bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped
bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped
bean for request, session or application scoped data, and abusing a @SessionScoped
bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.
Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped
beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty
in case of JSF managed beans or @Inject
in case of CDI managed beans.
@CustomScoped/NoneScoped/Dependent
It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped
and @NoneScoped
, which are rarely used in real world. The @CustomScoped
must refer a custom Map<K, Bean>
implementation in some broader scope which has overridden Map#put()
and/or Map#get()
in order to have more fine grained control over bean creation and/or destroy.
The JSF @NoneScoped
and CDI @Dependent
basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped
or @Dependent
is injected in a @SessionScoped
, then it will live as long as the @SessionScoped
bean.
As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.
This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped
. The flash scope is only available as a map via ExternalContext#getFlash()
in managed beans and #{flash}
in EL.
intersect_all <- function(a,b,...){
all_data <- c(a,b,...)
require(plyr)
count_data<- length(list(a,b,...))
freq_dist <- count(all_data)
intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
intersect_data
}
intersect_all(a,b,c)
UPDATE EDIT A simpler code
intersect_all <- function(a,b,...){
Reduce(intersect, list(a,b,...))
}
intersect_all(a,b,c)
If you are on osx and using an emulator, you can view your console.log
s directly in safari web inspector.
Safari => Development => Simulator - [your simulator version here] => JSContext
It's not "plumbing", but it'll do exactly what you want:
$ git log --format=%B -n 1 <commit>
If you absolutely need a "plumbing" command (not sure why that's a requirement), you can use rev-list
:
$ git rev-list --format=%B --max-count=1 <commit>
Although rev-list
will also print out the commit sha (on the first line) in addition to the commit message.
I see this is old but... I dont know if you are looking for code to generate the numbers/options every time its loaded or not. But I use an excel or open office calc page and place use the auto numbering all the time. It may look like this...
| <option>
| 1 | </option>
|
Then I highlight the cells in the row and drag them down until there are 100 or the number that I need. I now have code snippets that I just refer back to.
You can use like this...
<div id="rot">hello</div>
#rot
{
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
width:100px;
}
Have a look at this fiddle:http://jsfiddle.net/anish/MAN4g/
We're not necessarily talking theoretical limits here, we're talking about real world limits of the 2GB max file size AND database schema.
The schema is on even footing with the row count in determining how many rows you can have.
We have used Access MDBs to store exports of MS-SQL data for statistical analysis by some of our corporate users. In those cases we've exported our core table structure, typically four tables with 20 to 150 columns varying from a hundred bytes per row to upwards of 8000 bytes per row. In these cases, we would bump up against a few hundred thousand rows of data were permissible PER MDB that we would ship them.
So, I just don't think that this question has an answer in absence of your schema.
You can use the following class for bootstrap 4:
mt-0
mt-1
mt-2
mt-3
mt-4
...
You could also expose the directive's controller to the parent scope, like ngForm
with name
attribute does: http://docs.angularjs.org/api/ng.directive:ngForm
Here you could find a very basic example how it could be achieved http://plnkr.co/edit/Ps8OXrfpnePFvvdFgYJf?p=preview
In this example I have myDirective
with dedicated controller with $clear
method (sort of very simple public API for the directive). I can publish this controller to the parent scope and use call this method outside the directive.
IOC (Inversion Of Control): Giving control to the container to get an instance of the object is called Inversion of Control, means instead of you are creating an object using the new operator, let the container do that for you.
DI (Dependency Injection): Way of injecting properties to an object is called Dependency Injection.
We have three types of Dependency Injection:
Spring supports only Constructor Injection and Setter/Getter Injection.
If you removed the make all
line from your "fresh" target:
fresh :
rm -f *.o $(EXEC)
clear
You could simply run the command make fresh all
, which will execute as make fresh; make all
.
Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.
Okay, I think I know what you're looking for. It appears that GGT is a pretty good solution, as Reed Copsey suggested.
Personally, we rolled our own little library, because we deal with rational points a lot - lots of rational NURBS and Beziers.
It turns out that most 3D graphics libraries do computations with projective points that have no basis in projective math, because that's what gets you the answer you want. We ended up using Grassmann points, which have a solid theoretical underpinning and decreased the number of point types. Grassmann points are basically the same computations people are using now, with the benefit of a robust theory. Most importantly, it makes things clearer in our minds, so we have fewer bugs. Ron Goldman wrote a paper on Grassmann points in computer graphics called "On the Algebraic and Geometric Foundations of Computer Graphics".
Not directly related to your question, but an interesting read.
Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores
Some of the basic data structures in programming languages such as C and C++ are stacks and queues.
The stack data structure follows the "First In Last Out" policy (FILO) where the first element inserted or "pushed" into a stack is the last element that is removed or "popped" from the stack.
Similarly, a queue data structure follows a "First In First Out" policy (as in the case of a normal queue when we stand in line at the counter), where the first element is pushed into the queue or "Enqueued" and the same element when it has to be removed from the queue is "Dequeued".
This is quite similar to push and pop in a stack, but the terms enqueue and dequeue avoid confusion as to whether the data structure in use is a stack or a queue.
Class coders has a simple program to demonstrate the enqueue and dequeue process. You could check it out for reference.
http://classcoders.blogspot.in/2012/01/enque-and-deque-in-c.html
The newly released PyCharm 5 supports type hinting. In their blog post about it (see Python 3.5 type hinting in PyCharm 5) they offer a great explanation of what type hints are and aren't along with several examples and illustrations for how to use them in your code.
Additionally, it is supported in Python 2.7, as explained in this comment:
PyCharm supports the typing module from PyPI for Python 2.7, Python 3.2-3.4. For 2.7 you have to put type hints in *.pyi stub files since function annotations were added in Python 3.0.
IIS express configuration is managed by applicationhost.config.
You can find it in
Users\<username>\Documents\IISExpress\config folder.
Inside you can find the sites section that hold a section for each IIS Express configured site.
Add (or modify) a site section like this:
<site name="WebSiteWithVirtualDirectory" id="20">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="c:\temp\website1" />
</application>
<application path="/OffSiteStuff" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="d:\temp\SubFolderApp" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:1132:localhost" />
</bindings>
</site>
Practically you need to add a new application tag in your site for each virtual directory. You get a lot of flexibility because you can set different configuration for the virtual directory (for example a different .Net Framework version)
EDIT Thanks to Fevzi Apaydin to point to a more elegant solution.
You can achieve same result by adding one or more virtualDirectory tag to the Application tag:
<site name="WebSiteWithVirtualDirectory" id="20">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="c:\temp\website1" />
<virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:1132:localhost" />
</bindings>
</site>
Reference:
->
calls/sets object variables. Ex:
$obj = new StdClass;
$obj->foo = 'bar';
var_dump($obj);
=> Sets key/value pairs for arrays. Ex:
$array = array(
'foo' => 'bar'
);
var_dump($array);
select top 0 *
into #mytemptable
from myrealtable
You can use
$("#btnAddProfile").text('Save');
although
$("#btnAddProfile").html('Save');
would work as well, but it's misleading (it gives the impression you could write something like
$("#btnAddProfile").html('Save <b>now</b>');
but of course you can't
You can pass the arraylist from one activity to another by using bundle with intent. Use the code below This is the shortest and most suitable way to pass arraylist
bundle.putStringArrayList("keyword",arraylist);
I suggest:
writeLines(c("Hello","World"), "output.txt")
It is shorter and more direct than the current accepted answer. It is not necessary to do:
fileConn<-file("output.txt")
# writeLines command using fileConn connection
close(fileConn)
Because the documentation for writeLines()
says:
If the
con
is a character string, the function callsfile
to obtain a file connection which is opened for the duration of the function call.
# default settings for writeLines(): sep = "\n", useBytes = FALSE
# so: sep = "" would join all together e.g.
Have a look at the class
org.joda.time.DateTime
This allows you to do things like:
old = new DateTime();
new = old.plusSeconds(500000);
System.out.println("Hours: " + (new.Hours() - old.Hours()));
However, your solution probably can be simpler:
You need to work out how many seconds in a day, divide your input by the result to get the days, and subtract it from the input to keep the remainder. You then need to work out how many hours in the remainder, followed by the minutes, and the final remainder is the seconds.
This is the analysis done for you, now you can focus on the code.
You need to ask what s/he means by "no hard coding", generally it means pass parameters, rather than fixing the input values. There are many ways to do this, depending on how you run your code. Properties are a common way in java.
Yes, this sort of thing is possible without Flash:
However, only very modern browsers supports HTML5 videos, and this should be your consideration when deploying in HTML 5, and you should provide a fallback (probably Flash or just omit the transparency).
Gson is also good for it: http://code.google.com/p/google-gson/
" Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. "
Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Options -Indexes
I have to try create .htaccess file that current directory that i want to disallow directory index listing. But, sorry i don't know about recursive in .htaccess code.
Try it.
You can use SystemSound, for example, System.Media.SystemSounds.Asterisk.Play();
.
Just for completeness, let's not forget the Simplest Thing That Could Possibly Work:
for i in list:
if i.n == 5:
# do something with it
print "YAY! Found one!"
As you comment in your question, awk
is really the way to go. To use cut
is possible together with tr -s
to squeeze spaces, as kev's answer shows.
Let me however go through all the possible combinations for future readers. Explanations are at the Test section.
tr -s ' ' < file | cut -d' ' -f4
awk '{print $4}' file
while read -r _ _ _ myfield _
do
echo "forth field: $myfield"
done < file
sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' file
Given this file, let's test the commands:
$ cat a
this is line 1 more text
this is line 2 more text
this is line 3 more text
this is line 4 more text
$ cut -d' ' -f4 a
is
# it does not show what we want!
$ tr -s ' ' < a | cut -d' ' -f4
1
2 # this makes it!
3
4
$
$ awk '{print $4}' a
1
2
3
4
This reads the fields sequentially. By using _
we indicate that this is a throwaway variable as a "junk variable" to ignore these fields. This way, we store $myfield
as the 4th field in the file, no matter the spaces in between them.
$ while read -r _ _ _ a _; do echo "4th field: $a"; done < a
4th field: 1
4th field: 2
4th field: 3
4th field: 4
This catches three groups of spaces and no spaces with ([^ ]*[ ]*){3}
. Then, it catches whatever coming until a space as the 4th field, that it is finally printed with \1
.
$ sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' a
1
2
3
4
Use something like the following on the server side:
http.createServer(function (request, response) {
if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
// handle async request
var u = url.parse(request.url, true); //not needed
response.writeHead(200, {'content-type':'text/json'})
response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
} else {
// handle sync request (by server index.html)
if (request.url == '/') {
response.writeHead(200, {'content-type': 'text/html'})
util.pump(fs.createReadStream('index.html'), response)
}
else
{
// 404 error
}
}
}).listen(31337)
I believe this is what you're looking for:
char[] characters = "this is a test".ToCharArray();
Simple and easy!
get_queried_object_id()
The easiest and the most straightforward way:
To activate: File > Settings > Editor > General
For Mac OS X
, Android Studio > Preferences > Editor > General and check Show quick documentation on mouse move:
Other ways:
You can go into your IntelliJ's bin folder and search for idea.properties. Add this line to the document:
auto.show.quick.doc=true
Now you'll have the same floating docs window like in Eclipse.
You have to press CTRL+Q to see the Javadoc.
You can pin the window and make the documentation appear every time you select a method with your mouse though.
Android Studio 1.0: You have to hold CTRL if you want to get hold of documentation window for e.g. scrolling documentation otherwise as you move your mouse away from method documentation window will disappear.
tr.rowhighlight td, tr.rowhighlight th{
background-color:#f0f8ff;
}
Class that will call the methods:
namespace myNamespace
{
public class myClass
{
public static void voidMethodWithoutParameters()
{
// code here
}
public static string stringReturnMethodWithParameters(string param1, string param2)
{
// code here
return "output";
}
}
}
Calling myClass static methods using Reflection:
var myClassType = Assembly.GetExecutingAssembly().GetType(GetType().Namespace + ".myClass");
// calling my void Method that has no parameters.
myClassType.GetMethod("voidMethodWithoutParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
// calling my string returning Method & passing to it two string parameters.
Object methodOutput = myClassType.GetMethod("stringReturnMethodWithParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { "value1", "value1" });
Console.WriteLine(methodOutput.ToString());
Note: I don't need to instantiate an object of myClass to use it's methods, as the methods I'm using are static
.
Great resources:
For Python 3.5+ use:
import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()
For Python 3.3 and 3.4 use:
from importlib.machinery import SourceFileLoader
foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()
(Although this has been deprecated in Python 3.4.)
For Python 2 use:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
There are equivalent convenience functions for compiled Python files and DLLs.
See also http://bugs.python.org/issue21436.
I had also try to many solution but make some changes it will work
host = smtp.gmail.com
port = 587
username = [email protected]
password = password
enabledssl = true
with smtpclient above parameters are work in gmail
To let MySql generate sequence numbers for an AUTO_INCREMENT
field you have three options:
...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.
These three statements will produce the same result:
$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";
f = open('words.txt')
for word in f.read().split():
print(word)
Best to use JSON.stringify()
to cover all your bases, like backslashes and other special characters. Here's your original function with that in place instead of modifying strInputString
:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
eval(strTest);
alert(strResult);
}
(This way your strInputString
could be something like \\\'\"'"''\\abc'\
and it will still work fine.)
Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.
Another solution is to use linear layouts and set dividers between rows and cells like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#8000"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
></LinearLayout>
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"></LinearLayout>
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#8000"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
></LinearLayout>
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"></LinearLayout>
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#8000"/>
</LinearLayout>
It's a dirty solution, but it's simple and also works with transparent background and borders.
Calculate Leave working days in a table column as a default value--updated
If you are using SQL here is the query which can help you: http://gallery.technet.microsoft.com/Calculate...
I would suggest:
std::cout << setbase(16) << 32;
Taken from: http://www.cprogramming.com/tutorial/iomanip.html
You can use curl
or wget
to retrieve the raw data, or you can use w3m -dump
to have a nice text representation of a web page.
$ foo=$(w3m -dump http://www.example.com/); echo $foo
You have reached this web page by typing "example.com", "example.net","example.org" or "example.edu" into your web browser. These domain names are reserved for use in documentation and are not available for registration. See RFC 2606, Section 3.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
You should not trust $_FILES['upfile']['mime']
, check MIME type by yourself. For that purpose, you may use fileinfo
extension, enabled by default as of PHP 5.3.0.
$fileInfo = new finfo(FILEINFO_MIME_TYPE);
$fileMime = $fileInfo->file($_FILES['upfile']['tmp_name']);
$validMimes = array(
'zip' => 'application/zip',
'rar' => 'application/x-rar',
);
$fileExt = array_search($fileMime, $validMimes, true);
if($fileExt != 'zip' && $fileExt != 'rar')
throw new RuntimeException('Invalid file format.');
NOTE: Don't forget to enable the extension in your php.ini
and restart your server:
extension=php_fileinfo.dll
The click event is not bound to your new element, use a jQuery.on
to handle the click.
you can check ZBarSDK to reads QR Code and ECN/ISBN codes it's simple to integrate try the following code.
- (void)scanBarcodeWithZBarScanner
{
// ADD: present a barcode reader that scans from the camera feed
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;
ZBarImageScanner *scanner = reader.scanner;
// TODO: (optional) additional reader configuration here
// EXAMPLE: disable rarely used I2/5 to improve performance
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
//Get the return value from controller
[reader setReturnBlock:^(BOOL value) {
}
and in didFinishPickingMediaWithInfo we get bar code value.
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
// ADD: get the decode results
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
// EXAMPLE: just grab the first barcode
break;
// EXAMPLE: do something useful with the barcode data
barcodeValue = symbol.data;
// EXAMPLE: do something useful with the barcode image
barcodeImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[_barcodeIV setImage:barcodeImage];
//set the values for to TextFields
[self setBarcodeValue:YES];
// ADD: dismiss the controller (NB dismiss from the *reader*!)
[reader dismissViewControllerAnimated:YES completion:nil];
}
$("#radio1").attr('checked', true).trigger('click');
See this post it looks like you can use UIGetScreenImage(
) for now.