What about CassandraDB, Project Voldemort, TokyoCabinet?
Either
or
Which one you use is up to you, depending how much performance and how much stability you need.
The developer of H2 has put up a nice performance evaluation:
http://www.h2database.com/html/performance.html
try this,
Uri imageUri = Uri.parse("android.resource://your.package/drawable/fileName");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(intent , "Share"));
<td class="first"> <?php echo $proxy ?> </td>
is inside a literal string that you are echo
ing. End the string, or concatenate it correctly:
<td class="first">' . $proxy . '</td>
If you have access to other AMD gpu's please see here: https://github.com/ROCmSoftwarePlatform/hiptensorflow/tree/hip/rocm_docs
This should get you going in the right direction for tensorflow on the ROCm platform, but Selly's post about https://rocm.github.io/hardware.html is the deal with this route. That page is not an exhaustive list, I found out on my own that the Xeon E5 v2 Ivy Bridge works fine with ROCm even though they list v3 or newer, graphics cards however are a bit more picky. gfx8 or newer with a few small exceptions, polaris and maybe others as time goes on.
UPDATE - It looks like hiptensorflow has an option for opencl support during configure. I would say investigate the link even if you don't have gfx8+ or polaris gpu if the opencl implementation works. It is a long winded process but an hour or three (depending on hardware) following a well written instruction isn't too much to lose to find out.
Follow these steps:
Microsoft Access Database Engine 2016 Redistributable
and installSomewhere, you need to tell Apache that people are allowed to see contents of this directory.
<Directory "F:/bar/public">
Order Allow,Deny
Allow from All
# Any other directory-specific stuff
</Directory>
Try this:
require 'open-uri'
open('image.png', 'wb') do |file|
file << open('http://example.com/image.png').read
end
You have to catch the error just as you're already doing for your save()
call and since you're handling multiple errors here, you can try
multiple calls sequentially in a single do-catch block, like so:
func deleteAccountDetail() {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
do {
let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
} catch {
print(error)
}
}
Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws
then try
to call the method. For example:
func deleteAccountDetail() throws {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
}
Use
//$arr should be array as you mentioned as below
foreach($arr as $key=>$value){
echo $value->sm_id;
}
OR
//$arr should be array as you mentioned as below
foreach($arr as $value){
echo $value->sm_id;
}
The amount of "neurons", or "cells", or whatever the layer has inside it.
It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:
Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.
Ex: a shape (30,4,10)
means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.
What flows between layers are tensors. Tensors can be seen as matrices, with shapes.
In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.
Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3)
. Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).
Each type of layer requires the input with a certain number of dimensions:
Dense
layers require inputs as (batch_size, input_size)
(batch_size, optional,...,optional, input_size)
channels_last
: (batch_size, imageside1, imageside2, channels)
channels_first
: (batch_size, channels, imageside1, imageside2)
(batch_size, sequence_length, features)
Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.
All the other shapes are calculated automatically based on the units and particularities of each layer.
Given the input shape, all other shapes are results of layers calculations.
The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).
Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)
Let's show what happens with "Dense" layers, which is the type shown in your graph.
A dense layer has an output shape of (batch_size,units)
. So, yes, units, the property of the layer, also defines the output shape.
(batch_size,4)
. (batch_size,4)
. (batch_size,1)
. Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.
In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.
In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.
Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3)
.
Since the input shape is the only one you need to define, Keras will demand it in the first layer.
But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:
input_shape = (50,50,3)
#regardless of how many images I have, each image has this shape
Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3)
or batch_shape=(30,50,50,3)
. This limits your training possibilities to this unique batch size, so it should be used only when really required.
Either way you choose, tensors in the model will have the batch dimension.
So, even if you used input_shape=(50,50,3)
, when keras sends you messages, or when you print the model summary, it will show (None,50,50,3)
.
The first dimension is the batch size, it's None
because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None
)
Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.
input_shape=(50,50,3)
(30,50,50,3)
(None,50,50,3)
or (30,50,50,3)
, depending on what type of message it sends you. And in the end, what is dim
?
If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim
as a scalar number.
So, in your model, where your input layer has 3 elements, you can use any of these two:
input_shape=(3,)
-- The comma is necessary when you have only one dimension input_dim = 3
But when dealing directly with the tensors, often dim
will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.
Keras has two ways of doing it, Sequential
models, or the functional API Model
. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.
PS: here I ignored other aspects, such as activation functions.
With the Sequential model:
from keras.models import Sequential
from keras.layers import *
model = Sequential()
#start from the first hidden layer, since the input is not actually a layer
#but inform the shape of the input, with 3 elements.
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input
#further layers:
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer
With the functional API Model:
from keras.models import Model
from keras.layers import *
#Start defining the input tensor:
inpTensor = Input((3,))
#create the layers and pass them the input tensor to get the output tensor:
hidden1Out = Dense(units=4)(inpTensor)
hidden2Out = Dense(units=4)(hidden1Out)
finalOut = Dense(units=1)(hidden2Out)
#define the model's start and end points
model = Model(inpTensor,finalOut)
Shapes of the tensors
Remember you ignore batch sizes when defining layers:
(None,3)
(None,4)
(None,4)
(None,1)
Okay, first things first.
There is no such thing as "variable declaration" or "variable initialization" in Python.
There is simply what we call "assignment", but should probably just call "naming".
Assignment means "this name on the left-hand side now refers to the result of evaluating the right-hand side, regardless of what it referred to before (if anything)".
foo = 'bar' # the name 'foo' is now a name for the string 'bar'
foo = 2 * 3 # the name 'foo' stops being a name for the string 'bar',
# and starts being a name for the integer 6, resulting from the multiplication
As such, Python's names (a better term than "variables", arguably) don't have associated types; the values do. You can re-apply the same name to anything regardless of its type, but the thing still has behaviour that's dependent upon its type. The name is simply a way to refer to the value (object). This answers your second question: You don't create variables to hold a custom type. You don't create variables to hold any particular type. You don't "create" variables at all. You give names to objects.
Second point: Python follows a very simple rule when it comes to classes, that is actually much more consistent than what languages like Java, C++ and C# do: everything declared inside the class
block is part of the class. So, functions (def
) written here are methods, i.e. part of the class object (not stored on a per-instance basis), just like in Java, C++ and C#; but other names here are also part of the class. Again, the names are just names, and they don't have associated types, and functions are objects too in Python. Thus:
class Example:
data = 42
def method(self): pass
Classes are objects too, in Python.
So now we have created an object named Example
, which represents the class of all things that are Example
s. This object has two user-supplied attributes (In C++, "members"; in C#, "fields or properties or methods"; in Java, "fields or methods"). One of them is named data
, and it stores the integer value 42
. The other is named method
, and it stores a function object. (There are several more attributes that Python adds automatically.)
These attributes still aren't really part of the object, though. Fundamentally, an object is just a bundle of more names (the attribute names), until you get down to things that can't be divided up any more. Thus, values can be shared between different instances of a class, or even between objects of different classes, if you deliberately set that up.
Let's create an instance:
x = Example()
Now we have a separate object named x
, which is an instance of Example
. The data
and method
are not actually part of the object, but we can still look them up via x
because of some magic that Python does behind the scenes. When we look up method
, in particular, we will instead get a "bound method" (when we call it, x
gets passed automatically as the self
parameter, which cannot happen if we look up Example.method
directly).
What happens when we try to use x.data
?
When we examine it, it's looked up in the object first. If it's not found in the object, Python looks in the class.
However, when we assign to x.data
, Python will create an attribute on the object. It will not replace the class' attribute.
This allows us to do object initialization. Python will automatically call the class' __init__
method on new instances when they are created, if present. In this method, we can simply assign to attributes to set initial values for that attribute on each object:
class Example:
name = "Ignored"
def __init__(self, name):
self.name = name
# rest as before
Now we must specify a name
when we create an Example
, and each instance has its own name
. Python will ignore the class attribute Example.name
whenever we look up the .name
of an instance, because the instance's attribute will be found first.
One last caveat: modification (mutation) and assignment are different things!
In Python, strings are immutable. They cannot be modified. When you do:
a = 'hi '
b = a
a += 'mom'
You do not change the original 'hi ' string. That is impossible in Python. Instead, you create a new string 'hi mom'
, and cause a
to stop being a name for 'hi '
, and start being a name for 'hi mom'
instead. We made b
a name for 'hi '
as well, and after re-applying the a
name, b
is still a name for 'hi '
, because 'hi '
still exists and has not been changed.
But lists can be changed:
a = [1, 2, 3]
b = a
a += [4]
Now b
is [1, 2, 3, 4] as well, because we made b
a name for the same thing that a
named, and then we changed that thing. We did not create a new list for a
to name, because Python simply treats +=
differently for lists.
This matters for objects because if you had a list as a class attribute, and used an instance to modify the list, then the change would be "seen" in all other instances. This is because (a) the data is actually part of the class object, and not any instance object; (b) because you were modifying the list and not doing a simple assignment, you did not create a new instance attribute hiding the class attribute.
My version is like this:
php on my server:
<?php
header('content-type: application/json; charset=utf-8');
$data = json_encode($_SERVER['REMOTE_ADDR']);
$callback = filter_input(INPUT_GET,
'callback',
FILTER_SANITIZE_STRING,
FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);
echo $callback . '(' . $data . ');';
?>
jQuery on the page:
var self = this;
$.ajax({
url: this.url + "getip.php",
data: null,
type: 'GET',
crossDomain: true,
dataType: 'jsonp'
}).done( function( json ) {
self.ip = json;
});
It works cross domain. It could use a status check. Working on that.
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
This worked for me: (notice that java 8 is required)
String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);
UserJsonParse is a class that shows gson how to parse the json formant.
class is like that:
public class UserJsonParser {
private String username;
private String name;
private String lastname;
private String mail;
private String pass1;
//then put setters and getters
}
the json string that is parsed is like that:
$jsonData: { "username": "testuser", "pass1": "clave1234" }
The rest of values (mail, lastname, name) are set to null
These answers are all way too complicated!
The way he wrote the method is fine. The problem is where he invoked the method. He did not include parentheses after the method name, so the compiler thought he was trying to get a value from a variable instead of a method.
In Visual Basic and Delphi, those parentheses are optional, but in C#, they are required. So, to correct the last line of the original post:
Console.WriteLine("{0}", x.fullNameMethod());
This answer will sum up almost all the queries about when to use List and Array:
The main difference between these two data types is the operations you can perform on them. For example, you can divide an array by 3 and it will divide each element of array by 3. Same can not be done with the list.
The list is the part of python's syntax so it doesn't need to be declared whereas you have to declare the array before using it.
You can store values of different data-types in a list (heterogeneous), whereas in Array you can only store values of only the same data-type (homogeneous).
Arrays being rich in functionalities and fast, it is widely used for arithmetic operations and for storing a large amount of data - compared to list.
Arrays take less memory compared to lists.
In my case, this happens when I try to save an object in hibernate or other orm-mapping with null property which can not be null in database table. This happens when you try to save an object, but the save action doesn't comply with the contraints of the table.
Format specifier in printf
should be %f
for doubl
datatypes since float
datatyles eventually convert to double
datatypes inside printf
.
There is no provision to print float
data. Please find the discussion here : Correct format specifier for double in printf
Generics:
With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T>
class the java compiler generates Byte Code as if it was Foo<Object>
. This means casting and also boxing/unboxing will have to be done in the "background".
I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.
public static void Copy(String SourceFile, String TargetFile)
{
FileStream fis = null;
FileStream fos = null;
try
{
Console.Write("## Try No. " + a + " : (Write from " + SourceFile + " to " + TargetFile + ")\n");
fis = new FileStream(SourceFile, FileMode.Open, FileAccess.ReadWrite);
fos = new FileStream(TargetFile, FileMode.Create, FileAccess.ReadWrite);
int intbuffer = 5242880;
byte[] b = new byte[intbuffer];
int i;
while ((i = fis.Read(b, 0, intbuffer)) > 0)
{
fos.Write(b, 0, i);
}
Console.Write("Writing file : " + TargetFile + " is successful.\n");
break;
}
catch (Exception e)
{
Console.Write("Writing file : " + TargetFile + " is unsuccessful.\n");
Console.Write(e);
}
finally
{
if (fis != null)
{
fis.Close();
}
if (fos != null)
{
fos.Close();
}
}
}
The code above will read a big file and write to a new big file. The "intbuffer" value can be set in multiple of 1024. While both source and target file are open, it reads the big file by bytes and write to the new target file by bytes. It will not go out of memory.
As @jethro said, splitext
is the neat way to do it. But in this case, it's pretty easy to split it yourself, since the extension must be the part of the filename coming after the final period:
filename = '/home/user/somefile.txt'
print( filename.rsplit( ".", 1 )[ 0 ] )
# '/home/user/somefile'
The rsplit
tells Python to perform the string splits starting from the right of the string, and the 1
says to perform at most one split (so that e.g. 'foo.bar.baz'
-> [ 'foo.bar', 'baz' ]
). Since rsplit
will always return a non-empty array, we may safely index 0
into it to get the filename minus the extension.
You would want to amend the commit and then do a force push which will update the branch with the PR.
Here's how I recommend you do this:
git reset --soft HEAD^
or if it's a different commit, you would want to replace 'HEAD^' with the commit id)git commit -a -c ORIG_HEAD
The now that your branch has been updated, the Pull Request will include your changes.
Here's a link to Gits documentation where they have a pretty good example under Undo a commit and redo.
On a mac you have to set keybinding yourself. Simply go to
Sublime --> Preference --> Key Binding - User
and input the following:
{ "keys": ["shift+command+m"], "command": "goto_definition" }
This will enable keybinding of Shift + Command + M
to enable goto definition. You can set the keybinding to anything you would like of course.
Regarding the performance of the direct operations and the method .equals()
. The .equals()
methods seems to be roughly 4 times slower than ==
.
I ran the following tests..
For the performance of ==
:
public class BooleanPerfCheck {
public static void main(String[] args) {
long frameStart;
long elapsedTime;
boolean heyderr = false;
frameStart = System.currentTimeMillis();
for (int i = 0; i < 999999999; i++) {
if (heyderr == false) {
}
}
elapsedTime = System.currentTimeMillis() - frameStart;
System.out.println(elapsedTime);
}
}
and for the performance of .equals()
:
public class BooleanPerfCheck {
public static void main(String[] args) {
long frameStart;
long elapsedTime;
Boolean heyderr = false;
frameStart = System.currentTimeMillis();
for (int i = 0; i < 999999999; i++) {
if (heyderr.equals(false)) {
}
}
elapsedTime = System.currentTimeMillis() - frameStart;
System.out.println(elapsedTime);
}
}
Total system time for ==
was 1
Total system time for .equals()
varied from 3 - 5
Thus, it is safe to say that .equals()
hinders performance and that ==
is better to use in most cases to compare Boolean
.
Usually when I use a select menu, each option has a value associated with it. For example
<select id="nfl">
<option value="Bears Still...">Chicago Bears</option>
<option selected="selected" value="Go Pack">Green Bay Packers</option>
</select>
console.log($('#nfl').val()) logs "Go Pack" to the console
Set the value to an empty string $('#nfl').val("")
console.log($('#nfl').val()) logs "" to the console
Now this doesn't remove the selected attribute from the option but all I really want is the value.
You can replace WB_parentfolder with something like "C:\". For me WB_parentfolder is grabbing the location of the current workbook. file_des_folder is the new folder i want. This goes through and creates as many folders as you need.
folder1 = Left(file_des_folder, InStr(Len(WB_parentfolder) + 1, file_loc, "\"))
Do While folder1 <> file_des_folder
folder1 = Left(file_des_folder, InStr(Len(folder1) + 1, file_loc, "\"))
If Dir(file_des_folder, vbDirectory) = "" Then 'create folder if there is not one
MkDir folder1
End If
Loop
I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.
I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.
The project goals were very simple;
Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;
ConfigurationManager.AppSettings.Add(key_name, data_value)
That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.
After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.
With a little trial and error, I found the following code would do exactly what I wanted;
ConfigurationManager.AppSettings.Set(key_name, data_value)
Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.
In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;
appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True
With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.
This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.
I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.
/**
*
* @param {HTMLElement} el
* @return {{top: number, left: number}}
*/
function getDocumentOffsetPosition(el) {
var position = {
top: el.offsetTop,
left: el.offsetLeft
};
if (el.offsetParent) {
var parentPosition = getDocumentOffsetPosition(el.offsetParent);
position.top += parentPosition.top;
position.left += parentPosition.left;
}
return position;
}
Thank ThinkingStiff for the answer, this is only another version.
I am using event "live", my solution is basically similiar with Dimitiar, but instead of using "focus", my previous value is stored when "click" is triggered.
var previous = "initial prev value";
$("select").live('click', function () {
//update previous value
previous = $(this).val();
}).change(function() {
alert(previous); //I have previous value
});
The easiest way is:
File.WriteAllText(path, string.Empty)
However, I recommend you use FileStream
because the first solution can throw UnauthorizedAccessException
using(FileStream fs = File.Open(path,FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
lock(fs)
{
fs.SetLength(0);
}
}
You could use the copy()
function :
// Will copy foo/test.php to bar/test.php
// overwritting it if necessary
copy('foo/test.php', 'bar/test.php');
Quoting a couple of relevant sentences from its manual page :
Makes a copy of the file source to dest.
If the destination file already exists, it will be overwritten.
To others not using RubyMotion and don't think that deleting the app is acceptable (as in, you want to do upgrade testing). Check out the bottom of these docs from Apple:
https://developer.apple.com/library/ios/technotes/tn2319/_index.html
It looks like they changed something in 8.1.3 to check for this new rule.
The Fix
"[Add] the installed application’s application-identifier value, as logged in the second parentheses, to the previous-application-identifiers entitlement’s array value for the app being installed (by resigning it or re-building it) and requesting new special provisioning profiles as shown below."
<key>previous-application-identifiers</key>
<array>
<string>{Your Old App ID Prefix}.YourApp.Bundle.ID</string>
</array>
EDIT:
In order to do this, you need special provisioning profiles. You can request these from Apple: "To enable signing with the previous-application-identifiers entitlement new special provisioning profiles are required that can be obtained by going to the Contact US page and requesting them." (from the docs linked above).
Here is a simple customview for display circle progress. You can modify and optimize more to suitable for your project.
class CircleProgressBar @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val backgroundWidth = 10f
private val progressWidth = 20f
private val backgroundPaint = Paint().apply {
color = Color.LTGRAY
style = Paint.Style.STROKE
strokeWidth = backgroundWidth
isAntiAlias = true
}
private val progressPaint = Paint().apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = progressWidth
isAntiAlias = true
}
var progress: Float = 0f
set(value) {
field = value
invalidate()
}
private val oval = RectF()
private var centerX: Float = 0f
private var centerY: Float = 0f
private var radius: Float = 0f
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
centerX = w.toFloat() / 2
centerY = h.toFloat() / 2
radius = w.toFloat() / 2 - progressWidth
oval.set(centerX - radius,
centerY - radius,
centerX + radius,
centerY + radius)
super.onSizeChanged(w, h, oldw, oldh)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(centerX, centerY, radius, backgroundPaint)
canvas?.drawArc(oval, 270f, 360f * progress, false, progressPaint)
}
}
Example using
xml
<com.example.androidcircleprogressbar.CircleProgressBar
android:id="@+id/circle_progress"
android:layout_width="200dp"
android:layout_height="200dp" />
kotlin
class MainActivity : AppCompatActivity() {
val TOTAL_TIME = 10 * 1000L
override fun onCreate(savedInstanceState: Bundle?) {
...
timeOutRemoveTimer.start()
}
private var timeOutRemoveTimer = object : CountDownTimer(TOTAL_TIME, 10) {
override fun onFinish() {
circle_progress.progress = 1f
}
override fun onTick(millisUntilFinished: Long) {
circle_progress.progress = (TOTAL_TIME - millisUntilFinished).toFloat() / TOTAL_TIME
}
}
}
Result
This solution has really helped me :
By using below two methods we can clear data programatically
public void clearApplicationData() {
File cacheDirectory = getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent());
if (applicationDirectory.exists()) {
String[] fileNames = applicationDirectory.list();
for (String fileName : fileNames) {
if (!fileName.equals("lib")) {
deleteFile(new File(applicationDirectory, fileName));
}
}
}
}
public static boolean deleteFile(File file) {
boolean deletedAll = true;
if (file != null) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
}
} else {
deletedAll = file.delete();
}
}
return deletedAll;
}
This works for me:
android {
packagingOptions {
exclude 'LICENSE.txt'
}
}
You can't do it using environment variables. It's done via "non standard" options. Run: java -X
for details. The options you're looking for are -Xmx
and -Xms
(this is "initial" heap size, so probably what you're looking for.)
I did something like this in my project. I would like to share it here. You can add another div as a child and give it a border with small width and place it left, centre or right with usual CSS
HTML code:
<div>
content
<div class ="ac-brdr"></div>
</div>
CSS as below:
.active {
color: magneta;
}
.active .ac-brdr {
width: 20px;
margin: 0 auto;
border-bottom: 1px solid magneta;
}
You need to update the package list in your Ubuntu:
$ sudo apt-get update
$ sudo apt-get install <package_name>
The most straight-forward way I can think of is using numpy's gradient function:
x = numpy.linspace(0,10,1000)
dx = x[1]-x[0]
y = x**2 + 1
dydx = numpy.gradient(y, dx)
This way, dydx will be computed using central differences and will have the same length as y, unlike numpy.diff, which uses forward differences and will return (n-1) size vector.
Java and C:
You may find more information in Android developers site.
Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR
set these variables:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
export PATH=$JAVA_HOME/bin:$PATH
Run your app and fun :)
(Minor update: put variable value in quote)
This guy made a nice Range class.
Its use however will not yield nice code as it's a generic class. You'd have to type something like:
if (new Range<Integer>(0, 100).contains(i))
or (somewhat better if you implement first):
class IntRange extends Range<Integer>
....
if (new IntRange(0,100).contains(i))
Semantically both are IMHO nicer than what Java offers by default, but the memory overhead, performance degradation and more typing overall are hadly worth it. Personally, I like mdma's approach better.
$("#myframe").load(function() {
alert("loaded");
});
Select ColumnB and as two CF formula rules apply:
Green: =AND(B1048576="X",B1="Y")
Red: =AND(B1048576="X",B1="W")
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
An old post, but I was surprised about the most up-voted answer.
The proper solution for this should be to cancel the asynctask in onStop (or wherever appropriate in your fragment). This way you don't introduce a memory leak (an asynctask keeping a reference to your destroyed fragment) and you have better control of what is going on in your fragment.
@Override
public void onStop() {
super.onStop();
mYourAsyncTask.cancel(true);
}
Another way to do it:
<?php
$data = 'My data';
$menugen = function() use ($data) {
echo "[".$data."]";
};
$menugen();
UPDATE 2020-01-13: requested by Peter Mortensen
As of PHP 5.3.0 we have anonymous functions support that can create closures. A closure can access the variable which is created outside of its scope.
In the example, the closure is able to access $data
because it was declared in the use
clause.
System.in.read() is a read input method for System.in class which is "Standard Input file" or 0 in conventional OS.
The substitute command can be applied to a visual selection. Make a visual block over the lines that you want to change, and type :, and notice that the command-line is initialized like this: :'<,'>
. This means that the substitute command will operate on the visual selection, like so:
:'<,'>s/$/,/
And this is a substitution that should work for your example, assuming that you really want the comma at the end of each line as you've mentioned. If there are trailing spaces, then you may need to adjust the command accordingly:
:'<,'>s/\s*$/,/
This will replace any amount of whitespace preceding the end of the line with a comma, effectively removing trailing whitespace.
The same commands can operate on a range of lines, e.g. for the next 5 lines: :,+5s/$/,/
, or for the entire buffer: :%s/$/,/
.
Use multiselect function as below.
$('#drp_Books_Ill_Illustrations').multiSelect('select', 'value');
library(RODBC)
file.name <- "file.xls"
sheet.name <- "Sheet Name"
## Connect to Excel File Pull and Format Data
excel.connect <- odbcConnectExcel(file.name)
dat <- sqlFetch(excel.connect, sheet.name, na.strings=c("","-"))
odbcClose(excel.connect)
Personally, I like RODBC and can recommend it.
The prefect answers is. Enter the follow path,copy all of them
Macintosh HD ? ???? ? adt-bundle-mac ? sdk ? platform-tools
then parse into Macintosh HD ? ???? ? adt-bundle-mac ? sdk ? tools
,
last,edit the line plugin.version=23.0.0
of file Macintosh HD ? ???? ? adt-bundle-mac ? sdk ? tools ?plugin.prop
,such as plugin.version=21.0.0
.
restart eclipse.everything is all-right.
For pages that rely on external CSS (most pages nowadays) a simple and reliable solution is to kill the head
element:
document.querySelector("head").remove();
Right-click this page (in Chrome/Firefox), select Inspect, paste the code in the devtools console and press Enter.
A bookmarklet version of the same code that you can paste as the URL of a bookmark:
javascript:(function(){document.querySelector("head").remove();})()
Now clicking the bookmark on in your Favorites bar will show the page without any css stylesheets.
Removing the head will not work for pages that use inline styles.
If you happen to use Safari on MacOS then:
Converting the output is too late; the calculation has already taken place in integer arithmetic. You need to convert the inputs to double
:
System.out.println((double)completed/(double)total);
Note that you don't actually need to convert both of the inputs. So long as one of them is double
, the other will be implicitly converted. But I prefer to do both, for symmetry.
OpenCode appears to be a project at the MIT Media Lab for running Java Code online in a web browser interface. Years ago, I played around a lot at TopCoder. It runs a Java Web Start app, though, so you would need a Java run time installed.
AF_INET
is an address family that is used to designate the type of addresses that your socket can communicate with (in this case, Internet Protocol v4 addresses). When you create a socket, you have to specify its address family, and then you can only use addresses of that type with the socket. The Linux kernel, for example, supports 29 other address families such as UNIX (AF_UNIX
) sockets and IPX (AF_IPX
), and also communications with IRDA and Bluetooth (AF_IRDA
and AF_BLUETOOTH
, but it is doubtful you'll use these at such a low level).
For the most part, sticking with AF_INET
for socket programming over a network is the safest option. There is also AF_INET6
for Internet Protocol v6 addresses.
Hope this helps,
The following example show you how to define a function in jQuery. You will see a button “Click here”, when you click on it, we call our function “myFunction()”.
$(document).ready(function(){
$.myFunction = function(){
alert('You have successfully defined the function!');
}
$(".btn").click(function(){
$.myFunction();
});
});
You can see an example here: How to define a function in jQuery?
It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in What is a "slug" in Django? the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the page served (on this site at least)
I think this approach is more useful:
<h2 id="bar" title="Bar">Bar</h2>
[id]:target {
display: block;
position: relative;
top: -120px;
visibility: hidden;
}
[id]:target::before {
content: attr(title);
top: 120px;
position: relative;
visibility: visible;
}
You can use indexOf(). Like:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);
The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.
If you want to search from end to start, use the lastIndexOf() method:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.lastIndexOf("brown");
alert(a);
The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.
Returns -1 if the item is not found.
Maybe try this:
ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
Final answer was a combination of two of the above (I've upvoted both to show my appreciation!):
select case
when exists (
SELECT 1
FROM Sys.columns c
WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
AND c.name = 'ModifiedByUserId'
)
then 1
else 0
end
You can use body or * to make margin and padding 0px;
*{
margin: 0px;
padding:0px;
}
Let's look in the source of wisdom for such questions: Joshua Bloch's Effective Java:
Technically, there is no such thing as a static inner class. According to Effective Java, the correct terminology is a static nested class. A non-static nested class is indeed an inner class, along with anonymous classes and local classes.
And now to quote:
Each instance of a non-static nested class is implicitly associated with an enclosing instance of its containing class... It is possible to invoke methods on the enclosing instance.
A static nested class does not have access to the enclosing instance. It uses less space too.
Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.
Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return false;
}
if(getCookie("KoiMilGaya")) {
//alert('found');
// Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again..
} else {
//alert('nothing');
// Display popup or anthing here. it shows on first visit only.
// this will load again when user closer browser and open again.
setCookie('KoiMilGaya','1');
}
For MySQL, there is Querious and Sequel Pro. The former costs US$25, and the latter is free. You can find a comparison of them here, and a list of some other Mac OS X MySQL clients here.
Steve
I want to change or update my ContactNo to 8018070999 where there is 8018070777 using Case statement
update [Contacts] set contactNo=(case
when contactNo=8018070777 then 8018070999
else
contactNo
end)
Use a concrete list type, e.g. ArrayList
instead of just List
.
// convert datetime to unix epoch seconds
public static long ToUnixTime(DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}
Should use ToUniversalTime() for the DateTime object.
Angular 10
You should now edit the tsconfig.app.json
(notice the "app" in the name) file instead.
There you'll find the compilerOptions
, and you simply add resolveJsonModule: true
.
So, for example, the file in a brand new project should look like this:
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [],
"resolveJsonModule": true
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
We have Collection as below:
Syntax:
{{(Collection/array/list | filter:{Value : (object value)})[0].KeyName}}
Example:
{{(Collectionstatus | filter:{Value:dt.Status})[0].KeyName}}
-OR-
Syntax:
ng-bind="(input | filter)"
Example:
ng-bind="(Collectionstatus | filter:{Value:dt.Status})[0].KeyName"
I have never done so, but it seems like
MATCH (head, head, body) AGAINST ('some words' IN BOOLEAN MODE)
Should give a double weight to matches found in the head.
Just read this comment on the docs page, Thought it might be of value to you:
Posted by Patrick O'Lone on December 9 2002 6:51am
It should be noted in the documentation that IN BOOLEAN MODE will almost always return a relevance of 1.0. In order to get a relevance that is meaningful, you'll need to:
SELECT MATCH('Content') AGAINST ('keyword1 keyword2') as Relevance
FROM table
WHERE MATCH ('Content') AGAINST('+keyword1+keyword2' IN BOOLEAN MODE)
HAVING Relevance > 0.2
ORDER BY Relevance DESC
Notice that you are doing a regular relevance query to obtain relevance factors combined with a WHERE clause that uses BOOLEAN MODE. The BOOLEAN MODE gives you the subset that fulfills the requirements of the BOOLEAN search, the relevance query fulfills the relevance factor, and the HAVING clause (in this case) ensures that the document is relevant to the search (i.e. documents that score less than 0.2 are considered irrelevant). This also allows you to order by relevance.
This may or may not be a bug in the way that IN BOOLEAN MODE operates, although the comments I've read on the mailing list suggest that IN BOOLEAN MODE's relevance ranking is not very complicated, thus lending itself poorly for actually providing relevant documents. BTW - I didn't notice a performance loss for doing this, since it appears MySQL only performs the FULLTEXT search once, even though the two MATCH clauses are different. Use EXPLAIN to prove this.
So it would seem you may not need to worry about calling the fulltext search twice, though you still should "use EXPLAIN to prove this"
A simple one liner;
res.status(404).send("Oh uh, something went wrong");
Use requests.packages.urllib3.disable_warnings()
and verify=False
on requests
methods.
import requests
from urllib3.exceptions import InsecureRequestWarning
# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
# Set `verify=False` on `requests.post`.
requests.post(url='https://example.com', data={'bar':'baz'}, verify=False)
In case you need to access a specific set of remote services you could use an intermediate reverse-proxy, to perform tls1.2 for you. This would save you from trying to patch or upgrade java1.6.
e.g. app -> proxy:http(5500)[tls-1.2] -> remote:https(443)
Configuration in its simplest form (one port per service) for apache httpd is:
Listen 127.0.0.1:5000
<VirtualHost *:5500>
SSLProxyEngine On
ProxyPass / https://remote-domain/
ProxyPassReverse / https://remote-domain/
</VirtualHost>
Then instead of accessing https://remote-domain/ you access http://localhost:5500/
This theme only works after API 21(included). And make both the StatusBar and NavigationBar transparent.
<style name="TransparentAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
we can follow below procedure to avoid display of key-values in alphabetical order.
Javascript
$scope.data = {
"id": 2,
"project": "wewe2012",
"date": "2013-02-26",
"description": "ewew",
"eet_no": "ewew",
};
var array = [];
for(var key in $scope.data){
var test = {};
test[key]=$scope.data[key];
array.push(test);
}
$scope.data = array;
HTML
<p ng-repeat="obj in data">
<font ng-repeat="(key, value) in obj">
{{key}} : {{value}}
</font>
</p>
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public class DisplayImage {
public static void main(String avg[]) throws IOException
{
DisplayImage abc=new DisplayImage();
}
public DisplayImage() throws IOException
{
BufferedImage img=ImageIO.read(new File("f://images.jpg"));
ImageIcon icon=new ImageIcon(img);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(200,300);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
At first,
You should know that destroy()
is correct method for removing an entity directly via object or model and delete()
can only be called in query builder.
In your case, You have not checked if record exists in database or not. Record can only be deleted if exists.
So, You can do it like follows.
$user = User::find($id);
if($user){
$destroy = User::destroy(2);
}
The value or $destroy
above will be 0 or 1 on fail or success respectively. So, you can alter the $data
array like:
if ($destroy){
$data=[
'status'=>'1',
'msg'=>'success'
];
}else{
$data=[
'status'=>'0',
'msg'=>'fail'
];
}
Hope, you understand.
You don't need CSS for this.
<img src="abc"/>
now with link:
<a href="#myLink"><img src="abc"/></a>
Or with jquery, later on, you can use the wrap property, see these questions answer:
For Bootstrap 4
<hr>
still works for a normal divider. However, if you want a divider with text in the middle:
<div class="row">
<div class="col"><hr></div>
<div class="col-auto">OR</div>
<div class="col"><hr></div>
</div>
use #0000
(only four zeros otherwise it will be considered as black
) this is the color code for transparent. You can use it directly but I recommend you to define a color in color.xml so you can enjoy re-usefullness of the code.
The way to do such a thing when you have modern C (C99) is to use a compound literal.
a = (const struct x){ 0 };
This is somewhat similar to David's solution, only that you don't have to worry to declare an the empty structure or whether to declare it static
. If you use the const
as I did, the compiler is free to allocate the compound literal statically in read-only storage if appropriate.
This situation occurred to me when I uninstalled a method and tried to reinstall it. My very same interpreter, which worked before, suddenly stopped working. And this error occurred.
I tried restarting my PC, reinstalling Pycharm, invalidating caches, nothing worked.
Then I went here to reinstall the interpreter: https://www.python.org/downloads/
When you install it, there's an option to fix the python.exe interpreter. Click that. My IDE went back to normal working conditions.
You can also store the initial value in a data attribute and check it against the current value.
<input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" />
$("#id_someid").keyup(function() {
return $(this).val() == $(this).data().initial;
});
Would return true if the initial value has not changed.
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
All of these answers helped me construct the following script which will automatically convert XLS* files to CSV and vice versa, by dropping one or more files on the script (or via command line). Apologies for the janky formatting.
' https://stackoverflow.com/questions/1858195/convert-xls-to-csv-on-command-line
' https://gist.github.com/tonyerskine/77250575b166bec997f33a679a0dfbe4
' https://stackoverflow.com/a/36804963/1037948
'* Global Settings and Variables
Set args = Wscript.Arguments
For Each sFilename In args
iErr = ConvertExcelFormat(sFilename)
' 0 for normal success
' 404 for file not found
' 10 for file skipped (or user abort if script returns 10)
Next
WScript.Quit(0)
Function ConvertExcelFormat(srcFile)
if IsEmpty(srcFile) OR srcFile = "" Then
WScript.Echo "Error! Please specify at least one source path. Usage: " & WScript.ScriptName & " SourcePath.xls*|csv"
ConvertExcelFormat = -1
Exit Function
'Wscript.Quit
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
srcExt = objFSO.GetExtensionName(srcFile)
' the 6 is the constant for 'CSV' format, 51 is for 'xlsx'
' https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xlfileformat-enumeration-excel
' https://www.rondebruin.nl/mac/mac020.htm
Dim outputFormat, srcDest
If LCase(Mid(srcExt, 1, 2)) = "xl" Then
outputFormat = 6
srcDest = "csv"
Else
outputFormat = 51
srcDest = "xlsx"
End If
'srcFile = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
srcFile = objFSO.GetAbsolutePathName(srcFile)
destFile = Replace(srcFile, srcExt, srcDest)
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(srcFile)
' preserve formatting? https://stackoverflow.com/a/8658845/1037948
'oBook.Application.Columns("A:J").NumberFormat = "@"
oBook.SaveAs destFile, outputFormat
oBook.Close False
oExcel.Quit
WScript.Echo "Conversion complete of '" & srcFile & "' to '" & objFSO.GetFileName(destFile) & "'"
End Function
I have faced the same problem few hours ago.
The ".clear()" method actually clears the canvas, but (evidently) it leaves the object alive and reactive.
Reading carefully the official documentation, in the "Advanced usage" section, I have noticed the method ".destroy()", described as follows:
"Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js."
It actually does what it claims and it has worked fine for me, I suggest you to give it a try.
{
( VeryLongCondition_1 ) or last;
( VeryLongCondition_2 ) or last;
( VeryLongCondition_3 ) or last;
( VeryLongCondition_4 ) or last;
( VeryLongCondition_5 ) or last;
( VeryLongCondition_6 ) or last;
# Guarded code goes here
}
If any of the conditions fail it will just continue on, after the block. If you are defining any variables that you want to keep around after the block, you will need to define them before the block.
Windows7 FireFox/Chrome:
{
"cmd":["F:\\Program Files\\Mozilla Firefox\\firefox.exe","$file"]
}
just use your own path of firefox.exe or chrome.exe to replace mine.
Replace firefox.exe or chrome.exe with your own path.
You can find it in your "Home" directory:
On Windows 7:
C:\Users\<YOUR_ACCOUNT>\.keystore
On Linux (Ubuntu):
/home/<YOUR_ACCOUNT>/.keystore
We can use ix
to reorder by passing a list:
In [27]:
# get a list of columns
cols = list(df)
# move the column to head of list using index, pop and insert
cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[27]:
['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
In [28]:
# use ix to reorder
df = df.ix[:, cols]
df
Out[28]:
Mid Net Upper Lower Zsore
Answer_option
More_than_once_a_day 2 0% 0.22% -0.12% 65
Once_a_day 3 0% 0.32% -0.19% 45
Several_times_a_week 4 2% 2.45% 1.10% 78
Once_a_week 6 1% 1.63% -0.40% 65
Another method is to take a reference to the column and reinsert it at the front:
In [39]:
mid = df['Mid']
df.drop(labels=['Mid'], axis=1,inplace = True)
df.insert(0, 'Mid', mid)
df
Out[39]:
Mid Net Upper Lower Zsore
Answer_option
More_than_once_a_day 2 0% 0.22% -0.12% 65
Once_a_day 3 0% 0.32% -0.19% 45
Several_times_a_week 4 2% 2.45% 1.10% 78
Once_a_week 6 1% 1.63% -0.40% 65
You can also use loc
to achieve the same result as ix
will be deprecated in a future version of pandas from 0.20.0
onwards:
df = df.loc[:, cols]
Since 2.3.25, do it like this:
<#list user as propName, propValue>
${propName} = ${propValue}
</#list>
Note that this also works with non-string keys (unlike map[key]
, which had to be written as map?api.get(key)
then).
Before 2.3.25 the standard solution was:
<#list user?keys as prop>
${prop} = ${user[prop]}
</#list>
However, some really old FreeMarker integrations use a strange configuration, where the public Map
methods (like getClass
) appear as keys. That happens as they are using a pure BeansWrapper
(instead of DefaultObjectWrapper
) whose simpleMapWrapper
property was left on false
. You should avoid such a setup, as it mixes the methods with real Map
entries. But if you run into such unfortunate setup, the way to escape the situation is using the exposed Java methods, such as user.entrySet()
, user.get(key)
, etc., and not using the template language constructs like ?keys
or user[key]
.
Even I too faced similar issue,
fatal error RC1015: cannot open include file 'afxres.h'. from this code
Replacing afxres.h with Winresrc.h and declaring IDC_STATIC as -1 worked for me. (Using visual studio Premium 2012)
//#include "afxres.h"
#include "WinResrc.h"
#define IDC_STATIC -1
Actually, there is a better way to do it than split:
public string GetFirstFromSplit(string input, char delimiter)
{
var i = input.IndexOf(delimiter);
return i == -1 ? input : input.Substring(0, i);
}
And as extension methods:
public static string FirstFromSplit(this string source, char delimiter)
{
var i = source.IndexOf(delimiter);
return i == -1 ? source : source.Substring(0, i);
}
public static string FirstFromSplit(this string source, string delimiter)
{
var i = source.IndexOf(delimiter);
return i == -1 ? source : source.Substring(0, i);
}
Usage:
string result = "hi, hello, sup".FirstFromSplit(',');
Console.WriteLine(result); // "hi"
As others have pointed out, you need to create an explicit reference for every Excel object you use, and call Marshal.ReleaseComObject on that reference, as described in this KB article. You also need to use try/finally to ensure ReleaseComObject is always called, even when an exception is thrown. I.e. instead of:
Worksheet sheet = excelApp.Worksheets(1)
... do something with sheet
you need to do something like:
Worksheets sheets = null;
Worksheet sheet = null
try
{
sheets = excelApp.Worksheets;
sheet = sheets(1);
...
}
finally
{
if (sheets != null) Marshal.ReleaseComObject(sheets);
if (sheet != null) Marshal.ReleaseComObject(sheet);
}
You also need to call Application.Quit before releasing the Application object if you want Excel to close.
As you can see, this quickly becomes extremely unwieldy as soon as you try to do anything even moderately complex. I have successfully developed .NET applications with a simple wrapper class that wraps a few simple manipulations of the Excel object model (open a workbook, write to a Range, save/close the workbook etc). The wrapper class implements IDisposable, carefully implements Marshal.ReleaseComObject on every object it uses, and does not pubicly expose any Excel objects to the rest of the app.
But this approach doesn't scale well for more complex requirements.
This is a big deficiency of .NET COM Interop. For more complex scenarios, I would seriously consider writing an ActiveX DLL in VB6 or other unmanaged language to which you can delegate all interaction with out-proc COM objects such as Office. You can then reference this ActiveX DLL from your .NET application, and things will be much easier as you will only need to release this one reference.
public class DogAgeComparator implements Comparator<Dog> {
public int compare(Dog o1, Dog o2) {
return Integer.compare(o1.getAge(), o2.getId());
}
}
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
A CTE worked for me:
with cte as (
select 1 col1
from temptable
group by column_1
)
select COUNT(col1)
from cte;
For those not getting a solution for older answers, i simply put my file name as the very first line in my code.
like so
#ruby_file_name_here.rb
puts "hello world"
This code make clean dataframe:
df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
#clean
df = pd.DataFrame()
These days something like the following will suffice:
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
restTemplate.exchange(RequestEntity.get(new URI(url)).headers(headers).build(), returnType);
Another way to continue with the example @nfreeze used is this validation method:
UserModel.schema.path('name').validate(function (value, res) {
UserModel.findOne({name: value}, 'id', function(err, user) {
if (err) return res(err);
if (user) return res(false);
res(true);
});
}, 'already exists');
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
You can find a few examples here:
// Fill the DataSet. DataSet ds = new DataSet(); ds.Locale = CultureInfo.InvariantCulture; FillDataSet(ds); DataTable contacts = ds.Tables["Contact"]; DataTable orders = ds.Tables["SalesOrderHeader"]; var query = contacts.AsEnumerable().Join(orders.AsEnumerable(), order => order.Field<Int32>("ContactID"), contact => contact.Field<Int32>("ContactID"), (contact, order) => new { ContactID = contact.Field<Int32>("ContactID"), SalesOrderID = order.Field<Int32>("SalesOrderID"), FirstName = contact.Field<string>("FirstName"), Lastname = contact.Field<string>("Lastname"), TotalDue = order.Field<decimal>("TotalDue") }); foreach (var contact_order in query) { Console.WriteLine("ContactID: {0} " + "SalesOrderID: {1} " + "FirstName: {2} " + "Lastname: {3} " + "TotalDue: {4}", contact_order.ContactID, contact_order.SalesOrderID, contact_order.FirstName, contact_order.Lastname, contact_order.TotalDue); }
Or just google for 'linq join method syntax'.
I was also in the same problem, check your build path in eclipse by Right Click on Project > build path > configure build path
Now check for Excluded Files, it should not have your file specified there by any means or by regex.
Cheers!
My setup was a little different using XAMPP. in httpd-xampp.conf I had to make the following change.
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
AllowOverride AuthConfig
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
change to
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
AllowOverride AuthConfig
#makes it so I can config the database from anywhere
#change the line below
Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
I need to state that I'm brand new at this so I'm just hacking around but this is how I got it working.
With typescript we can leverage type aliases, like so:
type KeyboardEvent = {
target: HTMLInputElement,
key: string,
};
const onKeyPress = (e: KeyboardEvent) => {
if ('Enter' === e.key) { // Enter keyboard was pressed!
submit(e.target.value);
e.target.value = '';
return;
}
// continue handle onKeyPress input events...
};
Click settings and search for "Repositories", then select the local repo and click "Update". That's all. This action meets my need.
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
What do you want to validate? The email address?
The email address can only be checked for its format conformance. See the standard: RFC2822. Best way to do that is a regular expression. You will never know if really exists without sending an email.
I checked the commons validator. It contains an org.apache.commons.validator.EmailValidator class. Seems to be a good starting point.
using (B a = new B())
{
DoSomethingWith(a);
}
is equivalent to
B a = new B();
try
{
DoSomethingWith(a);
}
finally
{
((IDisposable)a).Dispose();
}
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
var a = new Date("2010 jan 10"),
b = new Date("2010 jan 9");
alert(
a + "\n" +
b + "\n" +
"Difference: " + ((+a - +b) / 1000)
);
If you want to keep the autocomplete functionality intact you can use a bit of jQuery to remove Chrome's styling. I wrote a short post about it here: http://www.benjaminmiles.com/2010/11/22/fixing-google-chromes-yellow-autocomplete-styles-with-jquery/
if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
$(window).load(function(){
$('input:-webkit-autofill').each(function(){
var text = $(this).val();
var name = $(this).attr('name');
$(this).after(this.outerHTML).remove();
$('input[name=' + name + ']').val(text);
});
});}
Take out the MONTHS from your case, and remove the brackets... like this:
CASE
WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
ELSE 'NOTHING'
END AS 'MONTHS'
You can think of this as being equivalent to:
CASE TRUE
WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
ELSE 'NOTHING'
END AS 'MONTHS'
A many to many relationship normally has a linking table. Consider this "link" as an entity in its own right and give it a unique id, then send that id in the delete request.
You would have a a REST resource URL like /user/role to handle operations on a user-role "link" entity.
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">
I was getting the same error and nothing was wrong with my java files and packages. Later I noticed that the folder name WEB-INF was written like this "WEB_INF". So correcting just the folder name solved the issue
So here is the solution for this:
I check port 80
used by Skype, after that I changes port to 81
and also along with that somewhere i read this error may be because of SSL Port then I changed SSL port to 444
. However this got resolved easily.
One most important thing to notice here, all the port changes should be done inside config files, for http port change: httpd.conf for SSL httpd-ssl.conf. Otherwise changes will not replicate to Apache, Sometime PC reboot is also required.
Edit: Make Apache use port 80 and make Skype communicate on other Port
For those who are struggling with Skype, want to change its port and to make Apache to use port 80.
No need to Re-Install, Here is simply how to change Skype Port
Goto: Tools > Options > Advanced > Connection
There you need to uncheck
Use port 80 and 443 as alternative for incoming connections.
That's it, here is screen shot of it.
A faster and shorter notation for null
checks can be:
value == null ? "UNDEFINED" : value
This line is equivalent to:
if(value == null) {
console.log("UNDEFINED")
} else {
console.log(value)
}
Especially when you have a lot of null
check it is a nice short notation.
There is an easy way to set the default timezone in laravel or lumen.
This is helpful while working in multiple environments where you can use different timezone based on each environment.
APP_TIMEZONE=Asia/Kolkata
in .env
(Your can choose any timezone from the supported timezones)date_default_timezone_set(env('APP_TIMEZONE', 'UTC'));
in app.php
.With this change your project will take your .env set timezone and if there is nothing set then take UTC by default.
After modifying the time zone setting run command
php artisan config:clear
so that your changes reflect in your application
String.matches
returns whether the whole string matches the regex, not just any substring.
Yes you can...
PDFs have Javascript support. I needed to have auto print capabilities when a PHP-generated PDF was created and I was able to use FPDF to get it to work:
find "${search_dir}" "${work_dir}" -mindepth 1 -maxdepth 1 -type f -print0 | xargs -0 -I {} echo "{}"
Try the following:
$('#to').datepicker({
dateFormat: 'yy-mm-dd'
});
You'd think it would be yyyy-mm-dd but oh well :P
With all zeroes:
static String hexToBin(String s) {
String preBin = new BigInteger(s, 16).toString(2);
Integer length = preBin.length();
if (length < 8) {
for (int i = 0; i < 8 - length; i++) {
preBin = "0" + preBin;
}
}
return preBin;
}
If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule
that gets added this code to every HttpApplication.Begin_Request
event:-
HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
"Note that you need to have image fully loaded first (otherwise ending up in having empty images), so in some cases you'd need to wrap handling into: bannerImage.addEventListener("load", function () {}); – yuga Nov 1 '17 at 13:04"
This is extremely IMPORTANT. One of the the options i'm exploring this afternoon is using javascript callback methods rather than addEventListeners since that doesn't seem to bind correctly either. Getting all the elements ready before page load WITHOUT a page refresh is critical.
If anyone can expand upon this please do - as in, did you use a settimeout, a wait, a callback, or an addEventListener method to get the desired result. Which one and why?
// set your date here
$mydate = "2009-01-01";
/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastyear = strtotime("-1 year", strtotime($mydate));
// format and display the computed date
echo date("Y-m-d", $lastyear);
<div class="content scrollable" ref="msgContainer">
<!-- content -->
</div>
data() {
return {
count: 5
};
},
watch: {
count: function() {
this.$nextTick(function() {
var container = this.$refs.msgContainer;
container.scrollTop = container.scrollHeight + 120;
});
}
}
.scrollable {
overflow: hidden;
overflow-y: scroll;
height: calc(100vh - 20px);
}
pypsrp - Python PowerShell Remoting Protocol Client library
At a basic level, you can use this library to;
Execute a cmd command
Run another executable
Execute PowerShell scripts
Copy a file from the localhost to the remote Windows host
Fetch a file from the remote Windows host to the localhost
Create a Runspace Pool that contains one or multiple PowerShell pipelines and execute them asynchronously
Support for a reference host base implementation of PSRP for interactive scripts
Swift 3 Update
Replace
Selector("tapFunction:")
with
#selector(DetailViewController.tapFunction)
Example:
class DetailViewController: UIViewController {
@IBOutlet weak var tripDetails: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
...
let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction))
tripDetails.isUserInteractionEnabled = true
tripDetails.addGestureRecognizer(tap)
}
@objc
func tapFunction(sender:UITapGestureRecognizer) {
print("tap working")
}
}
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
I have solved following this way
import { Router, ActivatedRoute } from '@angular/router';
constructor(private router: Router
, private activeRoute: ActivatedRoute) {
}
reloadCurrentPage(){
let currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'
Now rows that were like
http://www.example.com/articles/updates/43
will be
http://www.example.com/articles/news/43
There are multiple schemas for "JUnit" and "xUnit" results.
model/xsd
)Please note that there are several versions of the schema in use by the Jenkins xunit-plugin (the current latest version is junit-10.xsd
which adds support for Erlang/OTP Junit format).
Some testing frameworks as well as "xUnit"-style reporting plugins also use their own secret sauce to generate "xUnit"-style reports, those may not use a particular schema (please read: they try to but the tools may not validate against any one schema). Python unittests in Jenkins? gives a quick comparison of several of these libraries and slight differences between the xml reports generated.
For people that have PowerShell 3 or later (i.e. Windows Server 2012+ or Windows Server 2008 R2 with the Windows Management Framework 4.0 update), you can do this one-liner instead of invoking System.Net.WebRequest
:
$statusCode = wget http://stackoverflow.com/questions/20259251/ | % {$_.StatusCode}
You can use exit method to quit an ios app :
exit(0);
You should say same alert message and ask him to quit
Another way is by using [[NSThread mainThread] exit]
However you should not do this way
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
This is the sort of thing that the CSS flexbox model will fix, because it will let you specify that each li will receive an equal proportion of the remaining width.
I see that a few important reasons for doing as few new's as possible are missed:
new
has a non-deterministic execution timeCalling new
may or may not cause the OS to allocate a new physical page to your process this can be quite slow if you do it often. Or it may already have a suitable memory location ready, we don't know. If your program needs to have consistent and predictable execution time (like in a real-time system or game/physics simulation) you need to avoid new
in your time critical loops.
new
is an implicit thread synchronizationYes you heard me, your OS needs to make sure your page tables are consistent and as such calling new
will cause your thread to acquire an implicit mutex lock. If you are consistently calling new
from many threads you are actually serialising your threads (I've done this with 32 CPUs, each hitting on new
to get a few hundred bytes each, ouch! that was a royal p.i.t.a. to debug)
The rest such as slow, fragmentation, error prone, etc have already been mentioned by other answers.
For those having this issue when building a Docker image with Jenkins (or any CI), make sure the package-lock.json
is also copied to the container.
COPY ./src/package*.json /home/node/
RUN npm install
For us, the install actually went fine, the error only occurred when running npm prune production
for the production image.
This can happen when you link to msvcrt.dll instead of msvcr10.dll (or similar), which is a good plan. Because it will free you up to redistribute your Visual Studio's runtime library inside your final software package.
That workaround helps me (at Visual Studio 2008):
#if _MSC_VER >= 1400
#undef stdin
#undef stdout
#undef stderr
extern "C" _CRTIMP extern FILE _iob[];
#define stdin _iob
#define stdout (_iob+1)
#define stderr (_iob+2)
#endif
This snippet is not needed for Visual Studio 6 and its compiler. Therefore the #ifdef.
If you don't want to rely on third party API's, here is a working code for JDK7 or below. I am not instantiating temporary Character Objects as done by other solutions above. foreach loops are more readable, see yourself :)
public static Character[] convertStringToCharacterArray(String str) {
if (str == null || str.isEmpty()) {
return null;
}
char[] c = str.toCharArray();
final int len = c.length;
int counter = 0;
final Character[] result = new Character[len];
while (len > counter) {
for (char ch : c) {
result[counter++] = ch;
}
}
return result;
}
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
Yes, window.onfocus
and window.onblur
should work for your scenario:
http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
Sorted set:
return new TreeSet(setIWantSorted);
or:
return new ArrayList(new TreeSet(setIWantSorted));
in your device you want to run app on Go to settings About device >> Build number triple clicks or more and back to settings you will found "Developer options" appear go to and click on "USB debugging" Done
I could able to make it work only by adding GRANT OPTION
, without that always receive permission denied error
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost' WITH GRANT OPTION;
If you just want to delete the address assigned to the user and not to affect on User entity class you should try something like that:
@Entity
public class User {
@OneToMany(mappedBy = "addressOwner", cascade = CascadeType.ALL)
protected Set<Address> userAddresses = new HashSet<>();
}
@Entity
public class Addresses {
@ManyToOne(cascade = CascadeType.REFRESH) @JoinColumn(name = "user_id")
protected User addressOwner;
}
This way you dont need to worry about using fetch in annotations. But remember when deleting the User you will also delete connected address to user object.
Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.
Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?
Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).
from numpy import arange
from timeit import Timer
Nelements = 10000
Ntimeits = 10000
x = arange(Nelements)
y = range(Nelements)
t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list: %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))
which on my systems (while I'm running a backup) gives:
numpy: 3.004e-05
list: 5.363e-04
I simply use a FloatingActionButton
with elevation = 0dp
to remove the shadow:
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_send"
app:elevation="0dp" />
This is not a bug but PHP normal behavior. It happens because the ==
operator in PHP doesn't check for type.
'' == null == 0 == false
If you want also to check if the values have the same type, use ===
instead. To study in deep this difference, please read the official documentation.
Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.
{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li> {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}
I had the same problem and I fixed it with simple JS. The input:
<input type="date" name="dateOrder" id="dateOrder" required="required">
the JS
<script language="javascript">
document.getElementById('dateOrder').value = "<?php echo date("Y-m-d"); ?>";
</script>
Important: the JS script should be in the last code line, or after to input, because if you put this code before, the script won't find your input.
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
With the latest Firefox, I must use:
<script type="text/javascript">...</script>
Or else the script may not run properly.
To kill a process by a specific keyword you could create an alias in ~/.bashrc
(linux) or ~/.bash_profile
(mac).
alias killps="kill -9 `ps -ef | grep '[k]eyword' | awk '{print $2}'`"
Almost all Oracle deployments are done through SQL*Plus (that weird little command line tool that your DBA uses). And in SQL*Plus a lone slash basically means "re-execute last SQL or PL/SQL command that I just executed".
See
Rule of thumb would be to use slash with things that do BEGIN .. END
or where you can use CREATE OR REPLACE
.
For inserts that need to be unique use
INSERT INTO my_table ()
SELECT <values to be inserted>
FROM dual
WHERE NOT EXISTS (SELECT
FROM my_table
WHERE <identify data that you are trying to insert>)
<?php
$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];
if($browser_ver['browser'] == 'IE') {
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
html { height:100%; }
</style>
<script>
function printIt(id) {
var pdf = document.getElementById("samplePDF");
pdf.click();
pdf.setActive();
pdf.focus();
pdf.print();
}
</script>
</head>
<body style="margin:0; height:100%;">
<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" />
<button onClick="printIt('samplePDF')">Print</button>
</body>
</html>
<?php
} else {
?>
<HTML>
<script Language="javascript">
function printfile(id) {
window.frames[id].focus();
window.frames[id].print();
}
</script>
<BODY marginheight="0" marginwidth="0">
<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe><br>
<input type="button" value="Print" onclick="javascript:printfile('objAdobePrint');">
</BODY>
</HTML>
<?php
}
?>
Your working tree are the files that you are currently working on.
The git "index" is where you place files you want commit to the git repository.
The index is also known as cache, directory cache, current directory cache, staging area, staged files.
Before you "commit" (checkin) files to the git repository, you need to first place the files in the git "index".
The index is not the working directory: you can type a command such as git status
, and git will tell you what files in your working directory have been added to the git index (for example, by using the git add filename
command).
The index is not the git repository: files in the git index are files that git would commit to the git repository if you used the git commit command.
Try this
$data = array(
'email' =>$email,
'last_ip' => $last_ip
);
$where = array('username ' => $username , 'status ' => $status);
$this->db->where($where);
$this->db->update('table_user ', $data);
For Windows 7:
Control Panel > Programs > Programs and Features > Turn Windows Features On or Off > to turn on IIS click on Check box.
Try with
f.mkdirs()
then createNewFile()
SELECT column1 FROM table WHERE column1 not like '%[0-9]%'
Removing the '^' did it for me. I'm looking at a varchar field and when I included the ^ it excluded all of my non-numerics which is exactly what I didn't want. So, by removing ^ I only got non-numeric values back.
To deal with the following special cases in Ray casting algorithm:
Check Determining Whether A Point Is Inside A Complex Polygon. The article provides an easy way to resolve them so there will be no special treatment required for the above cases.
Some may want to simply suppress the warning:
class SupressSettingWithCopyWarning:
def __enter__(self):
pd.options.mode.chained_assignment = None
def __exit__(self, *args):
pd.options.mode.chained_assignment = 'warn'
with SupressSettingWithCopyWarning():
#code that produces warning
If you just want to check string equality, use the == operator. Determining whether two strings are equal is simpler than finding an ordering (which is what compare() gives,) so it might be better performance-wise in your case to use the equality operator.
Longer answer: The API provides a method to check for string equality and a method to check string ordering. You want string equality, so use the equality operator (so that your expectations and those of the library implementors align.) If performance is important then you might like to test both methods and find the fastest.
Task.WaitAll
blocks the current thread until everything has completed.
Task.WhenAll
returns a task which represents the action of waiting until everything has completed.
That means that from an async method, you can use:
await Task.WhenAll(tasks);
... which means your method will continue when everything's completed, but you won't tie up a thread to just hang around until that time.
this might be helpful:
// Operator overloading in C++
//assignment operator overloading
#include<iostream>
using namespace std;
class Employee
{
private:
int idNum;
double salary;
public:
Employee ( ) {
idNum = 0, salary = 0.0;
}
void setValues (int a, int b);
void operator= (Employee &emp );
};
void Employee::setValues ( int idN , int sal )
{
salary = sal; idNum = idN;
}
void Employee::operator = (Employee &emp) // Assignment operator overloading function
{
salary = emp.salary;
}
int main ( )
{
Employee emp1;
emp1.setValues(10,33);
Employee emp2;
emp2 = emp1; // emp2 is calling object using assignment operator
}
If you want to allow the user to browse for a file, you need to have an input type="file"
The closest you could get to your requirement would be to place the input type="file"
on the page and hide it. Then, trigger the click event of the input when the button is clicked:
#myFileInput {
display:none;
}
<input type="file" id="myFileInput" />
<input type="button"
onclick="document.getElementById('myFileInput').click()"
value="Select a File" />
Here's a working fiddle.
Note: I would not recommend this approach. The input type="file"
is the mechanism that users are accustomed to using for uploading a file.
There are two kinds of cell reference, and it's really valuable to understand them well.
One is relative reference, which is what you get when you just type the cell: A5
. This reference will be adjusted when you paste or fill the formula into other cells.
The other is absolute reference, and you get this by adding dollar signs to the cell reference: $A$5
. This cell reference will not change when pasted or filled.
A cool but rarely used feature is that row and column within a single cell reference may be independent: $A5
and A$5
. This comes in handy for producing things like multiplication tables from a single formula.
Don_crissti's answer from Show only text between 2 matching pattern?
firstmatch="abc"
secondmatch="cdf"
sed "/$firstmatch/,/$secondmatch/!d;//d" infile
which is much more efficient than AWK's application, see here.
In file /etc/ssh/sshd_config
# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication no
Uncomment the second line, and, if needed, change yes to no.
Then run
service ssh restart
An easy way to check the CPU usage is to use the adb tool w/ top. I.e.:
adb shell top -m 10
You can do this with CSS:
@media only screen and (max-width: 1026px) {
#fadeshow1 {
display: none;
}
}
We're using max-width
, because we want to make an exception to the CSS, when a screen is smaller than the 1026px.
min-width
would make the CSS rule count for all screens of 1026px width and larger.
Something to keep in mind is that @media
queries are not supported on IE8 and lower.
You need to use the CONCAT()
function in MySQL for string concatenation:
UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;
dumpbin
from the Visual Studio command prompt:
dumpbin /exports csp.dll
Example of output:
Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file csp.dll
File Type: DLL
Section contains the following exports for CSP.dll
00000000 characteristics
3B1D0B77 time date stamp Tue Jun 05 12:40:23 2001
0.00 version
1 ordinal base
25 number of functions
25 number of names
ordinal hint RVA name
1 0 00001470 CPAcquireContext
2 1 000014B0 CPCreateHash
3 2 00001520 CPDecrypt
4 3 000014B0 CPDeriveKey
5 4 00001590 CPDestroyHash
6 5 00001590 CPDestroyKey
7 6 00001560 CPEncrypt
8 7 00001520 CPExportKey
9 8 00001490 CPGenKey
10 9 000015B0 CPGenRandom
11 A 000014D0 CPGetHashParam
12 B 000014D0 CPGetKeyParam
13 C 00001500 CPGetProvParam
14 D 000015C0 CPGetUserKey
15 E 00001580 CPHashData
16 F 000014F0 CPHashSessionKey
17 10 00001540 CPImportKey
18 11 00001590 CPReleaseContext
19 12 00001580 CPSetHashParam
20 13 00001580 CPSetKeyParam
21 14 000014F0 CPSetProvParam
22 15 00001520 CPSignHash
23 16 000015A0 CPVerifySignature
24 17 00001060 DllRegisterServer
25 18 00001000 DllUnregisterServer
Summary
1000 .data
1000 .rdata
1000 .reloc
1000 .rsrc
1000 .text
Only suggestion is to access your resp_dict
via .get()
for a more graceful approach that will degrade well if the data isn't as expected.
resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist
You could also add some logic to test for the key if you want as well.
if 'name' in resp_dict:
resp_dict['name']
else:
# do something else here.
Give the canvas the following css style properties:
canvas {
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
width: 800px;
}
Edit
Since this answer is quite popular, let me add a little bit more details.
The above properties will horizontally center the canvas, div or whatever other node you have relative to it's parent. There is no need to change the top or bottom margins and paddings. You specify a width and let the browser fill the remaining space with the auto margins.
However, if you want to type less, you could use whatever css shorthand properties you wish, such as
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
}
Centering the canvas vertically requires a different approach however. You need to use absolute positioning, and specify both the width and the height. Then set the left, right, top and bottom properties to 0 and let the browser fill the remaining space with the auto margins.
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
height: 600px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
The canvas will center itself based on the first parent element that has position
set to relative
or absolute
, or the body if none is found.
Another approach would be to use display: flex
, that is available in IE11
Also, make sure you use a recent doctype such as xhtml or html 5.
Found it.
run cmd as administrator, go to your system32\inetsrv folder and execute:
appcmd.exe set config -section:system.webServer/httpErrors -allowAbsolutePathsWhenDelegated:true
Now I can see detailed asp errors .
Try listening for events in the parent document and passing the event to a handler in the iframe document.
There are three ways to resolve this issue.
Right click the project and click "Properties". Then select "Android" from left. You can then select the target version from right side.
Right Click on Project and select "run as" , then a drop down list will be open.
Select "Run Configuration" from Drop Down list.Then a form will be open ,
Select "Target" tab from "Form" and also select Android Version Api ,
On which you want to execute your application, it is a fastest way to check
your application on different Target Version.
Edit the following elements in the AndroidManifest.xml file
xml:
<uses-sdk android:minSdkVersion="3" />
<uses-sdk android:targetSdkVersion="8" />
With Python>3.5, using glob, .
pointing to your current folder and looking for .txt
files:
python -c "import glob;[print(x) for x in glob.glob('./**/*txt', recursive=True)]"
For older versions of Python, you can install glob2
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('path/to/folder'));
$files = array();
foreach ($rii as $file) {
if ($file->isDir()){
continue;
}
$files[] = $file->getPathname();
}
var_dump($files);
This will bring you all the files with paths.
I found the answer!! Taking a screenshot interrupts any touches that are on the screen. This is why snapchat requires holding to see the picture. Reference: http://tumblr.jeremyjohnstone.com/post/38503925370/how-to-detect-screenshots-on-ios-like-snapchat
Use the ExecuteStoreQuery method of the entity context. This avoids downloading the entire result set and deserializing into objects to do a simple row count.
int count;
using (var db = new MyDatabase()){
string sql = "SELECT COUNT(*) FROM MyTable where FkId = {0}";
object[] myParams = {1};
var cntQuery = db.ExecuteStoreQuery<int>(sql, myParams);
count = cntQuery.First<int>();
}
As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.
You need to wrap your .myTestClass
inside an element and apply the styles to descendants by adding .wrapper *
descendant selector. Then, add .myTestClass > *
child selector to apply the style to the elements children, not its grand children. For example like this:
JSFiddle - DEMO
.wrapper * {_x000D_
color: blue;_x000D_
margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
color:red;_x000D_
margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="myTestClass">Text 0_x000D_
<div>Text 1</div>_x000D_
<span>Text 1</span>_x000D_
<div>Text 1_x000D_
<p>Text 2</p>_x000D_
<div>Text 2</div>_x000D_
</div>_x000D_
<p>Text 1</p>_x000D_
</div>_x000D_
<div>Text 0</div>_x000D_
</div>
_x000D_
alternative would be javascript and forwarding via the onclick event
<div onclick="window.location.href='somewhere...';">...</div>
Since scikit-learn 0.20 you can use sklearn.compose.ColumnTransformer
and sklearn.preprocessing.OneHotEncoder
:
If you only have categorical variables, OneHotEncoder
directly:
from sklearn.preprocessing import OneHotEncoder
OneHotEncoder(handle_unknown='ignore').fit_transform(df)
If you have heterogeneously typed features:
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import OneHotEncoder
categorical_columns = ['pets', 'owner', 'location']
numerical_columns = ['age', 'weigth', 'height']
column_trans = make_column_transformer(
(categorical_columns, OneHotEncoder(handle_unknown='ignore'),
(numerical_columns, RobustScaler())
column_trans.fit_transform(df)
More options in the documentation: http://scikit-learn.org/stable/modules/compose.html#columntransformer-for-heterogeneous-data
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)The error means that you are providing not as much data as the table wp_posts
does contain columns. And now the DB engine does not know in which columns to put your data.
To overcome this you must provide the names of the columns you want to fill. Example:
insert into wp_posts (column_name1, column_name2)
values (1, 3)
Look up the table definition and see which columns you want to fill.
And insert
means you are inserting a new record. You are not modifying an existing one. Use update
for that.
Constructor injection is used when the class cannot function without the dependent class.
Property injection is used when the class can function without the dependent class.
As a concrete example, consider a ServiceRepository which depends on IService to do its work. Since ServiceRepository cannot function usefully without IService, it makes sense to have it injected via the constructor.
The same ServiceRepository class may use a Logger to do tracing. The ILogger can be injected via Property injection.
Other common examples of Property injection are ICache (another aspect in AOP terminology) or IBaseProperty (a property in the base class).
Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016)
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue()
fp.close()
device.close()
retstr.close()
return text
PDFMiner's structure changed recently, so this should work for extracting text from the PDF files.
Edit : Still working as of the June 7th of 2018. Verified in Python Version 3.x
Edit: The solution works with Python 3.7 at October 3, 2019. I used the Python library pdfminer.six
, released on November 2018.
Hope you been through this , if not please read.
https://developer.android.com/reference/android/os/AsyncTask
Depending on the nature of result data, you should choose best possible option you can think of.
It is a great choice to use an Interface
some other options would be..
If the AsyncTask class is defined inside the very class you want to use the result in.Use a static global variable or get() , use it from outer class (volatile variable if necessary). but should be aware of the AsyncTask progress or should at least make sure that it have finished the task and result is available through global variable / get() method. you may use polling, onProgressUpdate(Progress...), synchronization or interfaces (Which ever suits best for you)
If the Result is compatible to be a sharedPreference entry or it is okay to be saved as a file in the memory you could save it even from
the background task itself and could use the onPostExecute() method
to get notified when the result is available in the memory.
If the string is small enough, and is to be used with start of an activity. it is possible to use intents (putExtra()) within onPostExecute() , but remember that static contexts aren't that safe to deal with.
If possible, you can call a static method from the onPostExecute() method, with the result being your parameter
I believe that main()
should return either EXIT_SUCCESS
or EXIT_FAILURE
. They are defined in stdlib.h
If you really can't use pointers, do something like this:
char get_string_char(int index)
{
static char array[] = "my string";
return array[index];
}
int main()
{
for (int i = 0; i < 9; ++i)
printf("%c", get_string_char(i));
printf("\n");
return 0;
}
The magic number 9 is awful, and this is not an example of good programming. But you get the point. Note that pointers and arrays are the same thing (kind of), so this is a bit cheating.
Click Product
> Archive
from the menu, once this is complete open up the Organiser
and click the latest version > Distribute
> Save for Enterprise or Ad-Hoc Deployment
> Choose correct signing > Save to destination
Here is a way to change the owner on ALL DBS (excluding System)
EXEC sp_msforeachdb'
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
exec sp_changedbowner ''sa''
END
'