A numpy single-element array is mutable and yet for most purposes, it can be evaluated as if it was a numerical python variable. Therefore, it's a more convenient by-reference number container than a single-element list.
import numpy as np
def triple_var_by_ref(x):
x[0]=x[0]*3
a=np.array([2])
triple_var_by_ref(a)
print(a+1)
output:
3
I think this simple explanation might help you understand as I wanted to understand this same thing when I was struggling through this.
When you pass a primitive data to a function call it's content is being copied to the function's argument and when you pass an object it's reference is being copied to the function's argument. Speaking of object, you can't change the copied reference-the argument variable is referencing to in the calling function.
Consider this simple example, String is an object in java and when you change the content of a string the reference variable will now point to some new reference as String objects are immutable in java.
String name="Mehrose"; // name referencing to 100
ChangeContenet(String name){
name="Michael"; // refernce has changed to 1001
}
System.out.print(name); //displays Mehrose
Fairly simple because as I mentioned you are not allowed to change the copied reference in the calling function. But the problem is with the array when you pass an array of String/Object. Let us see.
String names[]={"Mehrose","Michael"};
changeContent(String[] names){
names[0]="Rose";
names[1]="Janet"
}
System.out.println(Arrays.toString(names)); //displays [Rose,Janet]
As we said that we can't change the copied reference in the function call and we also have seen in the case of a single String object. The reason is names[] variable referencing to let's say 200 and names[0] referencing to 205 and so on. You see we didn't change the names[] reference it still points to the old same reference still after the function call but now names[0] and names[1] reference has been changed. We Still stand on our definition that we can't change the reference variable's reference so we didn't.
The same thing happens when you pass a Student object to a method and you are still able to change the Student name or other attributes, the point is we are not changing the actual Student object rather we are changing the contents of it
You can't do this
Student student1= new Student("Mehrose");
changeContent(Student Obj){
obj= new Student("Michael") //invalid
obj.setName("Michael") //valid
}
There are some differences in calling conventions in C++ and Java. In C++ there are technically speaking only two conventions: pass-by-value and pass-by-reference, with some literature including a third pass-by-pointer convention (that is actually pass-by-value of a pointer type). On top of that, you can add const-ness to the type of the argument, enhancing the semantics.
Pass by reference
Passing by reference means that the function will conceptually receive your object instance and not a copy of it. The reference is conceptually an alias to the object that was used in the calling context, and cannot be null. All operations performed inside the function apply to the object outside the function. This convention is not available in Java or C.
Pass by value (and pass-by-pointer)
The compiler will generate a copy of the object in the calling context and use that copy inside the function. All operations performed inside the function are done to the copy, not the external element. This is the convention for primitive types in Java.
An special version of it is passing a pointer (address-of the object) into a function. The function receives the pointer, and any and all operations applied to the pointer itself are applied to the copy (pointer), on the other hand, operations applied to the dereferenced pointer will apply to the object instance at that memory location, so the function can have side effects. The effect of using pass-by-value of a pointer to the object will allow the internal function to modify external values, as with pass-by-reference and will also allow for optional values (pass a null pointer).
This is the convention used in C when a function needs to modify an external variable, and the convention used in Java with reference types: the reference is copied, but the referred object is the same: changes to the reference/pointer are not visible outside the function, but changes to the pointed memory are.
Adding const to the equation
In C++ you can assign constant-ness to objects when defining variables, pointers and references at different levels. You can declare a variable to be constant, you can declare a reference to a constant instance, and you can define all pointers to constant objects, constant pointers to mutable objects and constant pointers to constant elements. Conversely in Java you can only define one level of constant-ness (final keyword): that of the variable (instance for primitive types, reference for reference types), but you cannot define a reference to an immutable element (unless the class itself is immutable).
This is extensively used in C++ calling conventions. When the objects are small you can pass the object by value. The compiler will generate a copy, but that copy is not an expensive operation. For any other type, if the function will not change the object, you can pass a reference to a constant instance (usually called constant reference) of the type. This will not copy the object, but pass it into the function. But at the same time the compiler will guarantee that the object is not changed inside the function.
Rules of thumb
This are some basic rules to follow:
There are other small deviations from these rules, the first of which is handling ownership of an object. When an object is dynamically allocated with new, it must be deallocated with delete (or the [] versions thereof). The object or function that is responsible for the destruction of the object is considered the owner of the resource. When a dynamically allocated object is created in a piece of code, but the ownership is transfered to a different element it is usually done with pass-by-pointer semantics, or if possible with smart pointers.
Side note
It is important to insist in the importance of the difference between C++ and Java references. In C++ references are conceptually the instance of the object, not an accessor to it. The simplest example is implementing a swap function:
// C++
class Type; // defined somewhere before, with the appropriate operations
void swap( Type & a, Type & b ) {
Type tmp = a;
a = b;
b = tmp;
}
int main() {
Type a, b;
Type old_a = a, old_b = b;
swap( a, b );
assert( a == old_b );
assert( b == old_a );
}
The swap function above changes both its arguments through the use of references. The closest code in Java:
public class C {
// ...
public static void swap( C a, C b ) {
C tmp = a;
a = b;
b = tmp;
}
public static void main( String args[] ) {
C a = new C();
C b = new C();
C old_a = a;
C old_b = b;
swap( a, b );
// a and b remain unchanged a==old_a, and b==old_b
}
}
The Java version of the code will modify the copies of the references internally, but will not modify the actual objects externally. Java references are C pointers without pointer arithmetic that get passed by value into functions.
I'm not sure if I understand your question correctly. It is a bit unclear. However, what might be confusing you is the following:
When passing by reference, a reference to the same object is passed to the function being called. Any changes to the object will be reflected in the original object and hence the caller will see it.
When passing by value, the copy constructor will be called. The default copy constructor will only do a shallow copy, hence, if the called function modifies an integer in the object, this will not be seen by the calling function, but if the function changes a data structure pointed to by a pointer within the object, then this will be seen by the caller due to the shallow copy.
I might have mis-understood your question, but I thought I would give it a stab anyway.
Yes, excluding anonymous classes, readability and intent declaration it's almost worthless. Are those three things worthless though?
Personally I tend not to use final
for local variables and parameters unless I'm using the variable in an anonymous inner class, but I can certainly see the point of those who want to make it clear that the parameter value itself won't change (even if the object it refers to changes its contents). For those who find that adds to readability, I think it's an entirely reasonable thing to do.
Your point would be more important if anyone were actually claiming that it did keep data constant in a way that it doesn't - but I can't remember seeing any such claims. Are you suggesting there's a significant body of developers suggesting that final
has more effect than it really does?
EDIT: I should really have summed all of this up with a Monty Python reference; the question seems somewhat similar to asking "What have the Romans ever done for us?"
Pass by value sends a COPY of the data stored in the variable you specify, pass by reference sends a direct link to the variable itself. So if you pass a variable by reference and then change the variable inside the block you passed it into, the original variable will be changed. If you simply pass by value, the original variable will not be able to be changed by the block you passed it into but you will get a copy of whatever it contained at the time of the call.
PHP variables are assigned by value, passed to functions by value and when containing/representing objects are passed by reference. You can force variables to pass by reference using an '&'.
Assigned by value/reference example:
$var1 = "test";
$var2 = $var1;
$var2 = "new test";
$var3 = &$var2;
$var3 = "final test";
print ("var1: $var1, var2: $var2, var3: $var3);
output:
var1: test, var2: final test, var3: final test
Passed by value/reference example:
$var1 = "foo";
$var2 = "bar";
changeThem($var1, $var2);
print "var1: $var1, var2: $var2";
function changeThem($var1, &$var2){
$var1 = "FOO";
$var2 = "BAR";
}
output:
var1: foo, var2 BAR
Object variables passed by reference example:
class Foo{
public $var1;
function __construct(){
$this->var1 = "foo";
}
public function printFoo(){
print $this->var1;
}
}
$foo = new Foo();
changeFoo($foo);
$foo->printFoo();
function changeFoo($foo){
$foo->var1 = "FOO";
}
output:
FOO
(The last example could be better probably.)
Think of it like this:
Whenever you create an object in ECMAscript, this object is formed in a mystique ECMAscript universal place where no man will ever be able to get. All you get back is a reference to that object in this mystique place.
var obj = { };
Even obj
is only a reference to the object (which is located in that special wonderful place) and hence, you can only pass this reference around. Effectively, any piece of code which accesses obj will modify the object which is far, far away.
For the second part of your question, see the array page of the manual, which states (quoting) :
Array assignment always involves value copying. Use the reference operator to copy an array by reference.
And the given example :
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
For the first part, the best way to be sure is to try ;-)
Consider this example of code :
function my_func($a) {
$a[] = 30;
}
$arr = array(10, 20);
my_func($arr);
var_dump($arr);
It'll give this output :
array
0 => int 10
1 => int 20
Which indicates the function has not modified the "outside" array that was passed as a parameter : it's passed as a copy, and not a reference.
If you want it passed by reference, you'll have to modify the function, this way :
function my_func(& $a) {
$a[] = 30;
}
And the output will become :
array
0 => int 10
1 => int 20
2 => int 30
As, this time, the array has been passed "by reference".
Don't hesitate to read the References Explained section of the manual : it should answer some of your questions ;-)
Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.
An example:
function changeParam(x, y, z) {
x = 3;
y = "new string";
z["key2"] = "new";
z["key3"] = "newer";
z = {"new" : "object"};
}
var a = 1,
b = "something",
c = {"key1" : "whatever", "key2" : "original value"};
changeParam(a, b, c);
// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...
In Pass By Reference You only add "ref" in the function parameters and one
more thing you should be declaring function "static" because of main is static(#public void main(String[] args)
)!
namespace preparation
{
public class Program
{
public static void swap(ref int lhs,ref int rhs)
{
int temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a = 10;
int b = 80;
Console.WriteLine("a is before sort " + a);
Console.WriteLine("b is before sort " + b);
swap(ref a, ref b);
Console.WriteLine("");
Console.WriteLine("a is after sort " + a);
Console.WriteLine("b is after sort " + b);
}
}
}
well, it's about 'performance' and 'speed' and in the simple word 'memory management' in a programming language.
in javascript we can put values in two layer: type1-objects
and type2-all other types of value such as string
& boolean
& etc
if you imagine memory as below squares which in every one of them just one type2-value can be saved:
every type2-value (green) is a single square while a type1-value (blue) is a group of them:
the point is that if you want to indicate a type2-value, the address is plain but if you want to do the same thing for type1-value that's not easy at all! :
and in a more complicated story:
so here references can rescue us:
while the green arrow here is a typical variable, the purple one is an object variable, so because the green arrow(typical variable) has just one task (and that is indicating a typical value) we don't need to separate it's value from it so we move the green arrow with the value of that wherever it goes and in all assignments, functions and so on ...
but we cant do the same thing with the purple arrow, we may want to move 'john' cell here or many other things..., so the purple arrow will stick to its place and just typical arrows that were assigned to it will move ...
a very confusing situation is where you can't realize how your referenced variable changes, let's take a look at a very good example:
let arr = [1, 2, 3, 4, 5]; //arr is an object now and a purple arrow is indicating it
let obj2 = arr; // now, obj2 is another purple arrow that is indicating the value of arr obj
let obj3 = ['a', 'b', 'c'];
obj2.push(6); // first pic below - making a new hand for the blue circle to point the 6
//obj2 = [1, 2, 3, 4, 5, 6]
//arr = [1, 2, 3, 4, 5, 6]
//we changed the blue circle object value (type1-value) and due to arr and obj2 are indicating that so both of them changed
obj2 = obj3; //next pic below - changing the direction of obj2 array from blue circle to orange circle so obj2 is no more [1,2,3,4,5,6] and it's no more about changing anything in it but we completely changed its direction and now obj2 is pointing to obj3
//obj2 = ['a', 'b', 'c'];
//obj3 = ['a', 'b', 'c'];
Edit: New article by Dave Abrahams on cpp-next:
Pass by value for structs where the copying is cheap has the additional advantage that the compiler may assume that the objects don't alias (are not the same objects). Using pass-by-reference the compiler cannot assume that always. Simple example:
foo * f;
void bar(foo g) {
g.i = 10;
f->i = 2;
g.i += 5;
}
the compiler can optimize it into
g.i = 15;
f->i = 2;
since it knows that f and g doesn't share the same location. if g was a reference (foo &), the compiler couldn't have assumed that. since g.i could then be aliased by f->i and have to have a value of 7. so the compiler would have to re-fetch the new value of g.i from memory.
For more pratical rules, here is a good set of rules found in Move Constructors article (highly recommended reading).
"Primitive" above means basically small data types that are a few bytes long and aren't polymorphic (iterators, function objects, etc...) or expensive to copy. In that paper, there is one other rule. The idea is that sometimes one wants to make a copy (in case the argument can't be modified), and sometimes one doesn't want (in case one wants to use the argument itself in the function if the argument was a temporary anyway, for example). The paper explains in detail how that can be done. In C++1x that technique can be used natively with language support. Until then, i would go with the above rules.
Examples: To make a string uppercase and return the uppercase version, one should always pass by value: One has to take a copy of it anyway (one couldn't change the const reference directly) - so better make it as transparent as possible to the caller and make that copy early so that the caller can optimize as much as possible - as detailed in that paper:
my::string uppercase(my::string s) { /* change s and return it */ }
However, if you don't need to change the parameter anyway, take it by reference to const:
bool all_uppercase(my::string const& s) {
/* check to see whether any character is uppercase */
}
However, if you the purpose of the parameter is to write something into the argument, then pass it by non-const reference
bool try_parse(T text, my::string &out) {
/* try to parse, write result into out */
}
If you look for POSIX compliant solution:
cd DirsRoot && find . -type f -print -o -name . -o -prune
-maxdepth is not POSIX compliant option.
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
repartition/coalesce to 1 partition before you save (you'd still get a folder but it would have one part file in it)
Maybe one of the easiest solutions would be to use the x
descriptor of the srcset
attribute as such:
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />
<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />
<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
Currently supported by all browsers except IE. (caniuse)
n = 1 # N. . .
[x[n] for x in elements]
Use the following query:
SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1
Note: Sqlite's row id references are detailed here.
I just installed Linux Mint 19 (based on Ubuntu 18.04) on my machine. I installed MySQL 5.7 from the repo (sudo apt install mysql-server) and surprisingly during installation, the setup didn't prompt to enter root password. As a result I wasn't able to login into MySQL. I googled here and there and tried various answers I found on the net, including the accepted answer above. I uninstalled (purging all dpkgs with mysql in its name) and reinstalled again from the default Linux Mint repositories. NONE works.
After hours of unproductive works, I decided to reinstall MySQL from the official page. I opened MySQL download page (https://dev.mysql.com/downloads/repo/apt) for apt repo and clicked Download button at the bottom right.
Next, run it with dpkg:
sudo dpkg -i mysql-apt-config_0.8.10-1_all.deb
At the installation setup, choose the MySQL version that you'd like to install. The default option is 8.0 but I changed it to 5.7. Click OK to quit. After this, you have a new MySQL repo in your Software Sources.
Update your repo:
sudo apt update
Finally, install MySQL:
sudo apt install mysql-server
And now I was prompted to provide root password! Hope it helps for others with this same experience.
Here is the simplest example that has the key lines of code:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
plt.imshow(H, interpolation='none')
plt.show()
gcloud config set project my-project
You may also set the environment variable $CLOUDSDK_CORE_PROJECT
.
You can use
docker exec -it <container_name> bash
If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:
NET USE z: \server\c$\folder1\folder2
NET USE y: \server\d$
Note that you can map drive-to-drive or drill down and map to sub-folder.
//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]
The reason why I add this answer is that I want to explain the relationship of .
and text()
.
The first thing is when using []
, there are only two types of data:
[number]
to select a node from node-set[bool]
to filter a node-set from node-setIn this case, the value is evaluated to boolean by function boolean()
, and there is a rule:
Filters are always evaluated with respect to a context.
When you need to compare text()
or .
with a string "Data"
, it first uses string()
function to transform those to string type, than gets a boolean result.
There are two important rule about string()
:
The string()
function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.
text()
is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]
.
When it is evaluated by string(["Data"])
, it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.
If you want the string()
function to concatenate all child text, you must then pass a single node instead of a node-set.
For example, we get a node-set ['a', 'b']
, you can pass there parent node to string(parent)
, this will return 'ab'
, and of cause string(.)
in you case will return an concatenated string "Data"
.
Both way will get same result only when there is a text node.
This is the one I use:
set statusline=
set statusline+=%7*\[%n] "buffernr
set statusline+=%1*\ %<%F\ "File+path
set statusline+=%2*\ %y\ "FileType
set statusline+=%3*\ %{''.(&fenc!=''?&fenc:&enc).''} "Encoding
set statusline+=%3*\ %{(&bomb?\",BOM\":\"\")}\ "Encoding2
set statusline+=%4*\ %{&ff}\ "FileFormat (dos/unix..)
set statusline+=%5*\ %{&spelllang}\%{HighlightSearch()}\ "Spellanguage & Highlight on?
set statusline+=%8*\ %=\ row:%l/%L\ (%03p%%)\ "Rownumber/total (%)
set statusline+=%9*\ col:%03c\ "Colnr
set statusline+=%0*\ \ %m%r%w\ %P\ \ "Modified? Readonly? Top/bot.
Highlight on? function:
function! HighlightSearch()
if &hls
return 'H'
else
return ''
endif
endfunction
Colors (adapted from ligh2011.vim):
hi User1 guifg=#ffdad8 guibg=#880c0e
hi User2 guifg=#000000 guibg=#F4905C
hi User3 guifg=#292b00 guibg=#f4f597
hi User4 guifg=#112605 guibg=#aefe7B
hi User5 guifg=#051d00 guibg=#7dcc7d
hi User7 guifg=#ffffff guibg=#880c0e gui=bold
hi User8 guifg=#ffffff guibg=#5b7fbb
hi User9 guifg=#ffffff guibg=#810085
hi User0 guifg=#ffffff guibg=#094afe
Before defining abstract data types, let us considers the different view of system-defined data types. We all know that by default all primitive data types (int, float, etc.) support basic operations such as addition and subtraction. The system provides the implementations for the primitive data types. For user-defined data types, we also need to define operations. The implementation for these operations can be done when we want to actually use them. That means in general, user-defined data types are defined along with their operations.
To simplify the process of solving problems, we combine the data structures with their operations and we call this "Abstract Data Type". (ADT's).
Commonly used ADT'S include: Linked List, Stacks, Queues, Binary Tree, Dictionaries, Disjoint Sets (Union and find), Hash Tables and many others.
ADT's consist of two types:
1. Declaration of data.
2. Declaration of operation.
Use this
@Cacheable(value="bookCache", key="#isbn + '_' + #checkWarehouse + '_' + #includeUsed")
Systemd which now runs in the majority of distros
Find your user defined services mine was at /usr/lib/systemd/system/
Create a text file with your favorite text editor name it whatever_you_want.service
Put following
Template to the file whatever_you_want.service
[Unit]
Description=webserver Daemon
[Service]
ExecStart=/usr/bin/java -jar /web/server.jar
User=user
[Install]
WantedBy=multi-user.target
Run your service
as super user
$ systemctl start whatever_you_want.service # starts the service
$ systemctl enable whatever_you_want.service # auto starts the service
$ systemctl disable whatever_you_want.service # stops autostart
$ systemctl stop whatever_you_want.service # stops the service
$ systemctl restart whatever_you_want.service # restarts the service
Use \t
and enclose the string with double-quotes:
$chunk = "abc\tdef\tghi";
You can use the standard MaterialCard
included in the official Material Components library.
Use in your layout:
<com.google.android.material.card.MaterialCardView
style="@style/MyCardView"
...>
In your style use the shapeAppearanceOverlay
attribute to customize the shape (the default corner radius is 4dp
)
<style name="MyCardView" parent="@style/Widget.MaterialComponents.CardView">
<item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MaterialCardView.Cut</item>
</style>
<style name="ShapeAppearanceOverlay.MaterialCardView.Cut" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSizeTopRight">8dp</item>
<item name="cornerSizeTopLeft">8dp</item>
<item name="cornerSizeBottomRight">0dp</item>
<item name="cornerSizeBottomLeft">0dp</item>
</style>
You can also use:
<com.google.android.material.card.MaterialCardView
app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MaterialCardView.Cut"
...>
It is the result:
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
I suggest this one:
if [ "$a" = "$b" ]
Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the '=' sign.
Also, be careful of your script header. It's not the same thing whether you use
#!/bin/bash
or
#!/bin/sh
As others said, you can't actually strictly do what you are asking for. That said, all of the tools available to the angular framework are actually available to you as well! What that means is you can actually write your own elements and provide this feature yourself. I wrote one of these up as an example which you can see at the following plunkr (http://plnkr.co/edit/Qrz9zFjc7Ud6KQoNMEI1).
The key parts of this are that I define a "clickable" element (don't do this if you need older IE support). In code that looks like:
<clickable>
<h1>Hello World!</h1>
</clickable>
Then I defined a directive to take this clickable element and turn it into what I want (something that automatically sets up my click event):
app.directive('clickable', function() {
return {
transclude: true,
restrict: 'E',
template: '<div ng-transclude ng-click="handleClick($event)"></div>'
};
});
Finally in my controller I have the click event ready to go:
$scope.handleClick = function($event) {
var i = 0;
};
Now, its worth stating that this hard codes the name of the method that handles the click event. If you wanted to eliminate this, you should be able to provide the directive with the name of your click handler and "tada" - you have an element (or attribute) that you can use and never have to inject "$event" again.
Hope that helps!
You can as long as
I think you're reading those stats incorrectly. They show that Python is up to about 400 times slower than C++ and with the exception of a single case, Python is more of a memory hog. When it comes to source size though, Python wins flat out.
My experiences with Python show the same definite trend that Python is on the order of between 10 and 100 times slower than C++ when doing any serious number crunching. There are many reasons for this, the major ones being: a) Python is interpreted, while C++ is compiled; b) Python has no primitives, everything including the builtin types (int, float, etc.) are objects; c) a Python list can hold objects of different type, so each entry has to store additional data about its type. These all severely hinder both runtime and memory consumption.
This is no reason to ignore Python though. A lot of software doesn't require much time or memory even with the 100 time slowness factor. Development cost is where Python wins with the simple and concise style. This improvement on development cost often outweighs the cost of additional cpu and memory resources. When it doesn't, however, then C++ wins.
Take a look at this , we can simply do this with outline-offset
property
Output image look like
.black_box {_x000D_
width:500px;_x000D_
height:200px;_x000D_
background:#000;_x000D_
float:left;_x000D_
border:2px solid #000;_x000D_
outline: 1px dashed #fff;_x000D_
outline-offset: -10px;_x000D_
}
_x000D_
<div class="black_box"></div>
_x000D_
Required Launch Icon And Splash Image size
I've developed my own MySQL escape method in Java (if useful for anyone).
See class code below.
Warning: wrong if NO_BACKSLASH_ESCAPES SQL mode is enabled.
private static final HashMap<String,String> sqlTokens;
private static Pattern sqlTokenPattern;
static
{
//MySQL escape sequences: http://dev.mysql.com/doc/refman/5.1/en/string-syntax.html
String[][] search_regex_replacement = new String[][]
{
//search string search regex sql replacement regex
{ "\u0000" , "\\x00" , "\\\\0" },
{ "'" , "'" , "\\\\'" },
{ "\"" , "\"" , "\\\\\"" },
{ "\b" , "\\x08" , "\\\\b" },
{ "\n" , "\\n" , "\\\\n" },
{ "\r" , "\\r" , "\\\\r" },
{ "\t" , "\\t" , "\\\\t" },
{ "\u001A" , "\\x1A" , "\\\\Z" },
{ "\\" , "\\\\" , "\\\\\\\\" }
};
sqlTokens = new HashMap<String,String>();
String patternStr = "";
for (String[] srr : search_regex_replacement)
{
sqlTokens.put(srr[0], srr[2]);
patternStr += (patternStr.isEmpty() ? "" : "|") + srr[1];
}
sqlTokenPattern = Pattern.compile('(' + patternStr + ')');
}
public static String escape(String s)
{
Matcher matcher = sqlTokenPattern.matcher(s);
StringBuffer sb = new StringBuffer();
while(matcher.find())
{
matcher.appendReplacement(sb, sqlTokens.get(matcher.group(1)));
}
matcher.appendTail(sb);
return sb.toString();
}
Please follow the steps below to install sshpass
in mac.
curl -O -L https://fossies.org/linux/privat/sshpass-1.06.tar.gz && tar xvzf sshpass-1.06.tar.gz
cd sshpass-1.06
./configure
sudo make install
Integer typeValue = 0;
try {
Class<Types> types = Types.class;
java.lang.reflect.Field field = types.getDeclaredField("Type");
field.setAccessible(true);
Object value = field.get(types);
typeValue = (Integer) value;
} catch (Exception e) {
e.printStackTrace();
}
Try this as a shortcut, not as a definitive solution (see comments):
<script type="text/javascript">
var ip = location.host;
alert(ip);
</script>
This solution cannot work in some scenarios but it can help for quick testing. Regards
Please incre max_iter to 10000 as default value is 1000. Possibly, increasing no. of iterations will help algorithm to converge. For me it converged and solver was -'lbfgs'
log_reg = LogisticRegression(solver='lbfgs',class_weight='balanced', max_iter=10000)
This is the way I achieved it. And the example below has used the React.createRef() API introduced in React 16.3.
class Test extends React.Component {
constructor(props) {
super(props);
this.secondTextInputRef = React.createRef();
}
render() {
return(
<View>
<TextInput
placeholder = "FirstTextInput"
returnKeyType="next"
onSubmitEditing={() => { this.secondTextInputRef.current.focus(); }}
/>
<TextInput
ref={this.secondTextInputRef}
placeholder = "secondTextInput"
/>
</View>
);
}
}
I think this will help you.
hello you can try this bellow :
char arr[nb_of_string][max_string_length];
strcpy(arr[0], "word");
a nice example of using, array of strings in c if you want it
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
int i, j, k;
// to set you array
//const arr[nb_of_string][max_string_length]
char array[3][100];
char temp[100];
char word[100];
for (i = 0; i < 3; i++){
printf("type word %d : ",i+1);
scanf("%s", word);
strcpy(array[i], word);
}
for (k=0; k<3-1; k++){
for (i=0; i<3-1; i++)
{
for (j=0; j<strlen(array[i]); j++)
{
// if a letter ascii code is bigger we swap values
if (array[i][j] > array[i+1][j])
{
strcpy(temp, array[i+1]);
strcpy(array[i+1], array[i]);
strcpy(array[i], temp);
j = 999;
}
// if a letter ascii code is smaller we stop
if (array[i][j] < array[i+1][j])
{
j = 999;
}
}
}
}
for (i=0; i<3; i++)
{
printf("%s\n",array[i]);
}
return 0;
}
You should be using SqlConnection.State
e.g,
using System.Data;
if (myConnection != null && myConnection.State == ConnectionState.Closed)
{
// do something
// ...
}
There's no need to use onAuthStateChanged() function in this scenario.
You can easily detect if the user is logged or not by executing:
var user = firebase.auth().currentUser;
For those who face the "returning null" issue, it's just because you are not waiting for the firebase call to complete.
Let's suppose you perform the login action on Page A and then you invoke Page B, on Page B you can call the following JS code to test the expected behavior:
var config = {
apiKey: "....",
authDomain: "...",
databaseURL: "...",
projectId: "..",
storageBucket: "..",
messagingSenderId: ".."
};
firebase.initializeApp(config);
$( document ).ready(function() {
console.log( "testing.." );
var user = firebase.auth().currentUser;
console.log(user);
});
If the user is logged then "var user" will contain the expected JSON payload, if not, then it will be just "null"
And that's all you need.
Regards
Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.
The Node Knockout competition wrapped up recently, and many of the submissions are available on github. The competition site doesn't appear to be working right now, but I'm sure you could Google up a few entries to check out.
I usually write a macro like this:
#define UNUSED(x) (void)(x)
You can use this macro for all your unused parameters. (Note that this works on any compiler.)
For example:
void f(int x) {
UNUSED(x);
...
}
You are using older MySql version. Update your myqsl to 5.6.5+ it will work.
I suggest using DateUtils from apache.commons library.
long millis = DateUtils.truncate(utilDate, Calendar.MILLISECOND).getTime();
java.sql.Timestamp sq = new java.sql.Timestamp(millis );
Edit: Fixed Calendar.MILISECOND
to Calendar.MILLISECOND
Use Apache Friends XAMPP. It will set up Apache HTTP server, PHP 5 and MySQL 5 (as far as I know, there's probably some more than that). You don't need to know how to configure apache (or any of the modules) to use it.
You will have an htdocs directory which Apache will serve (accessible by http://localhost/) and should be able to put your PHP files there. With my installation, it is at C:\xampp\htdocs.
There are many possible conversion ways:
$input => 123
sprintf('%d',$input) => 123
(string)$input => 123
strval($input) => 123
settype($input, "string") => 123
I get get the same minicom error, "cannot open /dev/ttyUSB0: No such file or directory"
Three notes:
I get the error when the device attached to the serial port end of my Prolific Technology PL2303 USB/Serial adapter is turned off. After turning on the device (an embedded controller running Linux) minicom connected fine.
I have to run as super user (i.e. sudo minicom
)
Sometimes I have to unplug and plug back in the USB-to-serial adapter to get minicom to connect to it.
I am running Ubuntu 10.04 LTS (Lucid Lynx) under VMware (running on Windows 7). In this situation, make sure the device is attached to VM operating system by right clicking on the USB/Serial USB icon in the lower right of the VMware window and select Connect (Disconnect from Host).
Remember to press Ctrl + A to get minicom's prompt, and type X to exit the program. Just exiting the terminal session running minicom will leave the process running.
This Perl one-liner shows how closely Perl is related to awk:
perl -lane 'print $F[3]' text.txt
However, the @F
autosplit array starts at index $F[0]
while awk fields start with $1
What @dmckee said.
It's not difficult to write your own bespoke footnote-queuing code. What you need to do is:
\footnote
to add a footnote macro to your queue;If this is interesting, I show some code that does this.
here you can see the latest updated status form their website
if Git via HTTPS
status is Major Outage
, you will not be able to pull/push, let this status to get green
HTTP Error 503 - Service unavailable
If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr
function like this:
regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')
This should work:
import java.util.Scanner;
public class Test {
public static void main(String... args) throws Throwable {
Scanner kb = new Scanner(System.in);
int num1;
System.out.print("Enter number 1: ");
while (true)
try {
num1 = Integer.parseInt(kb.nextLine());
break;
} catch (NumberFormatException nfe) {
System.out.print("Try again: ");
}
int num2;
do {
System.out.print("Enter number 2: ");
while (true)
try {
num2 = Integer.parseInt(kb.nextLine());
break;
} catch (NumberFormatException nfe) {
System.out.print("Try again: ");
}
} while (num2 < num1);
}
}
One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):
My solution will be to run the code (On timer event) from another hidden form that opens with the database.
I know this was posted a while ago, but in case anyone is searching for an answer and really wants to use a button element instead of an input element...
You can not use .attr('value')
or .val()
with a button in IE. IE reports both the .val() and .attr("value") as being the text label (content) of the button element instead of the actual value of the value attribute.
You can work around it by temporarily removing the button's label:
var getButtonValue = function($button) {
var label = $button.text();
$button.text('');
var buttonValue = $button.val();
$button.text(label);
return buttonValue;
}
There are a few other quirks with buttons in IE. I have posted a fix for the two most common issues here.
According to Martin Fowler
The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk, we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it’s caught on very nicely.
Generally, a POJO is not bound to any restriction and any Java object can be called a POJO but there are some directions. A well-defined POJO should follow below directions.
And according to Java Language Specification, a POJO should not have to
However, developers and frameworks describe a POJO still requires the use prespecified annotations to implement features like persistence, declarative transaction management etc. So the idea is that if the object was a POJO before any annotations were added would return to POJO status if the annotations are removed then it can still be considered a POJO.
A JavaBean is a special kind of POJO that is Serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.
Read more on Plain Old Java Object (POJO) Explained.
Try these steps.
--We are going to edit "etc\profile". The environment variables are to be input at the bottom of the file. Since Ubuntu does not give access to root folder, we will have to use a few commands in the terminal
Step1: Start Terminal. Type in command: gksudo gedit /etc/profile
Step2: The profile text file will open. Enter the environment variables at the bottom of the page........... Eg: export JAVA_HOME=/home/alex/jdk1.6.0_22/bin/java
export PATH=/home/alex/jdk1.6.0_22/bin:$PATH
step3: save and close the file. Check if the environment variables are set by using echo command........ Eg echo $PATH
For me this works best:
class="{{url()->current() == route('dashboard') ? 'bg-gray-900 text-white' : 'text-gray-300'}}"
I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI
to create a config file. The reason is, with the config file, the CLI
or the SDK
will automatically look for credentials in the ~/.aws
folder. And the good thing is that AWS CLI
is written in python.
You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal
$> pip install awscli #can add user flag
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:
After this you can access boto
and any of the api without having to specify keys (unless you want to use a different credentials).
Hi have improved ssorallen answer. You don't need to bind function because you can access to the input without it.
var Hello = React.createClass({
render: function() {
var total = this.state.input1 + this.state.input2;
return (
<div>{total}<br/>
<input type="text"
value={this.state.input1}
id="input1"
onChange={this.handleChange} />
<input type="text"
value={this.state.input2}
id="input2"
onChange={this.handleChange} />
</div>
);
},
handleChange: function (name, value) {
var change = {};
change[name] = value;
this.setState(change);
}
});
React.renderComponent(<Hello />, document.getElementById('content'));
This can be a huge approximation depending on your polygons, but here's one :
Though, this should be very efficient as any transformation to the polygon applies in the very same way to the center of mass and the center-node distances can be computed only once.
You can't change your password through TortoiseSVN. Authentication to the SVN server has to be changed within the SVN server itself.
How you actually achieve this depends on which SVN Server is housing the repository and how the SVN Server was laid out on your computer.
n a Windows environment, credentials are typically stored in <yoursvnroot>\conf\passwd
.
In a Linux environment it could be as above, or a myriad of other ways depending on how it's hosted.
library(tidyverse)
x <- data.frame(Category= c('First', 'First', 'First', 'Second', 'Third', 'Third', 'Second'),
Frequency = c(10, 15, 5, 2, 14, 20, 3))
count(x, Category, wt = Frequency)
That should help
df.groupby(['NFF', 'ABUSE']).size().unstack().plot(kind='bar', stacked=True)
Just zero off the time element of the date. e.g.
SELECT DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
I've used GetDate as that's an MSSQL function, as you've tagged, but Now()
is probably MySQL or you're using the ODBC function call, still should work if you just replace one with the other.
For Android API level 13 and you need to use this:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int maxX = size.x;
int maxY = size.y;
Then (0,0) is top left corner and (maxX,maxY) is bottom right corner of the screen.
The 'getWidth()' for screen size is deprecated since API 13
Furthermore getwidth() and getHeight() are methods of android.view.View class in android.So when your java class extends View class there is no windowManager overheads.
int maxX=getwidht();
int maxY=getHeight();
as simple as that.
This is what I did
hope this will help you
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
AND table_schema = 'db_name'
AND column_name = 'column_name'
or
delimiter '//'
CREATE PROCEDURE addcol() BEGIN
IF NOT EXISTS(
SELECT * FROM information_schema.COLUMNS
WHERE COLUMN_NAME='new_column' AND TABLE_NAME='tablename' AND TABLE_SCHEMA='the_schema'
)
THEN
ALTER TABLE `the_schema`.`the_table`
ADD COLUMN `new_column` TINYINT(1) NOT NULL DEFAULT 1;;
END IF;
END;
//
delimiter ';'
CALL addcol();
DROP PROCEDURE addcol;
The following should work:
var="pid: 1234"
var=${var:5}
Are you sure bash
is the shell executing your script?
Even the POSIX-compliant
var=${var#?????}
would be preferable to using an external process, although this requires you to hard-code the 5 in the form of a fixed-length pattern.
I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database
Windows Services do not have UIs. You can redirect the output from a console app to your service with the code shown in this question.
I just want to post my solution. Previous answers was pretty helpful for my research. I use length-stream to get the size of the stream, but the problem here is that the callback is fired near the end of the stream, so i also use stream-cache to cache the stream and pipe it to res object once i know the content-length. In case on an error,
var StreamCache = require('stream-cache');
var lengthStream = require('length-stream');
var _streamFile = function(res , stream , cb){
var cache = new StreamCache();
var lstream = lengthStream(function(length) {
res.header("Content-Length", length);
cache.pipe(res);
});
stream.on('error', function(err){
return cb(err);
});
stream.on('end', function(){
return cb(null , true);
});
return stream.pipe(lstream).pipe(cache);
}
Whilst these answers work they do not address the problem with npm test
If, for example, I create a global variable in server.js, it will not be set for my test suite execution.
To set a global appRoot variable that will avoid the ../../../ problem and will be available in both npm start AND npm test see:
Mocha tests with extra options or parameters
Note that this is the new official mocha solution.
Use tqdm_notebook
from tqdm import tqdm_notebook as tqdm
x=[1,2,3,4,5]
for i in tqdm(range(0,len(x))):
print(x[i])
You can use some div or span instead of button and then on click call some function which submits form at he end.
<form id="my_form">
<span onclick="submit()">submit</span>
</form>
<script>
function submit()
{
//do something
$("#my_form").submit();
}
</script>
HTML :
<div class="span4">
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
</div>
</div>
CSS :
.panel-height {
height: 100px; / change according to your requirement/
}
check this out :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
?for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}?
Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.
You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).
it clears the all the bits that are not in the first byte
Consider this implementation of foo():
public void foo(final String a) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.print(a);
}
});
}
Because the Runnable
instance would outlive the method, this wouldn't compile without the final
keyword -- final
tells the compiler that it's safe to take a copy of the reference (to refer to it later). Thus, it's the reference that's considered final, not the value. In other words: As a caller, you can't mess anything up...
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
One work-around is to right-click on the result set and select "Save Results As...". This exports it to a CSV file with the entire contents of the column. Not perfect but worked well enough for me.
It should be
if (*message == '\0')
In C, simple quotes delimit a single character whereas double quotes are for strings.
This is almost the same as @Brocco 's answer, but with a slight twist: only pass optional parameters in an object. (And also make params object optional).
It ends up being kind of like Python's **kwargs, but not exactly.
export interface IErrorParams {
title?: string;
autoHideAfter?: number;
}
export interface INotificationService {
// make params optional so you don't have to pass in an empty object
// in the case that you don't want any extra params
error(message: string, params?: IErrorParams);
}
// all of these will work as expected
error('A message with some params but not others:', {autoHideAfter: 42});
error('Another message with some params but not others:', {title: 'StackOverflow'});
error('A message with all params:', {title: 'StackOverflow', autoHideAfter: 42});
error('A message with all params, in a different order:', {autoHideAfter: 42, title: 'StackOverflow'});
error('A message with no params at all:');
If the SSL certificates are not properly installed in your system, you may get this error:
cURL error 60: SSL certificate problem: unable to get local issuer certificate.
You can solve this issue as follows:
Download a file with the updated list of certificates from https://curl.haxx.se/ca/cacert.pem
Move the downloaded cacert.pem
file to some safe location in your system
Update your php.ini
file and configure the path to that file:
Depending on your version of linux it may be called mail. To quote @David above:
mail -s "Backup" -a mysqldbbackup.sql [email protected] < message.txt
or also:
cat message.txt | mail -s "Backup" -a mysqldbbackup.sql [email protected]
An other approach after trying the solutions below. When you need it clear, just initialise your list to new clear new list.
List<ModelData> dataLists = new ArrayList<>();
RaporAdapter adapter = new RaporAdapter(AyrintiliRapor.this, dataLists);
listview.setAdapter(adapter);
Or set visibility to Gone / Invisible up to need
img_pdf.setVisibility(View.INVISIBLE);
You can use df.plot.scatter, and pass an array to c= argument defining the color of each point:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
colors = np.where(df["key1"]==4,'r','-')
colors[df["key1"]==6] = 'g'
colors[df["key1"]==8] = 'b'
print(colors)
df.plot.scatter(x="one",y="two",c=colors)
plt.show()
There are a bunch of reasons here: http://macresearch.org/difference-between-alloc-init-and-new
Some selected ones are:
new
doesn't support custom initializers (like initWithString
)alloc-init
is more explicit than new
General opinion seems to be that you should use whatever you're comfortable with.
No, you can't.
There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.
If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.
In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.
SQL> desc sys.com$
Name Null? Type
----------------------------------------- -------- ----------------------------
OBJ# NOT NULL NUMBER
COL# NUMBER
COMMENT$ VARCHAR2(4000)
SQL>
The column is optional and sys.col$
does not contain comment information.
I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.
If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY
is not "V_ARRAY"
, then you are using different types; even if they are declared identically (e.g. both are table of number
) this will not work.
You're hitting this data type compatibility restriction:
You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.
You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.
You can subtract the time zone difference from now.
final Calendar calendar = Calendar.getInstance();
final int utcOffset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
final long tempDate = new Date().getTime();
return new Date(tempDate - utcOffset);
Make sure that nothing is interfering with your app files (specially in Windows), in my case this problem arise due to a text editor that was holding some XML file and Android Studio wasn't able to modify it.
You need to enable deep object dirty checking. By default angular only checks the reference of the top level variable that you watch.
App.directive('d3Visualization', function() {
return {
restrict: 'E',
scope: {
val: '='
},
link: function(scope, element, attrs) {
scope.$watch('val', function(newValue, oldValue) {
if (newValue)
console.log("I see a data change!");
}, true);
}
}
});
see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.
Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data
variable the watch the variable directly.
scope.$watch('val.children', function(newValue, oldValue) {}, true);
version 1.2.x introduced $watchCollection
Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)
scope.$watchCollection('val.children', function(newValue, oldValue) {});
git add -u .
git add --update .
There does not seem to be any standard immutable interface for dictionaries, so creating a wrapper seems like the only reasonable option, unfortunately.
Edit: Marc Gravell found the ILookup that I missed - that will allow you to at least avoid creating a new wrapper, although you still need to transform the Dictionary with .ToLookup().
If this is a need constrained to a specific scenario, you might be better off with a more business-logic-oriented interface:
interface IActiveUserCountProvider
{
int GetMaxForServer(string serverName);
}
Bash 4 has a coproc
command which establishes a named pipe to a command and allows you to communicate through it.
This is not a security measure for weak code to be left unattended. Always get a permanent solution to weak code and secure your websites properly before implementing this strategy
The best tool by far according to my knowledge would be to add multiple javascript files that simply changes the integrity of the page back to normal by refreshing or replacing content. Disabling this developer tool would not be the greatest idea since bypassing is always in question since the code is part of the browser and not a server rendering, thus it could be cracked.
Should you have js file one
checking for <element>
changes on important elements and js file two
and js file three
checking that this file exists per period you will have full integrity restore on the page within the period.
Lets take an example of the 4 files and show you what I mean.
index.html
<!DOCTYPE html>
<html>
<head id="mainhead">
<script src="ks.js" id="ksjs"></script>
<script src="mainfile.js" id="mainjs"></script>
<link rel="stylesheet" href="style.css" id="style">
<meta id="meta1" name="description" content="Proper mitigation against script kiddies via Javascript" >
</head>
<body>
<h1 id="heading" name="dontdel" value="2">Delete this from console and it will refresh. If you change the name attribute in this it will also refresh. This is mitigating an attack on attribute change via console to exploit vulnerabilities. You can even try and change the value attribute from 2 to anything you like. If This script says it is 2 it should be 2 or it will refresh. </h1>
<h3>Deleting this wont refresh the page due to it having no integrity check on it</h3>
<p>You can also add this type of error checking on meta tags and add one script out of the head tag to check for changes in the head tag. You can add many js files to ensure an attacker cannot delete all in the second it takes to refresh. Be creative and make this your own as your website needs it.
</p>
<p>This is not the end of it since we can still enter any tag to load anything from everywhere (Dependent on headers etc) but we want to prevent the important ones like an override in meta tags that load headers. The console is designed to edit html but that could add potential html that is dangerous. You should not be able to enter any meta tags into this document unless it is as specified by the ks.js file as permissable. <br>This is not only possible with meta tags but you can do this for important tags like input and script. This is not a replacement for headers!!! Add your headers aswell and protect them with this method.</p>
</body>
<script src="ps.js" id="psjs"></script>
</html>
mainfile.js
setInterval(function() {
// check for existence of other scripts. This part will go in all other files to check for this file aswell.
var ksExists = document.getElementById("ksjs");
if(ksExists) {
}else{ location.reload();};
var psExists = document.getElementById("psjs");
if(psExists) {
}else{ location.reload();};
var styleExists = document.getElementById("style");
if(styleExists) {
}else{ location.reload();};
}, 1 * 1000); // 1 * 1000 milsec
ps.js
/*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload!You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.
*/
setInterval(function() {
// check for existence of other scripts. This part will go in all other files to check for this file aswell.
var mainExists = document.getElementById("mainjs");
if(mainExists) {
}else{ location.reload();};
//check that heading with id exists and name tag is dontdel.
var headingExists = document.getElementById("heading");
if(headingExists) {
}else{ location.reload();};
var integrityHeading = headingExists.getAttribute('name');
if(integrityHeading == 'dontdel') {
}else{ location.reload();};
var integrity2Heading = headingExists.getAttribute('value');
if(integrity2Heading == '2') {
}else{ location.reload();};
//check that all meta tags stay there
var meta1Exists = document.getElementById("meta1");
if(meta1Exists) {
}else{ location.reload();};
var headExists = document.getElementById("mainhead");
if(headExists) {
}else{ location.reload();};
}, 1 * 1000); // 1 * 1000 milsec
ks.js
/*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload! You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.
*/
setInterval(function() {
// check for existence of other scripts. This part will go in all other files to check for this file aswell.
var mainExists = document.getElementById("mainjs");
if(mainExists) {
}else{ location.reload();};
//Check meta tag 1 for content changes. meta1 will always be 0. This you do for each meta on the page to ensure content credibility. No one will change a meta and get away with it. Addition of a meta in spot 10, say a meta after the id="meta10" should also be covered as below.
var x = document.getElementsByTagName("meta")[0];
var p = x.getAttribute("name");
var s = x.getAttribute("content");
if (p != 'description') {
location.reload();
}
if ( s != 'Proper mitigation against script kiddies via Javascript') {
location.reload();
}
// This will prevent a meta tag after this meta tag @ id="meta1". This prevents new meta tags from being added to your pages. This can be used for scripts or any tag you feel is needed to do integrity check on like inputs and scripts. (Yet again. It is not a replacement for headers to be added. Add your headers aswell!)
var lastMeta = document.getElementsByTagName("meta")[1];
if (lastMeta) {
location.reload();
}
}, 1 * 1000); // 1 * 1000 milsec
style.css
Now this is just to show it works on all files and tags aswell
#heading {
background-color:red;
}
If you put all these files together and build the example you will see the function of this measure. This will prevent some unforseen injections should you implement it correctly on all important elements in your index file especially when working with PHP.
Why I chose reload instead of change back to normal value per attribute is the fact that some attackers could have another part of the website already configured and ready and it lessens code amount. The reload will remove all the attacker's hard work and he will probably go play somewhere easier.
Another note: This could become a lot of code so keep it clean and make sure to add definitions to where they belong to make edits easy in future. Also set the seconds to your preferred amount as 1 second intervals on large pages could have drastic effects on older computers your visitors might be using
First we need to define key as variable and then we need to assign as key as object., for example
var data = {key:'dynamic_key',value:'dynamic_value'}_x000D_
var key = data.key;_x000D_
var obj = { [key]: data.value}_x000D_
console.log(obj)
_x000D_
In my case, this was caused by custom manifest entries added by the maven-jar-plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<git>${buildNumber}</git>
<build-time>${timestamp}</build-time>
</manifestEntries>
</archive>
</configuration>
</plugin>
Removing the following entries fixed the problem
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
you can also use this as tooltip...It works same but you have to write extra tag thats it..
<abbr title="THis is tooltip"></abbr>
Float elements will be rendered at the line they are normally in the layout. To fix this, you have two choices:
Move the header and the p after the login box:
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
Or enclose the left block in a pull-left div, and add a clearfix at the bottom
<div class='container'>
<div class='hero-unit'>
<div class="pull-left">
<h2>Welcome</h2>
<p>Please log in</p>
</div>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<div class="clearfix"></div>
</div>
</div>
Window > Show view > Server
or right click on the server in "Servers" view, select "Properties".You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.
U can use something like this....
function (field,value) {
var newItemOrder= value;
// Make sure user hasnt already added this item
angular.forEach(arr, function(item) {
if (newItemOrder == item.value) {
arr.splice(arr.pop(item));
} });
submitFields.push({"field":field,"value":value});
};
New syntax has been supported for a while by all modern browsers (starting from Chrome 26, Opera 12.1, IE 10 and Firefox 16): http://caniuse.com/#feat=css-gradients
background: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
This renders a gradient, starting from solid black at the top, to fully transparent at the bottom.
If you don't want to use RegEx (which seems highly unnecessary given your problem), perhaps you should try something like this:
public String modified(final String input){
final StringBuilder builder = new StringBuilder();
for(final char c : input.toCharArray())
if(Character.isLetterOrDigit(c))
builder.append(Character.isLowerCase(c) ? c : Character.toLowerCase(c));
return builder.toString();
}
It loops through the underlying char[]
in the String
and only appends the char
if it is a letter or digit (filtering out all symbols, which I am assuming is what you are trying to accomplish) and then appends the lower case version of the char
.
Installing a 64-bit version of Java will solve the issue. Go to page Java Downloads for All Operating Systems
This is a problem due to the incompatibility of the Java version and the Eclipse version both should be 64 bit if you are using a 64-bit system.
You could try:
agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)
Upcoming pandas 0.13 version will allow to add rows through loc
on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.
Description is here and this new feature is called Setting With Enlargement.
eq is used to compare integers use equal '=' instead , example:
if [ 'AAA' = 'ABC' ];
then
echo "the same"
else
echo "not the same"
fi
good luck
Swift 2.0 as of Xcode 7 GM Seed
var text = "Hello, world!"
let firstChar = text[text.startIndex.advancedBy(0)] // "H"
For the nth character, replace 0 with n-1.
Edit: Swift 3.0
text[text.index(text.startIndex, offsetBy: 0)]
n.b. there are simpler ways of grabbing certain characters in the string
e.g. let firstChar = text.characters.first
Here is the simplest way to add Gestures on View in Swift 5
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
addGestures()
}
// MARK: Add Gestures to target view
func addGestures()
{
// 1. Single Tap or Touch
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapGetstureDetected))
tapGesture.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGesture)
//2. Double Tap
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapGestureDetected))
doubleTapGesture.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTapGesture)
//3. Swipe
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGetstureDetected))
view.addGestureRecognizer(swipeGesture)
//4. Pinch
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(self.pinchGetstureDetected))
view.addGestureRecognizer(pinchGesture)
//5. Long Press
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGetstureDetected))
view.addGestureRecognizer(longPressGesture)
//6. Pan
let panGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.panGestureDetected))
view.addGestureRecognizer(panGesture)
}
// MARK: Handle Gesture detection
@objc func swipeGetstureDetected() {
print("Swipe Gesture detected!!")
}
@objc func tapGetstureDetected() {
print("Touch/Tap Gesture detected!!")
}
@objc func pinchGetstureDetected() {
print("Pinch Gesture detected!!")
}
@objc func longPressGetstureDetected() {
print("Long Press Gesture detected!!")
}
@objc func doubleTapGestureDetected() {
print("Double Tap Gesture detected!!")
}
@objc func panGestureDetected()
{
print("Pan Gesture detected!!")
}
//MARK: Shake Gesture
override func becomeFirstResponder() -> Bool {
return true
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?){
if motion == .motionShake
{
print("Shake Gesture Detected")
}
}
}
It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.
You don't need any webpack configuration for this..
In your component just give image path. By default react will know its in public directory.
<img src="/image.jpg" alt="image" />
Try use this:
apt-get install r-base-dev
It will be help. After then I could makeinstall.packages('//package_name')
SELECT 'ColName1', 'ColName2', 'ColName3' UNION ALL SELECT ColName1, ColName2, ColName3 FROM YourTable INTO OUTFILE 'c:\\datasheet.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'
Used to face the same problem. The reason was in incorrect context passing to AlertDialog.Builder(here)
. use like
AlertDialog.Builder(Homeactivity.this)
Update:
These articles in my blog describe the differences between the methods in more detail:
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: SQL Server
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: PostgreSQL
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: Oracle
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: MySQL
There are three ways to do such a query:
LEFT JOIN / IS NULL
:
SELECT *
FROM common
LEFT JOIN
table1 t1
ON t1.common_id = common.common_id
WHERE t1.common_id IS NULL
NOT EXISTS
:
SELECT *
FROM common
WHERE NOT EXISTS
(
SELECT NULL
FROM table1 t1
WHERE t1.common_id = common.common_id
)
NOT IN
:
SELECT *
FROM common
WHERE common_id NOT IN
(
SELECT common_id
FROM table1 t1
)
When table1.common_id
is not nullable, all these queries are semantically the same.
When it is nullable, NOT IN
is different, since IN
(and, therefore, NOT IN
) return NULL
when a value does not match anything in a list containing a NULL
.
This may be confusing but may become more obvious if we recall the alternate syntax for this:
common_id = ANY
(
SELECT common_id
FROM table1 t1
)
The result of this condition is a boolean product of all comparisons within the list. Of course, a single NULL
value yields the NULL
result which renders the whole result NULL
too.
We never cannot say definitely that common_id
is not equal to anything from this list, since at least one of the values is NULL
.
Suppose we have these data:
common
--
1
3
table1
--
NULL
1
2
LEFT JOIN / IS NULL
and NOT EXISTS
will return 3
, NOT IN
will return nothing (since it will always evaluate to either FALSE
or NULL
).
In MySQL
, in case on non-nullable column, LEFT JOIN / IS NULL
and NOT IN
are a little bit (several percent) more efficient than NOT EXISTS
. If the column is nullable, NOT EXISTS
is the most efficient (again, not much).
In Oracle
, all three queries yield same plans (an ANTI JOIN
).
In SQL Server
, NOT IN
/ NOT EXISTS
are more efficient, since LEFT JOIN / IS NULL
cannot be optimized to an ANTI JOIN
by its optimizer.
In PostgreSQL
, LEFT JOIN / IS NULL
and NOT EXISTS
are more efficient than NOT IN
, sine they are optimized to an Anti Join
, while NOT IN
uses hashed subplan
(or even a plain subplan
if the subquery is too large to hash)
There is a Ruby gem that interfaces your ssh
configuration file which is called sshez
.
All you have to do is sshez <alias> [email protected] -p <port-number>
, and then you can connect using ssh <alias>
. It is also useful since you can list your aliases using sshez list
and can easily remove them using sshez remove alias
.
You could just use
DataGridView1.CurrentRow.Cells["ColumnName"].Value
Steps to create Hash Key.
1: Download openssl from Openssl for Windows . I downloaded the Win64 version
2:Unzip and copy all the files in the bin folder including openssl.exe(All file of bin folder)
3:Goto to the folder where you installed JDK for me it’s C:\Program Files\Java\jdk1.8.0_05\bin
4:Paste all the files you copied from Openssl’s bin folder to the Jdk folder.
then go C:\Program Files\Java\jdk1.8.0_05\bin and press shift key and right click and open cmd
C:\Program Files\Java\jdk1.8.0_05\bin>//cmd path
that is for Sha1 past this
keytool -exportcert -alias androiddebugkey -keystore "C:\User\ABC\.android.keystore" | openssl sha1 -binary | openssl base64
//and ABC is system name put own system name
New style classes may use super(Foo, self)
where Foo
is a class and self
is the instance.
super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
And in Python 3.x you can simply use super()
inside a class without any parameters.
There is no "DOS command prompt". DOS fully died with Windows ME (7/11/2006). It's simply called the Command Prompt on Windows NT (which is NT, 2K, XP, Vista, 7).
There is no way to alter the screen buffer through built-in cmd.exe commands. It can be altered through Console API Functions, so you might be able to create a utility to modify it. I've never tried this myself.
Another suggestion would be to redirect output to both a file and to the screen so that you have a "hard copy" of it. Windows does not have a TEE command like Unix, but someone has remedied that.
You can create a trigger which updates NoofUses
column in Coupon
table whenever
couponid
is used in CouponUse
table
query :
CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end
Though I haven't personally tested, I have good reason to believe that the above stated AT COMMAND solution will work for XP, 2000 and Server 2003. Per my and Bryant's testing, we've identified that the same approach does not work with Vista or Windows Server 2008 -- most probably due to added security and the /interactive switch being deprecated.
However, I came across this article which demonstrates the use of PSTools from SysInternals (which was acquired by Microsoft in July, 2006.) I launched the command line via the following and suddenly I was running under the Local Admin Account like magic:
psexec -i -s cmd.exe
PSTools works well. It's a lightweight, well-documented set of tools which provides an appropriate solution to my problem.
Many thanks to those who offered help.
If you are using emulator then try reset it and if you at mobile first uninstall the application then switch off the developer mode, and then switch it on the problem will be solved.
Try linux command chsh
.
The detailed command is chsh -s /bin/bash
.
It will prompt you to enter your password.
Your default login shell is /bin/bash
now. You must log out and log back in to see this change.
The following is quoted from man page:
The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account
This command will change the default login shell permanently.
Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh
.
does not work if numberOfLines > 1
What i did made a condition like this-
if(lblRecLocation.text.length > 100)
lblRecLocation.font = [UIFont fontWithName:@"app_font_name" size:10];
The most reliable way I've found to display the local time of a city or location is by tapping into a Time Zone API such as Google Time Zone API. It returns the correct time zone, and more importantly, Day Light Savings Time offset of any location, which just using JavaScript's Date() object cannot be done as far as I'm aware. There's a good tutorial on using the API to get and display the local time here:
var loc = '35.731252, 139.730291' // Tokyo expressed as lat,lng tuple
var targetDate = new Date() // Current date/time of user computer
var timestamp = targetDate.getTime() / 1000 + targetDate.getTimezoneOffset() * 60 // Current UTC date/time expressed as seconds since midnight, January 1, 1970 UTC
var apikey = 'YOUR_TIMEZONE_API_KEY_HERE'
var apicall = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + loc + '×tamp=' + timestamp + '&key=' + apikey
var xhr = new XMLHttpRequest() // create new XMLHttpRequest2 object
xhr.open('GET', apicall) // open GET request
xhr.onload = function() {
if (xhr.status === 200) { // if Ajax request successful
var output = JSON.parse(xhr.responseText) // convert returned JSON string to JSON object
console.log(output.status) // log API return status for debugging purposes
if (output.status == 'OK') { // if API reports everything was returned successfully
var offsets = output.dstOffset * 1000 + output.rawOffset * 1000 // get DST and time zone offsets in milliseconds
var localdate = new Date(timestamp * 1000 + offsets) // Date object containing current time of Tokyo (timestamp + dstOffset + rawOffset)
console.log(localdate.toLocaleString()) // Display current Tokyo date and time
}
} else {
alert('Request failed. Returned status of ' + xhr.status)
}
}
xhr.send() // send request
From: Displaying the Local Time of Any City using JavaScript and Google Time Zone API
@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.
This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:
Linux / GNU readlink
solution:
If your script needs to run on Linux only or you know that GNU readlink
is in the $PATH
, use readlink -f
, which conveniently resolves a symlink to its ultimate target:
scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")
Note that GNU readlink
has 3 related options for resolving a symlink to its ultimate target's full path: -f
(--canonicalize
), -e
(--canonicalize-existing
), and -m
(--canonicalize-missing
) - see man readlink
.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f
here, because it is the most well-known one.
Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):
If your script must run on any platform that:
has a readlink
utility, but lacks the -f
option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.
readlink
; note that recent versions of FreeBSD/PC-BSD do support -f
.does not even have readlink
, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).
The following solution, inspired by https://stackoverflow.com/a/1116890/45375,
defines helper shell function, rreadlink()
, which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink
's -e
option, which is similar to the -f
option, except that the ultimate target must exist.
Note: The function is a bash
function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh
), see here.
If readlink
is available, it is used (without options) - true on most modern platforms.
Otherwise, the output from ls -l
is parsed, which is the only POSIX-compliant way to determine a symlink's target.
Caveat: this will break if a filename or path contains the literal substring ->
- which is unlikely, however.
(Note that platforms that lack readlink
may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find
utility supporting the %l
format char. with its -printf
primary; in the interest of brevity the function does NOT try to detect such cases.)
An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink
in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink
; on other platforms (assuming they have bash
), follow the manual installation instructions.
If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.
#!/usr/bin/env bash
# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...
local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH=
# Since we'll be using `command` below for a predictable execution
# environment, we make sure that it has its original meaning.
{ \unalias command; \unset -f command; } &>/dev/null
while :; do # Resolve potential symlinks until the ultimate target is found.
[[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
fname=$(command basename -- "$target") # Extract filename.
[[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
if [[ -L $fname ]]; then
# Extract [next] target path, which is defined
# relative to the symlink's own directory.
if [[ -n $readlinkexe ]]; then # Use `readlink`.
target=$("$readlinkexe" -- "$fname")
else # `readlink` utility not available.
# Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant
# way to determine a symlink's target. Hypothetically, this can break with
# filenames containig literal ' -> ' and embedded newlines.
target=$(command ls -l -- "$fname")
target=${target#* -> }
fi
continue # Resolve [next] symlink target.
fi
break # Ultimate target reached.
done
targetDir=$(command pwd -P) # Get canonical dir. path
# Output the ultimate target's canonical path.
# Note that we manually resolve paths ending in /. and /.. to make sure we
# have a normalized path.
if [[ $fname == '.' ]]; then
command printf '%s\n' "${targetDir%/}"
elif [[ $fname == '..' ]]; then
# Caveat: something like /var/.. will resolve to /private (assuming
# /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
command printf '%s\n' "$(command dirname -- "${targetDir}")"
else
command printf '%s\n' "${targetDir%/}/$fname"
fi
)
# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")
You could define a name for the VLOOKUP part of the formula.
=VLOOKUP(A1,B:B, 1, 0)
=IF( Value > 10, Value - 10, Value )
Step (1) is important here: I guess on the second row, you want Excel to use VLOOKUP(A2,B:B, 1, 0)
, the third row VLOOKUP(A3,B:B, 1, 0)
, etc. Step (4) achieves this by using relative references (A1
and B:B
), not absolute references ($A$1
and $B:$B
).
Note:
For newer Excel versions with the ribbon, go to Formulas ribbon -> Define Name. It's the same after that. Also, to use your name, you can do "Use in Formula", right under Define Name, while editing the formula, or else start typing it, and Excel will suggest the name (credits: Michael Rusch)
Shortened steps: 1. Right click a cell and click Define name... 2. Enter a name and the formula which you want to associate with that name/local variable 3. Use variable (credits: Jens Bodal)
Open a terminal and take a look at:
/Applications/Python 3.6/Install Certificates.command
Python 3.6 on MacOS uses an embedded version of OpenSSL, which does not use the system certificate store. More details here.
(To be explicit: MacOS users can probably resolve by opening Finder and double clicking Install Certificates.command)
var TableIDvalue = "myTable";_x000D_
var TableLastSortedColumn = -1;_x000D_
_x000D_
function SortTable() {_x000D_
var sortColumn = parseInt(arguments[0]);_x000D_
var type = arguments.length > 1 ? arguments[1] : 'T';_x000D_
var dateformat = arguments.length > 2 ? arguments[2] : '';_x000D_
var table = document.getElementById(TableIDvalue);_x000D_
var tbody = table.getElementsByTagName("tbody")[0];_x000D_
var rows = tbody.getElementsByTagName("tr");_x000D_
_x000D_
var arrayOfRows = new Array();_x000D_
_x000D_
type = type.toUpperCase();_x000D_
_x000D_
dateformat = dateformat.toLowerCase();_x000D_
_x000D_
for (var i = 0, len = rows.length; i < len; i++) {_x000D_
arrayOfRows[i] = new Object;_x000D_
arrayOfRows[i].oldIndex = i;_x000D_
var celltext = rows[i].getElementsByTagName("td")[sortColumn].innerHTML.replace(/<[^>]*>/g, "");_x000D_
if (type == 'D') {_x000D_
arrayOfRows[i].value = GetDateSortingKey(dateformat, celltext);_x000D_
} else {_x000D_
var re = type == "N" ? /[^\.\-\+\d]/g : /[^a-zA-Z0-9]/g;_x000D_
arrayOfRows[i].value = celltext.replace(re, "").substr(0, 25).toLowerCase();_x000D_
}_x000D_
}_x000D_
_x000D_
if (sortColumn == TableLastSortedColumn) {_x000D_
arrayOfRows.reverse();_x000D_
} else {_x000D_
TableLastSortedColumn = sortColumn;_x000D_
switch (type) {_x000D_
case "N":_x000D_
arrayOfRows.sort(CompareRowOfNumbers);_x000D_
break;_x000D_
case "D":_x000D_
arrayOfRows.sort(CompareRowOfNumbers);_x000D_
break;_x000D_
default:_x000D_
arrayOfRows.sort(CompareRowOfText);_x000D_
}_x000D_
}_x000D_
var newTableBody = document.createElement("tbody");_x000D_
_x000D_
for (var i = 0, len = arrayOfRows.length; i < len; i++) {_x000D_
newTableBody.appendChild(rows[arrayOfRows[i].oldIndex].cloneNode(true));_x000D_
}_x000D_
table.replaceChild(newTableBody, tbody);_x000D_
}_x000D_
_x000D_
function CompareRowOfText(a, b) {_x000D_
var aval = a.value;_x000D_
var bval = b.value;_x000D_
return (aval == bval ? 0 : (aval > bval ? 1 : -1));_x000D_
}_x000D_
_x000D_
function deleteRow(i) {_x000D_
document.getElementById('myTable').deleteRow(i)_x000D_
}
_x000D_
<table id="myTable" border="1">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
<input type="button" onclick="javascript: SortTable(0, 'T');" value="SORT" /></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Shaa</td>_x000D_
<td>ABC</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cnubha</td>_x000D_
<td>XYZ</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Fine</td>_x000D_
<td>MNO</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Amit</td>_x000D_
<td>PQR</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sultan</td>_x000D_
<td>FGH</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Hello</td>_x000D_
<td>UST</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
_x000D_
</tbody>_x000D_
</table>
_x000D_
Date and time formats are well described below
SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns
There could be n
Number of formats you can possibly make. ex - dd/MM/yyyy
or YYYY-'W'ww-u
or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.
G
- Era designator (AD)y
- Year (1996; 96)Y
- Week Year (2009; 09)M
- Month in year (July; Jul; 07)w
- Week in year (27)W
- Week in month (2)D
- Day in year (189)d
- Day in month (10)F
- Day of week in month (2)E
- Day name in week (Tuesday; Tue)u
- Day number of week (1 = Monday, ..., 7 = Sunday)a
- AM/PM markerH
- Hour in day (0-23)k
- Hour in day (1-24)K
- Hour in am/pm (0-11)h
- Hour in am/pm (1-12)m
- Minute in hour (30)s
- Second in minute (55)S
- Millisecond (978)z
- General time zone (Pacific Standard Time; PST; GMT-08:00)Z
- RFC 822 time zone (-0800)X
- ISO 8601 time zone (-08; -0800; -08:00)To parse:
2000-01-23T04:56:07.000+0000
Use:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):
"hello\N{TAB}alex"
"hello\N{tab}alex"
"hello\N{TaB}alex"
"hello\N{HT}alex"
"hello\N{CHARACTER TABULATION}alex"
"hello\N{HORIZONTAL TABULATION}alex"
"hello\x09alex"
"hello\u0009alex"
"hello\U00000009alex"
Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:
"hello alex"
If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.
See respective Python documentation for reference.
Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl
You need xlutils.copy
. Try something like this:
from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')
Keep in mind you can't overwrite cells by default as noted in this question.
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
try with this link of code this is absolute correct answer for all cases all over date and time. or customize date and time as per need and requirement of app.
try with this link .try with this link
Try calling read_csv
with encoding='latin1'
, encoding='iso-8859-1'
or encoding='cp1252'
(these are some of the various encodings found on Windows).
You can do this using the Travis CLI. As described in the documentation, first install the CLI tool, then:
travis login --org --auto
travis token
You can keep this token in an environment variable TRAVIS_TOKEN
, as long as the file you keep it in is not version-controlled somewhere public.
I use this function to submit triggers:
function travis_trigger() {
local org=$1 && shift
local repo=$1 && shift
local branch=${1:-master} && shift
body="{
\"request\": {
\"branch\": \"${branch}\"
}
}"
curl -s -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "Travis-API-Version: 3" \
-H "Authorization: token $TRAVIS_TOKEN" \
-d "$body" \
"https://api.travis-ci.org/repo/${org}%2F${repo}/requests"
}
Yes there is possible to close TCP or UDP port there is a command in DOS
TASKKILL /f /pid 1234
I hope this will work for You
The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection
The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().
Select columns by namedata <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr [ 4]: carrier, tailnum, origin, dest
#> dbl [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#> plane year month day dep_time sched_dep_time dep_delay arr_time
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 N142… 2013 1 1 517 515 2 830
#> 2 N242… 2013 1 1 533 529 4 850
#> 3 N619… 2013 1 1 542 540 2 923
#> 4 N804… 2013 1 1 544 545 -1 1004
#> 5 N668… 2013 1 1 554 600 -6 812
#> 6 N394… 2013 1 1 554 558 -4 740
#> 7 N516… 2013 1 1 555 600 -5 913
#> 8 N829… 2013 1 1 557 600 -3 709
#> 9 N593… 2013 1 1 557 600 -3 838
#> 10 N3AL… 2013 1 1 558 600 -2 753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> # arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> # time_hour <dttm>
Goto project -->properties --> (in the dialog box that opens goto Java build path), and in order and export select android 4.1 (your new version) and select dependencies.
Just to be a bit left handed...
x ? y : x = value
will assign value to y if x is not 0 (false).
CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.
first we read data in csv format and then convert to data frame and create a temp view
Reading data in csv format
val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")
printing the schema
data.printSchema
data.createOrReplaceTempView("Data")
Now we can run sql queries on top the table view we just created
%sql select Week as Date,Campaign Type,Engagements,Country from Data order by Date asc
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
Check your font's css file. (fontawesome.css/fontawesome.min.css), you will see like this:
@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot-v=4.6.3.htm');
src: url('../fonts/fontawesome-webfont.eot#iefix-v=4.6.3') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2-v=4.6.3.htm') format('woff2'), url('../fonts/fontawesome-webfont.woff-v=4.6.3.htm') format('woff'), url('../fonts/fontawesome-webfont.ttf-v=4.6.3.htm') format('truetype'), url('../fonts/fontawesome-webfont.svg-v=4.6.3.htm#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal
}
you will see version tag after your font's file extension name. Like:
-v=4.6.3
You just need to remove this tag from your css file. After removing this, you need to go to your fonts folder, And you will see:
And, Form these font's files, you just need to remove the version tag -v=4.6.3 from the file name.
Then, The problem will be sloved.
If username
or password
has the @
character, then use it like this:
mongoose
.connect(
'DB_url',
{ user: '@dmin', pass: 'p@ssword', useNewUrlParser: true }
)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.log('Could not connect to MongoDB', err));
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
Method 1:\
add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables
Method 2: (if method 1 not work then)
simple open command prompt with "run as administrator"
I've an object (basically a VO) in Java and I don't know its type. I need to get values which are not null in that object.
Maybe you don't necessary need reflection for that -- here is a plain OO design that might solve your problem:
Validation
which expose a method validate
which checks the fields and return whatever is appropriate. Validation
and check that easily.I guess that you need the field that are null to display an error message in a generic way, so that should be enough. Let me know if this doesn't work for you for some reason.
Use the SETX command (note the 'x' suffix) to set variables that persist after the cmd window has been closed.
For example, to set an env var "foo" with value of "bar":
setx foo bar
Though it's worth reading the 'notes' that are displayed if you print the usage (setx /?
), in particular:
2) On a local system, variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window.
3) On a remote system, variables created or modified by this tool will be available at the next logon session.
In PowerShell, the [Environment]::SetEnvironmentVariable command.
For those strictly looking for a solution that works for input or textarea, this is the simplest solution I've came across. Only a few lines of CSS and one line of JS.
The JavaScript sets a data-* attribute on the element equal to the value of the input. The input is set within a CSS grid, where that grid is a pseudo-element that uses that data-* attribute as its content. That content is what stretches the grid to the appropriate size based on the input value.
You can also try this for Html.ActionLink DeleteId
If you are developing for Android, Color's method for this is rgb(int, int, int)
So you would do something like
myPaint.setColor(Color.rgb(int, int, int));
For retrieving the individual color values you can use the methods for doing so:
Color.red(int color)
Color.blue(int color)
Color.green(int color)
Refer to this document for more info
Go to file->export->JAR file, there you may select "Export generated class files and sources" and make sure that your project is selected, and all folder under there are also! Good luck!
I experienced the same errors on a fresh install of VestaCP. I solved the issues by following the instructions on this video.
Here's a method that handles .tar.gz
properly, even in a path with dots in directory names:
private static final String getExtension(final String filename) {
if (filename == null) return null;
final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1);
final int afterLastBackslash = afterLastSlash.lastIndexOf('\\') + 1;
final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash);
return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1);
}
afterLastSlash
is created to make finding afterLastBackslash
quicker since it won't have to search the whole string if there are some slashes in it.
The char[]
inside the original String
is reused, adding no garbage there, and the JVM will probably notice that afterLastSlash
is immediately garbage in order to put it on the stack instead of the heap.
I found this question when looking for a way to really read a local file instead of reading a file from the web server, which I'd rather call a "remote file".
Just call require
:
const content = require('../../path_of_your.json');
The Angular-CLI source code inspired me: I found out that they include component templates by replacing the templateUrl
property by template
and the value by a require
call to the actual HTML resource.
If you use the AOT compiler you have to add the node type definitons by adjusting tsconfig.app.json
:
"compilerOptions": {
"types": ["node"],
...
},
...
This might be a little late to answer but most simple and accurate way to compute square root is newton's method.
You have a number which you want to compute its square root (num)
and you have a guess of its square root (estimate)
. Estimate can be any number bigger than 0, but a number that makes sense shortens the recursive call depth significantly.
new_estimate = (estimate + num / estimate) / 2
This line computes a more accurate estimate with those 2 parameters. You can pass new_estimate value to the function and compute another new_estimate which is more accurate than the previous one or you can make a recursive function definition like this.
def newtons_method(num, estimate):
# Computing a new_estimate
new_estimate = (estimate + num / estimate) / 2
print(new_estimate)
# Base Case: Comparing our estimate with built-in functions value
if new_estimate == math.sqrt(num):
return True
else:
return newtons_method(num, new_estimate)
For example we need to find 30's square root. We know that the result is between 5 and 6.
newtons_method(30,5)
number is 30 and estimate is 5. The result from each recursive calls are:
5.5
5.477272727272727
5.4772255752546215
5.477225575051661
The last result is the most accurate computation of the square root of number. It is the same value as the built-in function math.sqrt().
For some reason, the replace works only with one string each time. I had a string like this "Test MSP" and I want to leave only one space.
I used the approach that @Farhan did, but with some modifications:
CREATE FUNCTION ReplaceAll
(
@OriginalString varchar(8000),
@StringToRemove varchar(20),
@StringToPutInPlace varchar(20)
)
RETURNS varchar(8000)
AS
BEGIN
declare @ResultStr varchar(8000)
set @ResultStr = @OriginalString
while charindex(@StringToRemove, @ResultStr) > 0
set @ResultStr = replace(@ResultStr, @StringToRemove, @StringToPutInPlace)
return @ResultStr
END
Then I run my update like this
UPDATE tbTest SET Description = dbo.ReplaceAll(Description, ' ', ' ') WHERE ID = 14225
Then I got this result: Test MSP
Posting here if in case someone needs it as I did.
Running on: Microsoft SQL Server 2016 (SP2)
This is simple and short way to redirect/link other existing application on app store.
NSString *customURL = @"http://itunes.apple.com/app/id951386316";
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
I have this:
debug_echo(array('$query'=>$query, '$nrUsers'=>$nrUsers, '$hdr'=>$hdr));
I would prefer this:
debug_echo($query, $nrUsers, $hdr);
The existing function displays a yellow box with a red outline and shows each variable by name and value. The array solution works but is a little convoluted to type when it is needed.
That's my use case and yes, it does have to do with debugging. I agree with those who question its use otherwise.
Have a look at Access Modifiers (C# Programming Guide)
Class and Struct Accessibility
Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.
Struct members, including nested classes and structs, can be declared as public, internal, or private. Class members, including nested classes and structs, can be public, protected internal, protected, internal, private protected or private. The access level for class members and struct members, including nested classes and structs, is private by default. Private nested types are not accessible from outside the containing type.
Derived classes cannot have greater accessibility than their base types. In other words, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.
You can enable specific other assemblies to access your internal types by using the
InternalsVisibleToAttribute
. For more information, see Friend Assemblies.Class and Struct Member Accessibility
Class members (including nested classes and structs) can be declared with any of the six types of access. Struct members cannot be declared as protected because structs do not support inheritance.
Normally, the accessibility of a member is not greater than the accessibility of the type that contains it. However, a public member of an internal class might be accessible from outside the assembly if the member implements interface methods or overrides virtual methods that are defined in a public base class.
The type of any member that is a field, property, or event must be at least as accessible as the member itself. Similarly, the return type and the parameter types of any member that is a method, indexer, or delegate must be at least as accessible as the member itself. For example, you cannot have a public method M that returns a class C unless C is also public. Likewise, you cannot have a protected property of type A if A is declared as private.
User-defined operators must always be declared as public and static. For more information, see Operator overloading.
Finalizers cannot have accessibility modifiers.
Other Types
Interfaces declared directly within a namespace can be declared as public or internal and, just like classes and structs, interfaces default to internal access. Interface members are always public because the purpose of an interface is to enable other types to access a class or struct. No access modifiers can be applied to interface members.
Enumeration members are always public, and no access modifiers can be applied.
Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.
You can use this Code
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust)
{
[[challenge sender] useCredential:[NSURLCredential credentialForTrust:[[challenge protectionSpace] serverTrust]] forAuthenticationChallenge:challenge];
}
}
Use -connection:willSendRequestForAuthenticationChallenge:
instead of these Deprecated Methods
Deprecated:
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
-(void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
Or use good old "find". For example in order to look for old mysql v5.7:
cd /
find . type -d -name "[email protected]"
Just add these lines to your /etc/mtab
and /etc/fstab
, and reboot the system.
none /dev/pts devpts defaults 0 0
SSIS (SQL Server Integration Services) is an upgrade of DTS (Data Transformation Services), which is a feature of the previous version of SQL Server. SSIS packages can be created in BIDS (Business Intelligence Development Studio). These can be used to merge data from heterogeneous data sources into SQL Server. They can also be used to populate data warehouses, to clean and standardize data, and to automate administrative tasks.
SQL Server Integration Services (SSIS) is a component of Microsoft SQL Server 2005. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is only available in the "Standard" and "Enterprise" editions. Integration Services provides a platform to build data integration and workflow applications. The primary use for SSIS is data warehousing as the product features a fast and flexible tool for data extraction, transformation, and loading (ETL).). The tool may also be used to automate maintenance of SQL Server databases, update multidimensional cube data, and perform other functions.
Simply specify the regexp anchors.
grep '^ABB\.log$' a.tmp
DefaultForeColor is enough for this statement. This property gets the default foreground color of the control.
lblExample.ForeColor = DefaultForeColor;
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g>
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(145,200,103);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(132,168,86);stop-opacity:1" />
</linearGradient>
</defs>
<rect width="220" height="30" class="GradientBorder" fill="url(#grad1)" />
<text x="60" y="20" font-family="Calibri" font-size="20" fill="white" >My Code , Your Achivement....... </text>
</g>
</svg>
the same solution as Basit .. but the version 3.0 doesn't work for me try this .. it works for me to integrate struts 2.x
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>blabla</display-name>
...
</web-app>
Here is my working example:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Product product, HttpPostedFileBase file)
{
if (!ModelState.IsValid)
return PartialView("Create", product);
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var guid = Guid.NewGuid().ToString();
var path = Path.Combine(Server.MapPath("~/Content/Uploads/ProductImages"), guid + fileName);
file.SaveAs(path);
string fl = path.Substring(path.LastIndexOf("\\"));
string[] split = fl.Split('\\');
string newpath = split[1];
string imagepath = "Content/Uploads/ProductImages/" + newpath;
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
var nId = Guid.NewGuid().ToString();
// Save record to database
product.Id = nId;
product.State = 1;
product.ImagePath = imagepath;
product.CreatedAt = DateTime.Now;
db.Products.Add(product);
await db.SaveChangesAsync();
TempData["message"] = "ProductCreated";
//return RedirectToAction("Index", product);
}
// after successfully uploading redirect the user
return Json(new { success = true });
}
Use pandas:
import pandas as pd
my_csv = pd.read_csv(filename)
column = my_csv.column_name
# you can also use my_csv['column_name']
Discard unneeded columns at parse time:
my_filtered_csv = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])
P.S. I'm just aggregating what other's have said in a simple manner. Actual answers are taken from here and here.
This script works on Windows, and should work on other OSes : It works on Windows, Debian, and macosx, need a test on solaris.
import os
import platform
def isUp(hostname):
giveFeedback = False
if platform.system() == "Windows":
response = os.system("ping "+hostname+" -n 1")
else:
response = os.system("ping -c 1 " + hostname)
isUpBool = False
if response == 0:
if giveFeedback:
print hostname, 'is up!'
isUpBool = True
else:
if giveFeedback:
print hostname, 'is down!'
return isUpBool
print(isUp("example.com")) #Example domain
print(isUp("localhost")) #Your computer
print(isUp("invalid.example.com")) #Unresolvable hostname: https://tools.ietf.org/html/rfc6761
print(isUp("192.168.1.1")) #Pings local router
print(isUp("192.168.1.135")) #Pings a local computer - will differ for your network
You can use two ways to resolve this problem, first way that i think it as best way is replace importing segment of your code with bellow one:
import Home from './layouts/Home'
or export your component without default which is called named export like this
import React, { Component } from 'react';
class Home extends Component{
render(){
return(
<p className="App-intro">
Hello Man
</p>
)
}
}
export {Home};
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
UPDATE TABLE <tablename>
SET <COLUMN=VALUE>
WHERE <CONDITION>
Example:
UPDATE TABLE teacher SET teacher_name='NSP' WHERE teacher_id='1'
I answered a similar question a couple weeks ago.
There is example code in that question, but basically you can do something like this: (Note the capitalization of User-Agent
as of RFC 2616, section 14.43.)
opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://www.stackoverflow.com')
For me, the main difference is that a script is interpreted, while a program is executed (i.e. the source is first compiled, and the result of that compilation is expected).
Wikipedia seems to agree with me on this :
Script :
"Scripts" are distinct from the core code of the application, which is usually written in a different language, and are often created or at least modified by the end-user.
Scripts are often interpreted from source code or bytecode, whereas the applications they control are traditionally compiled to native machine code.
Program :
The program has an executable form that the computer can use directly to execute the instructions.
The same program in its human-readable source code form, from which executable programs are derived (e.g., compiled)
Start by registering your custom browser/uploader when you instantiate CKEditor.
<script type="text/javascript">
CKEDITOR.replace('content', {
filebrowserUploadUrl: "Upload File Url",//http://localhost/phpwork/test/ckFileUpload.php
filebrowserWindowWidth : 800,
filebrowserWindowHeight : 500
});
</script>
Code for upload file(ckFileUpload.php) & put the upload file on root dir of your project.
// HERE SET THE PATH TO THE FOLDERS FOR IMAGES AND AUDIO ON YOUR SERVER (RELATIVE TO THE ROOT OF YOUR WEBSITE ON SERVER)
$upload_dir = array(
'img'=> '/phpwork/test/uploads/editor-images/',
'audio'=> '/phpwork/ezcore_v1/uploads/editor-images/'
);
// HERE PERMISSIONS FOR IMAGE
$imgset = array(
'maxsize' => 2000, // maximum file size, in KiloBytes (2 MB)
'maxwidth' => 900, // maximum allowed width, in pixels
'maxheight' => 800, // maximum allowed height, in pixels
'minwidth' => 10, // minimum allowed width, in pixels
'minheight' => 10, // minimum allowed height, in pixels
'type' => array('bmp', 'gif', 'jpg', 'jpeg', 'png'), // allowed extensions
);
// HERE PERMISSIONS FOR AUDIO
$audioset = array(
'maxsize' => 20000, // maximum file size, in KiloBytes (20 MB)
'type' => array('mp3', 'ogg', 'wav'), // allowed extensions
);
// If 1 and filename exists, RENAME file, adding "_NR" to the end of filename (name_1.ext, name_2.ext, ..)
// If 0, will OVERWRITE the existing file
define('RENAME_F', 1);
$re = '';
if(isset($_FILES['upload']) && strlen($_FILES['upload']['name']) >1) {
define('F_NAME', preg_replace('/\.(.+?)$/i', '', basename($_FILES['upload']['name']))); //get filename without extension
// get protocol and host name to send the absolute image path to CKEditor
$protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
$site = $protocol. $_SERVER['SERVER_NAME'] .'/';
$sepext = explode('.', strtolower($_FILES['upload']['name']));
$type = end($sepext); // gets extension
$upload_dir = in_array($type, $imgset['type']) ? $upload_dir['img'] : $upload_dir['audio'];
$upload_dir = trim($upload_dir, '/') .'/';
//checkings for image or audio
if(in_array($type, $imgset['type'])){
list($width, $height) = getimagesize($_FILES['upload']['tmp_name']); // image width and height
if(isset($width) && isset($height)) {
if($width > $imgset['maxwidth'] || $height > $imgset['maxheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .' \\n The maximum Width x Height must be: '. $imgset['maxwidth']. ' x '. $imgset['maxheight'];
if($width < $imgset['minwidth'] || $height < $imgset['minheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .'\\n The minimum Width x Height must be: '. $imgset['minwidth']. ' x '. $imgset['minheight'];
if($_FILES['upload']['size'] > $imgset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $imgset['maxsize']. ' KB.';
}
}
else if(in_array($type, $audioset['type'])){
if($_FILES['upload']['size'] > $audioset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $audioset['maxsize']. ' KB.';
}
else $re .= 'The file: '. $_FILES['upload']['name']. ' has not the allowed extension type.';
//set filename; if file exists, and RENAME_F is 1, set "img_name_I"
// $p = dir-path, $fn=filename to check, $ex=extension $i=index to rename
function setFName($p, $fn, $ex, $i){
if(RENAME_F ==1 && file_exists($p .$fn .$ex)) return setFName($p, F_NAME .'_'. ($i +1), $ex, ($i +1));
else return $fn .$ex;
}
$f_name = setFName($_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir, F_NAME, ".$type", 0);
$uploadpath = $_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir . $f_name; // full file path
// If no errors, upload the image, else, output the errors
if($re == '') {
if(move_uploaded_file($_FILES['upload']['tmp_name'], $uploadpath)) {
$CKEditorFuncNum = $_GET['CKEditorFuncNum'];
$url = $site. $upload_dir . $f_name;
$msg = F_NAME .'.'. $type .' successfully uploaded: \\n- Size: '. number_format($_FILES['upload']['size']/1024, 2, '.', '') .' KB';
$re = in_array($type, $imgset['type']) ? "window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')" //for img
: 'var cke_ob = window.parent.CKEDITOR; for(var ckid in cke_ob.instances) { if(cke_ob.instances[ckid].focusManager.hasFocus) break;} cke_ob.instances[ckid].insertHtml(\'<audio src="'. $url .'" controls></audio>\', \'unfiltered_html\'); alert("'. $msg .'"); var dialog = cke_ob.dialog.getCurrent(); dialog.hide();';
}
else $re = 'alert("Unable to upload the file")';
}
else $re = 'alert("'. $re .'")';
}
@header('Content-type: text/html; charset=utf-8');
echo '<script>'. $re .';</script>';
Ck-editor documentation is not clear after doing alot of R&D for custom file upload finally i have found this solution. It work for me and i hope it will helpful to others as well.
Try a slight different approach:
//set string and append it as object
var myHtmlString = '<iframe id="myFrame" width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>';
$('body').append(myHtmlString);
//as you noticed you can't just get it back
var myHtmlStringBack = $('#myFrame').html();
alert(myHtmlStringBack); // will be empty (a bug in jquery?) but...
//since an id was added to your iframe so you can retrieve its attributes back...
var width = $('#myFrame').attr('width');
var height = $('#myFrame').attr('height');
var src = $('#myFrame').attr('src');
var myReconstructedString = '<iframe id="myFrame" width="'+ width +'" height="'+ height +'" src="'+ src+'" frameborder="0" allowfullscreen></iframe>';
alert(myReconstructedString);
You can use the following command:
diff -x .git -r repo-A repo-B
or for the side by side you can use:
diff -x .git -W200 -y -r repo-A repo-B
In case of Colorizing every diff file, you can use:
diff -x .git -W200 -y -r repo-A repo-B | sed -e "s/\(^diff .*\)/\x1b[31m\1\x1b[0m/"
Project > Generate Javadoc....
In the Javadoc command: field, browse to find javadoc.exe (usually at [path_to_jdk_directory]\bin\javadoc.exe).
Check the box next to the project/package/file for which you are creating the Javadoc.
In the Destination: field, browse to find the desired destination (for example, the root directory of the current project).
Click Finish.
You should now be able to find the newly generated Javadoc in the destination folder. Open index.html.
In some browsers you will face problems if you are not giving an href attribute. I suggest you to write your code something like this:
<a href="#" onclick="yourcode();return false;">Link</a>
you can replace yourcode() with your own function or logic,but do remember to add return false; statement at the end.
You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect
for this.
The following version works:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{ id: 0, value: " --- Select a State ---" }];
const allowedState = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const [stateOptions, setStateValues] = useState(initialValue);
// initialValue.push(...allowedState);
console.log(initialValue.length);
// ****** BEGINNING OF CHANGE ******
useEffect(() => {
// Should not ever set state during rendering, so do this in useEffect instead.
setStateValues(allowedState);
}, []);
// ****** END OF CHANGE ******
return (<div>
<label>Select a State:</label>
<select>
{stateOptions.map((localState, index) => (
<option key={localState.id}>{localState.value}</option>
))}
</select>
</div>);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
and here it is in a code sandbox.
I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState
directly without using useState
at all). If so, that api call to load the list could also go inside the useEffect
block.
You can also let angular material solve the size itself depending on the content. This means you don't have to cloud your TS files with sizes that depend on your UI. You can keep these in the HTML/CSS.
my-dialog.html
<div class="myContent">
<h1 mat-dialog-title fxLayoutAlign="center">Your title</h1>
<form [formGroup]="myForm" fxLayout="column">
<div mat-dialog-content>
</div mat-dialog-content>
</form>
</div>
my-dialog.scss
.myContent {
width: 300px;
height: 150px;
}
my-component.ts
const myInfo = {};
this.dialog.open(MyDialogComponent, { data: myInfo });
I have tried many permutations by increasing heapspace and changing the garbage collector settings to speed up Eclipse.
But for my local development, in my humble opinion, I have seen that disabling the JVM garbage collector works best for me.
Mylyn autocomplete feature works with no issue and the (Not Responding) part has been significantly minimzed.
Below is a snapshot of my eclipse.ini file.
-vm
--C:\JAVA\jre\bin\server\jvm.dll
C:\JAVA8x64\jre\bin\server\jvm.dll
-vmargs
-Xnoclassgc
-Dosgi.requiredJavaVersion=1.6
-Xms256m
-Xmx1024m
I have tried using JDK 6 and JDK 8, and in both cases, noticed a significant speedup.
Apache Subversion supports path-based authorization that helps you configure granular permissions for user and group accounts on paths in your repositories (files or directories). Path-based authorization supports three access levels - No Access, Read Only and Read / Write.
Path-based authorization permissions are stored in per-repository or per-server authorization files with a special syntax. Here is an example from SVNBook:
[calc:/branches/calc/bug-142]
harry = rw
sally = r
When you require a complex permission structure with many paths and accounts you can benefit from a GUI-based permission management tools provided by VisualSVN Server:
Repository permissions in VisualSVN Server Manager
This is inspired from the original best answer provided by atzz, I just added replace file / folder logic. So it doesn't actually merge, but deletes the existing file/ folder and copies the new one:
import shutil
import os
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.exists(d):
try:
shutil.rmtree(d)
except Exception as e:
print e
os.unlink(d)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
#shutil.rmtree(src)
Uncomment the rmtree to make it a move function.
I find the accepted answer, and all the others strange, since they pass self
to an abstract class. An abstract class is not instantiated so can't have a self
.
So try this, it works.
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def foo():
"""An abstract method. No need to write pass"""
class Derived(Abstract):
def foo(self):
print('Hooray!')
FOO = Derived()
FOO.foo()
On Linux, I had the same problem of getting rid of the buffering. I finally used "stdbuf -o0" (or, unbuffer from expect) to get rid of the PIPE buffering.
proc = Popen(['stdbuf', '-o0'] + cmd, stdout=PIPE, stderr=PIPE)
stdout = proc.stdout
I could then use select.select on stdout.
I think the easiest way to think about this variable like input parameter in lambda expression in C#. I.e. $_
is similar to x
in x => Console.WriteLine(x)
anonymous function in C#. Consider following examples:
PowerShell:
1,2,3 | ForEach-Object {Write-Host $_}
Prints:
1
2
3
or
1,2,3 | Where-Object {$_ -gt 1}
Prints:
2
3
And compare this with C# syntax using LINQ:
var list = new List<int> { 1, 2, 3 };
list.ForEach( _ => Console.WriteLine( _ ));
Prints:
1
2
3
or
list.Where( _ => _ > 1)
.ToList()
.ForEach(s => Console.WriteLine(s));
Prints:
2
3
The answer is no; there can only one "main" method - where "main" means an entry point you can "run".
You can code overloaded versions as in your example, but they can't be "run".
I understand that the Q does not want to use a library, but I will offer this for others coming from Google searches. @EricRowell mentioned a good plugin, but, there is also another plugin you can try, html2canvas.
In our case we are using layered transparent PNG's with z-index
as a "product builder" widget. Html2canvas worked brilliantly to boil the stack down without pushing images, nor using complexities, workarounds, and the "non-responsive" canvas itself. We were not able to do this smoothly/sane with the vanilla canvas+JS.
First use z-index
on absolute divs to generate layered content within a relative positioned wrapper. Then pipe the wrapper through html2canvas to get a rendered canvas, which you may leave as-is, or output as an image so that a client may save it.
Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your function here
}
Swift 3
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
// your function here
}
Swift 2
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})
If all you want to do is display an iframe on a page, the simplest solution I was able to come up with doesn't require divs or flex stuff is:
html {
width: 100%;
height: 100%;
display: table;
}
body {
text-align: center;
vertical-align: middle;
display: table-cell;
}
And then the HTML is just:
<html>
<body>
<iframe ...></iframe>
</body>
</html>
If this is all you need you don't need wrapper divs to do it. This works for text content and stuff, too.
Also this looks even simpler.
Something like this:
select
*
from sales
where salesDate >= '11/11/2010'
AND salesDate < (Convert(datetime, '11/11/2010') + 1)
My code to solve this problem:
private void sendMail()
{
//This list can be a parameter of metothd
List<MailAddress> lst = new List<MailAddress>();
lst.Add(new MailAddress("[email protected]"));
lst.Add(new MailAddress("[email protected]"));
lst.Add(new MailAddress("[email protected]"));
lst.Add(new MailAddress("[email protected]"));
try
{
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "10.15.130.28"; //or SMTP name
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
objeto_mail.From = new MailAddress("[email protected]");
//add each email adress
foreach (MailAddress m in lst)
{
objeto_mail.To.Add(m);
}
objeto_mail.Subject = "Sending mail test";
objeto_mail.Body = "Functional test for automatic mail :-)";
client.Send(objeto_mail);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Actually, you don't need all that stuff with opacity, visibility, <input>
styling, etc. Just take a look:
<a href="#">Just click me.</a>
<script type="text/javascript">
$("a").click(function() {
// creating input on-the-fly
var input = $(document.createElement("input"));
input.attr("type", "file");
// add onchange handler if you wish to get the file :)
input.trigger("click"); // opening dialog
return false; // avoiding navigation
});
</script>
Demo on jsFiddle. Tested in Chrome 30.0 and Firefox 24.0. Didn't work in Opera 12.16, however.
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();