Have been edited in 2020-06-15
public class Outer {
public Inner getInner(){
return new Inner(this);
}
static class Inner {
public final Outer Outer;
public Inner(Outer outer) {
this.Outer=outer;
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Inner inner = outer.getInner();
Outer anotherOuter=inner.Outer;
if(anotherOuter == outer) {
System.out.println("Was able to reach out to the outer object via inner !!");
} else {
System.out.println("No luck :-( ");
}
}
}
Maybe this is a good example of when to use nested classes?
// ORIGINAL
class ImageCacheSettings { }
class ImageCacheEntry { }
class ImageCache
{
ImageCacheSettings mSettings;
List<ImageCacheEntry> mEntries;
}
And:
// REFACTORED
class ImageCache
{
Settings mSettings;
List<Entry> mEntries;
class Settings {}
class Entry {}
}
PS: I've not taken into account which access modifiers should be applied (private, protected, public, internal)
Declare the INNER class Thing as a static and it will work with no issues.
I remember I have the same issue with the inner class Dog when I declared it as class Dog { only. I got the same issue as you did. There were two solutions:
1- To declare the inner class Dog as static. Or
2- To move the inner class Dog to a new class by itself.
Here is the Example:
public class ReturnDemo {
public static void main(String[] args) {
int z = ReturnDemo.calculate(10, 12);
System.out.println("z = " + z);
ReturnDemo.Dog dog = new Dog("Bosh", " Doggy");
System.out.println( dog.getDog());
}
public static int calculate (int x, int y) {
return x + y;
}
public void print( ) {
System.out.println("void method");
return;
}
public String getString() {
return "Retrun String type value";
}
static class Dog {
private String breed;
private String name;
public Dog(String breed, String name) {
super();
this.breed = breed;
this.name = name;
}
public Dog getDog() {
// return Dog type;
return this;
}
public String toString() {
return "breed" + breed.concat("name: " + name);
}
}
}
Static inner class cannot access non-static members of enclosing class. It can directly access static members (instance field and methods) of enclosing class same like the procedural style of getting value without creating object.
Static inner class can declare both static and non-static members. The static methods have access to static members of main class. However, it cannot access non-static inner class members. To access members of non-static inner class, it has to create object of non-static inner class.
Non-static inner class cannot declare static field and static methods. It has to be declared in either static or top level types. You will get this error on doing so saying "static fields only be declared in static or top level types".
Non-static inner class can access both static and non-static members of enclosing class in procedural style of getting value, but it cannot access members of static inner class.
The enclosing class cannot access members of inner classes until it creates an object of inner classes. IF main class in accessing members of non-static class it can create object of non-static inner class.
If main class in accessing members of static inner class it has two cases:
One can implement a Builder pattern with nested class. Especially in C++, personally I find it semantically cleaner. For example:
class Product{
public:
class Builder;
}
class Product::Builder {
// Builder Implementation
}
Rather than:
class Product {}
class ProductBuilder {}
I think I wrote an elegant solution to this problem by using namespaces. In my case, the inner class does not need to know his parent class (like the static inner class in Java). As an example I made a class called 'User' and a subclass called 'Type', used as a reference for the user types (ADMIN, OTHERS) in my example. Regards.
User.php (User class file)
<?php
namespace
{
class User
{
private $type;
public function getType(){ return $this->type;}
public function setType($type){ $this->type = $type;}
}
}
namespace User
{
class Type
{
const ADMIN = 0;
const OTHERS = 1;
}
}
?>
Using.php (An example of how to call the 'subclass')
<?php
require_once("User.php");
//calling a subclass reference:
echo "Value of user type Admin: ".User\Type::ADMIN;
?>
First of all There is no such class called Static class.The Static modifier use with inner class (called as Nested Class) says that it is a static member of Outer Class which means we can access it as with other static members and without having any instance of Outer class. (Which is benefit of static originally.)
Difference between using Nested class and regular Inner class is:
OuterClass.InnerClass inner = new OuterClass().new InnerClass();
First We can to instantiate Outerclass then we Can access Inner.
But if Class is Nested then syntax is:
OuterClass.InnerClass inner = new OuterClass.InnerClass();
Which uses the static Syntax as normal implementation of static keyword.
class Outer(object):
outer_var = 1
class Inner(object):
@property
def inner_var(self):
return Outer.outer_var
This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var
. (If you change what object the name Outer
is bound to, then this code will use that object the next time it is executed.)
If you instead want all Inner
objects to have a reference to an Outer
because outer_var
is really an instance attribute:
class Outer(object):
def __init__(self):
self.outer_var = 1
def get_inner(self):
return self.Inner(self)
# "self.Inner" is because Inner is a class attribute of this class
# "Outer.Inner" would also work, or move Inner to global scope
# and then just use "Inner"
class Inner(object):
def __init__(self, outer):
self.outer = outer
@property
def inner_var(self):
return self.outer.outer_var
Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer
to Inner
, if you want.)
Yes it is correct. you can do it with an inner class.
Sometimes, we need to create a new instance of an inner class that can't be static because it depends on some global variables of the parent class. In that situation, if you try to create the instance of an inner class that is not static, a not an enclosing class
error is thrown.
Taking the example of the question, what if ZShape
can't be static because it need global variable of Shape
class?
How can you create new instance of ZShape
? This is how:
Add a getter in the parent class:
public ZShape getNewZShape() {
return new ZShape();
}
Access it like this:
Shape ss = new Shape();
ZShape s = ss.getNewZShape();
First of all, you are trying to access non-static member var
outside the class which is not allowed in C++.
Mark's answer is correct.
Anything that is part of Outer should have access to all of Outer's members, public or private.
So you can do two things, either declare var
as static
or use a reference of an instance of the outer class to access 'var' (because a friend class or function also needs reference to access private data).
Static var
Change var
to static
If you don't want var
to be associated with the instances of the class.
#include <iostream>
class Outer {
private:
static const char* const MYCONST;
static int var;
public:
class Inner {
public:
Inner() {
Outer::var = 1;
}
void func() ;
};
};
int Outer::var = 0;
void Outer::Inner::func() {
std::cout << "var: "<< Outer::var;
}
int main() {
Outer outer;
Outer::Inner inner;
inner.func();
}
Output- var: 1
Non-static var
An object's reference is must access any non-static member variables.
#include <iostream>
class Outer {
private:
static const char* const MYCONST;
int var;
public:
class Inner {
public:
Inner(Outer &outer) {
outer.var = 1;
}
void func(const Outer &outer) ;
};
};
void Outer::Inner::func(const Outer &outer) {
std::cout << "var: "<< outer.var;
}
int main() {
Outer outer;
Outer::Inner inner(outer);
inner.func(outer);
}
Output- var: 1
Edit - External links are links to my Blog.
... starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.
For example, suppose that the variable numberLength
is not declared final, and you add the marked assignment statement in the PhoneNumber
constructor:
public class OutterClass {
int numberLength; // <== not *final*
class PhoneNumber {
PhoneNumber(String phoneNumber) {
numberLength = 7; // <== assignment to numberLength
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
...
}
...
}
Because of this assignment statement, the variable numberLength is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner class PhoneNumber tries to access the numberLength variable:
http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html
http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
Here's how I do it when I need a database query's results in my batch file:
sqlplus -S schema/schema@db @query.sql> __query.tmp
set /p result=<__query.tmp
del __query.tmp
The key is in line 2: "set /p" sets the value of "result" to the value of the first line (only) in "__query.tmp" via the "<" redirection operator.
Here is a function I wrote to accomplish this based off of the previous answers.
CREATE FUNCTION dbo.RepetitiveReplace
(
@P_String VARCHAR(MAX),
@P_Pattern VARCHAR(MAX),
@P_ReplaceString VARCHAR(MAX),
@P_ReplaceLength INT = 1
)
RETURNS VARCHAR(MAX)
BEGIN
DECLARE @Index INT;
-- Get starting point of pattern
SET @Index = PATINDEX(@P_Pattern, @P_String);
while @Index > 0
begin
--replace matching charactger at index
SET @P_String = STUFF(@P_String, PATINDEX(@P_Pattern, @P_String), @P_ReplaceLength, @P_ReplaceString);
SET @Index = PATINDEX(@P_Pattern, @P_String);
end
RETURN @P_String;
END;
Originally I had a recursive function here which does not play well with sql server as it has a 32 nesting level limit which would result in an error like the below any time you attempt to make 32+ replacements with the function. Instead of trying to make a server level change to allow more nesting (which could be dangerous like allow never ending loops) switching to a while loop makes a lot more sense.
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).
I was also trying to achieve this. From above codes, what I understood was that you can call getch() function multiple times in order to get both bytes getting from the function. So the ord() function is not necessary if you are just looking to use with byte objects.
while True :
if m.kbhit() :
k = m.getch()
if b'\r' == k :
break
elif k == b'\x08'or k == b'\x1b':
# b'\x08' => BACKSPACE
# b'\x1b' => ESC
pass
elif k == b'\xe0' or k == b'\x00':
k = m.getch()
if k in [b'H',b'M',b'K',b'P',b'S',b'\x08']:
# b'H' => UP ARROW
# b'M' => RIGHT ARROW
# b'K' => LEFT ARROW
# b'P' => DOWN ARROW
# b'S' => DELETE
pass
else:
print(k.decode(),end='')
else:
print(k.decode(),end='')
This code will work print any key until enter key is pressed in CMD or IDE (I was using VS CODE) You can customize inside the if for specific keys if needed
If you're using IDLE, you can use Ctrl+]
to indent and Ctrl+[
to unindent.
Specifying inheritance in the FileSystemAccessRule()
constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl"
and "Allow"
).
$Acl = Get-Acl "\\R9N2WRN\Share"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl
According to this topic
"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."
I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.
If you only need to replace characters in one specific column, somehow regex=True and in place=True all failed, I think this way will work:
data["column_name"] = data["column_name"].apply(lambda x: x.replace("characters_need_to_replace", "new_characters"))
lambda is more like a function that works like a for loop in this scenario. x here represents every one of the entries in the current column.
The only thing you need to do is to change the "column_name", "characters_need_to_replace" and "new_characters".
If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"
For example, if your not careful you may be tempted to try something like:
Dim foo As Integer? = If(someTrueExpression, Nothing, 2)
Will give "foo" a value of 0!
I think the '?' operator equivalent in C# would instead fail compilation
I wrote a small "TreeMap" class based on "HashMap" that supports adding paths:
import java.util.HashMap;
import java.util.LinkedList;
public class TreeMap<T> extends LinkedHashMap<T, TreeMap<T>> {
public void put(T[] path) {
LinkedList<T> list = new LinkedList<>();
for (T key : path) {
list.add(key);
}
return put(list);
}
public void put(LinkedList<T> path) {
if (path.isEmpty()) {
return;
}
T key = path.removeFirst();
TreeMap<T> val = get(key);
if (val == null) {
val = new TreeMap<>();
put(key, val);
}
val.put(path);
}
}
It can be use to store a Tree of things of type "T" (generic), but does not (yet) support storing extra data in it's nodes. If you have a file like this:
root, child 1
root, child 1, child 1a
root, child 1, child 1b
root, child 2
root, child 3, child 3a
Then you can make it a tree by executing:
TreeMap<String> root = new TreeMap<>();
Scanner scanner = new Scanner(new File("input.txt"));
while (scanner.hasNextLine()) {
root.put(scanner.nextLine().split(", "));
}
And you will get a nice tree. It should be easy to adapt to your needs.
Pros
%1
, %2
, ... %*
in tact/arg
and -arg
styleCons
setlocal
for local scoping or write an accompanying :CLEAR-ARGS
routine!--force
to -f
)""
argument supportHere is an example how the following arguments relate to .bat variables:
>> testargs.bat /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"
echo %* | /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"
echo %ARG_FOO% | c:\
echo %ARG_A% |
echo %ARG_B% | 3
echo %ARG_C% | 1
echo %ARG_D% | 1
@echo off
setlocal
CALL :ARG-PARSER %*
::Print examples
echo: ALL: %*
echo: FOO: %ARG_FOO%
echo: A: %ARG_A%
echo: B: %ARG_B%
echo: C: %ARG_C%
echo: D: %ARG_D%
::*********************************************************
:: Parse commandline arguments into sane variables
:: See the following scenario as usage example:
:: >> thisfile.bat /a /b "c:\" /c /foo 5
:: >> CALL :ARG-PARSER %*
:: ARG_a=1
:: ARG_b=c:\
:: ARG_c=1
:: ARG_foo=5
::*********************************************************
:ARG-PARSER
::Loop until two consecutive empty args
:loopargs
IF "%~1%~2" EQU "" GOTO :EOF
set "arg1=%~1"
set "arg2=%~2"
shift
::Allow either / or -
set "tst1=%arg1:-=/%"
if "%arg1%" NEQ "" (
set "tst1=%tst1:~0,1%"
) ELSE (
set "tst1="
)
set "tst2=%arg2:-=/%"
if "%arg2%" NEQ "" (
set "tst2=%tst2:~0,1%"
) ELSE (
set "tst2="
)
::Capture assignments (eg. /foo bar)
IF "%tst1%" EQU "/" IF "%tst2%" NEQ "/" IF "%tst2%" NEQ "" (
set "ARG_%arg1:~1%=%arg2%"
GOTO loopargs
)
::Capture flags (eg. /foo)
IF "%tst1%" EQU "/" (
set "ARG_%arg1:~1%=1"
GOTO loopargs
)
goto loopargs
GOTO :EOF
Or you could just put
background-color: rgba(0,0,0,0.0);
That should solve your problem.
This will works perfectly in both cases, one or multiple fields searching multiple words.
Hope this will help someone. Thanks
declare @searchTrm varchar(MAX)='one two three four';
--select value from STRING_SPLIT(@searchTrm, ' ') where trim(value)<>''
select * from Bols
WHERE EXISTS (SELECT value
FROM STRING_SPLIT(@searchTrm, ' ')
WHERE
trim(value)<>''
and(
BolNumber like '%'+ value+'%'
or UserComment like '%'+ value+'%'
or RequesterId like '%'+ value+'%' )
)
Since iOS 13, UI_USER_INTERFACE_IDIOM
has been deprecated. If your code is still in Obj-C
, you can use the following:
if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
// device is iPad
}
Where:
typedef NS_ENUM(NSInteger, UIUserInterfaceIdiom) {
UIUserInterfaceIdiomUnspecified = -1,
UIUserInterfaceIdiomPhone API_AVAILABLE(ios(3.2)), // iPhone and iPod touch style UI
UIUserInterfaceIdiomPad API_AVAILABLE(ios(3.2)), // iPad style UI
UIUserInterfaceIdiomTV API_AVAILABLE(ios(9.0)), // Apple TV style UI
UIUserInterfaceIdiomCarPlay API_AVAILABLE(ios(9.0)), // CarPlay style UI
};
As of rev 17 of the Android Developer Tools, the correct way to add a library jar when.using the tools and Eclipse is to create a directory called libs
on the same level as your src
and assets
directories and then drop the jar in there. Nothing else.required, the tools take care of all the rest for you automatically.
Just to add to the conversation, using .NET 4.6.2 I was also able to do the following. I tested the code and it did work for me.
You can also do multiple "OR" statements, like below:
switch (value)
{
case string a when a.Contains("text1"):
// Do Something
break;
case string b when b.Contains("text3") || b.Contains("text4") || b.Contains("text5"):
// Do Something else
break;
default:
// Or do this by default
break;
}
You can also check if it matches a value in an array:
string[] statuses = { "text3", "text4", "text5"};
switch (value)
{
case string a when a.Contains("text1"):
// Do Something
break;
case string b when statuses.Contains(value):
// Do Something else
break;
default:
// Or do this by default
break;
}
-v
is the "inverted match" flag, so piping is a very good way:
grep "loom" ~/projects/**/trunk/src/**/*.@(h|cpp)| grep -v "gloom"
Mike; Everytime I need to modify an XML document I work it this way:
//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;
xmlDoc.Save(xmlFile);
//xmlFile is the path of your file to be modified
I hope you find it useful
It is similar to x = (x >> 1)
.
(operand1)(operator)=(operand2) implies(=>) (operand1)=(operand1)(operator)(operand2)
It shifts the binary value of x by one to the right.
E.g.
int x=3; // binary form (011)
x = x >> 1; // zero shifted in from the left, 1 shifted out to the right:
// x=1, binary form (001)
It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:
myFunc() = Object(...);
That would work nicely if myFunc
returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.
No there isn't an escape character as such, instead you can use "
or even <![CDATA["]]>
to represent the "
character.
Another solution from codeConcussion (https://stackoverflow.com/a/7265394/2793768)
var param = "Address";
var pi = typeof(Student).GetProperty(param);
var orderByAddress = items.OrderBy(x => pi.GetValue(x, null));
Try Like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class UserController extends Controller
{
function index(){
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
}
}
?>
I believe that the code should be:
$connect = new mysqli("host", "root", "", "dbname");
because root does not have a password. the (using password: YES)
is saying "you're using a password with this user"
try this:
$("#mydate").datepicker("setDate",'1d');
I know of few packages that support "make uninstall" but many more that support make install DESTDIR=xxx" for staged installs.
You can use this to create a package which you install instead of installing directly from the source. I had no luck with checkinstall but fpm works very well.
This can also help you remove a package previously installed using make install. You simply force install your built package over the make installed one and then uninstall it.
For example, I used this recently to deal with protobuf-3.3.0. On RHEL7:
make install DESTDIR=dest
cd dest
fpm -f -s dir -t rpm -n protobuf -v 3.3.0 \
--vendor "You Not RedHat" \
--license "Google?" \
--description "protocol buffers" \
--rpm-dist el7 \
-m [email protected] \
--url "http:/somewhere/where/you/get/the/package/oritssource" \
--rpm-autoreqprov \
usr
sudo rpm -i -f protobuf-3.3.0-1.el7.x86_64.rpm
sudo rpm -e protobuf-3.3.0
Prefer yum to rpm if you can.
On Debian9:
make install DESTDIR=dest
cd dest
fpm -f -s dir -t deb -n protobuf -v 3.3.0 \
-C `pwd` \
--prefix / \
--vendor "You Not Debian" \
--license "$(grep Copyright ../../LICENSE)" \
--description "$(cat README.adoc)" \
--deb-upstream-changelog ../../CHANGES.txt \
--url "http:/somewhere/where/you/get/the/package/oritssource" \
usr/local/bin \
usr/local/lib \
usr/local/include
sudo apt install -f *.deb
sudo apt-get remove protobuf
Prefer apt to dpkg where you can.
I've also posted answer this here
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
I found this snippet to work well when switching between X and no-X environments.
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
resource_url = 'http://localhost:8080/service/'
response = json.loads(urllib2.urlopen(resource_url).read())
Perhaps you'd consider using android:shadowColor, android:shadowDx
, android:shadowDy
, android:shadowRadius
; alternatively setShadowLayer() ?
Very easy. First put
io.sockets.on('connection', function (socket) {
console.log(socket);
You will see all fields of socket. then use CTRL+F and search the word address. Finally, when you find the field remoteAddress use dots to filter data. in my case it is
console.log(socket.conn.remoteAddress);
In your Page_Load you will want to clear out the normal output and write your own, for example:
string json = "{\"name\":\"Joe\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
To convert a C# object to JSON you can use a library such as Json.NET.
Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.
It work a simple example recursive (Y)
<?php function factorial($y,$x) { if ($y < $x) { echo $y; } else { echo $x; factorial($y,$x+1); } } $y=10; $x=0; factorial($y,$x); ?>
If by any chance you use VSCode and has installed the docker extension, just right+click on the docker you want to check (within the docker extension), click on Inspect, and there search for env, you will find all your env variables values
Consider using the following which its far better than the accepted answer
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate == null
? DateTime.Now : (DateTime)_objHotelPackageOrder.UpdatedDate;
It's just docker pull busybox
, are you using an up to date version of the docker
client. I think they stopped supporting clients lower than 1.5.
Incidentally that curl works for me:
$ curl -k https://registry.hub.docker.com/v1/repositories/busybox/tags
[{"layer": "fc0db02f", "name": "latest"}, {"layer": "fc0db02f", "name": "1"}, {"layer": "a6dbc8d6", "name": "1-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21.0-ubuntu"}, {"layer": "d7057cb0", "name": "1.23"}, {"layer": "d7057cb0", "name": "1.23.2"}, {"layer": "fc0db02f", "name": "1.24"}, {"layer": "3d5bcd78", "name": "1.24.0"}, {"layer": "fc0db02f", "name": "1.24.1"}, {"layer": "1c677c87", "name": "buildroot-2013.08.1"}, {"layer": "0f864637", "name": "buildroot-2014.02"}, {"layer": "a6dbc8d6", "name": "ubuntu"}, {"layer": "ff8f955d", "name": "ubuntu-12.04"}, {"layer": "633fcd11", "name": "ubuntu-14.04"}]
Interesting enough if you sniff the headers you get a HTTP 405 (Method not allowed). I think this might be to do with the fact that Docker have deprecated their Registry API.
You can simply use list comprehension in python:
def replace_element(YOUR_LIST, set_to=NEW_VALUE):
return [i
if SOME_CONDITION
else NEW_VALUE
for i in YOUR_LIST]
for your case, where you want to replace all occurrences of 1 with 10, the code snippet will be like this:
def replace_element(YOUR_LIST, set_to=10):
return [i
if i != 1 # keeps all elements not equal to one
else set_to # replaces 1 with 10
for i in YOUR_LIST]
You should check it against null
.
If you want to check if object x is null or not, you can do:
if(x != null)
But if it is not null, it can have properties which are null or empty. You will check those explicitly:
if(x.getProperty() != null)
For "empty" check, it depends on what type is involved. For a Java String
, you usually do:
if(str != null && !str.isEmpty())
As you haven't mentioned about any specific problem with this, difficult to tell.
Just a more brief and simple way using awesome dplyr library:
library(dplyr)
set.seed(275) #to get repeatable data
data.train <- sample_frac(Default, 0.7)
train_index <- as.numeric(rownames(data.train))
data.test <- Default[-train_index, ]
if we consider your real site configuration, than you need to run ReactJS in the head
<!-- Babel ECMAScript 6 injunction -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
and add attribute to your js file - type="text/babel" like
<script src="../js/r1HeadBabel.js" type="text/babel"></script>
then the below code example will work:
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
Adding to @David Roussel answer, classes may be loaded by multiple class loaders.
Lets understand how class loader works.
From javin paul blog in javarevisited :
ClassLoader
follows three principles.
A class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader
Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents.
Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property
System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.
Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader
class.
NOTE: Except Bootstrap class loader, which is implemented in native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader
.
According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true.
According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again
If you're specifically looking for a click outside the element but still within the parent, you can use
<div class="parent" @click.self="onParentClick">
<div class="child"></div>
</div>
I use this for modals.
On CentOS Linux, Python3.6, I edited this file (make a backup copy first)
/usr/lib/python3.6/site-packages/certifi/cacert.pem
to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.
THIS IS A VERY SIMPLE PROBLEM
Here is the best method for solve this problem.
Step 1 : Login to your cPanel (http://website.com/cpanel OR http://cpanel.website.com).
Step 2 : SOFTWARE -> Select PHP Version
Step 3 : Change Your Current PHP version : 5.6
Step 3 : HIT 'Set as current' [ ENJOY ]
//Example to define how to do :
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Address");
dt.Columns.Add("City");
// The table structure is:
//ID FirstName LastName Address City
//Now we want to add a PhoneNo column after the LastName column. For this we use the
//SetOrdinal function, as iin:
dt.Columns.Add("PhoneNo").SetOrdinal(3);
//3 is the position number and positions start from 0.`enter code here`
//Now the table structure will be:
// ID FirstName LastName PhoneNo Address City
Install via:
$ gem install pry
$ pry
Then add:
require 'pry'; binding.pry
into your program.
As of pry
0.12.2 however, there are no navigation commands such as next
, break
, etc. Some other gems additionally provide this, see for example pry-byedebug
.
In my case, I want to skip the Pods
folder when cloning the project. I did step by step like below and it works for me.
Hope it helps.
mkdir my_folder
cd my_folder
git init
git remote add origin -f <URL>
git config core.sparseCheckout true
echo '!Pods/*\n/*' > .git/info/sparse-checkout
git pull origin master
Memo, If you want to skip more folders, just add more line in sparse-checkout file.
public enum Operator
{
PLUS, MINUS, MULTIPLY, DIVIDE
}
public class Calc
{
public void Calculate(int left, int right, Operator op)
{
switch (op)
{
case Operator.DIVIDE:
//Divide
break;
case Operator.MINUS:
//Minus
break;
case Operator.MULTIPLY:
//...
break;
case Operator.PLUS:
//;;
break;
default:
throw new InvalidOperationException("Couldn't process operation: " + op);
}
}
}
All these answers are correct, but I had to also check if the string contains other characters and Hebrew letters so I simply used:
if (!str.match(/^[\d]+$/)) {
//contains other characters as well
}
i like this simple one:
function randstr(prefix)
{
return Math.random().toString(36).replace('0.',prefix || '');
}
since id should (though not must) start with a letter, i'd use it like this:
let div_id = randstr('youtube_div_');
some example values:
youtube_div_4vvbgs01076
youtube_div_1rofi36hslx
youtube_div_i62wtpptnpo
youtube_div_rl4fc05xahs
youtube_div_jb9bu85go7
youtube_div_etmk8u7a3r9
youtube_div_7jrzty7x4ft
youtube_div_f41t3hxrxy
youtube_div_8822fmp5sc8
youtube_div_bv3a3flv425
(EDIT: This does not work in scala 2.9 and maybe not 2.8 either)
Use trunk:
scala> io.File("/etc/passwd").slurp
res0: String =
##
# User Database
#
... etc
The most tricky way is to make its parent equals null (make the tab alone without parent):
tabPage.Parent = null;
And when you want to return it back (will return it back at the end of pages collection) :
tabPage.Parent = tabControl;
And if you want to return it back in a specific location among the pages you can use :
tabControl.TabPages.Insert(indexLocationYouWant, tabPage);
If this really is a QA issue and you can't change the code. Setup a new server instance on the machine and setup the language as "British English"
Add this script element to your body element:
<body>
<script type="text/javascript">
document.body.style.backgroundColor = "#AAAAAA";
</script>
</body>
The simplest solution is to pass the path as an argument when running the jar.
You can automate this with a shell script (.bat in Windows, .sh anywhere else):
java -jar my-jar.jar .
I used .
to pass the current working directory.
UPDATE
You may want to stick the jar file in a sub-directory so users don't accidentally click it. Your code should also check to make sure that the command line arguments have been supplied, and provide a good error message if the arguments are missing.
Unfortunately the standard DNS A-record (domain name to IP address) used by web-browsers to locate web-servers does not include a port number. Web-browsers use the URL protocol prefix (http://) to determine the port number (http = 80, https = 443, ftp = 21, etc.) unless the port number is specifically typed in the URL (for example "http://www.simpledns.com:5000" = port 5000).
Can I specify a TCP/IP port number for my web-server in DNS? (Other than the standard port 80)
// Pear Mail Library
require_once "Mail.php";
$from = '<[email protected]>';
$to = '<[email protected]>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory('smtp', array(
'host' => 'ssl://smtp.gmail.com',
'port' => '465',
'auth' => true,
'username' => '[email protected]',
'password' => 'passwordxxx'
));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo('<p>' . $mail->getMessage() . '</p>');
} else {
echo('<p>Message successfully sent!</p>');
}
Dont use spaces:
SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE
You can generate statement like this: DROP TABLE t1, t2, t3, ...
and then use prepared statements to execute it:
SET FOREIGN_KEY_CHECKS = 0;
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables
FROM information_schema.tables
WHERE table_schema = 'database_name'; -- specify DB name here.
SET @tables = CONCAT('DROP TABLE ', @tables);
PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;
Java does not allow operator overloading. The preferred approach is to define a method on your class to perform the action: a.add(b)
instead of a + b
. You can see a summary of the other bits Java left out from C like languages here: Features Removed from C and C++
You can search for “bullet” when using e.g. BabelPad (which has a Character Map where you can search by character name), but you will hardly find anything larger than U+2022 BULLET (though the size depends on font). Searching for “circle” finds many characters, too many, as the string appears in so many names. The largest simple circle is probably U+25CF BLACK CIRCLE “?”. If it’s too large U+26AB MEDIUM BLACK CIRCLE “?” might be suitable.
Beware that few fonts contain these characters.
You can use the function of java that is:
ContentValues cv = new ContentValues();
cv.put(Constants.DATE, java.lang.System.currentTimeMillis());
In this way, in your db you save a number.
This number could be interpreted in this way:
DateFormat dateF = DateFormat.getDateTimeInstance();
String data = dateF.format(new Date(l));
Instead of l into new Date(l), you shoul insert the number into the column of date.
So, you have your date.
For example i save in my db this number : 1332342462078
But when i call the method above i have this result: 21-mar-2012 16.07.42
I was also facing the same problem and I spent more than a week to fix it. Restarting my machine seemed to have fixed it, but only temporarily.
There was a solution to increase the maximum number of ephemeral ports by editing the registry file. That seemed to have fixed the problem but that also, only temporarily.
For sometime, I kept thinking if I was trying to access a driver which is no longer available, so I have tried to call:
driver.quit()
And then recreate the browser instance, which only gave me: SessionNotFoundException.
I now realized that I had used BOTH System.setProperty
as well as ffCapability.setCapability
to set the path of the binary.
I then tried with only System.setProperty
=> No luck there.
Only ffCapability.setCapability
=> Voila!!! So far it has been working fine. Hopefully it will work great when I try to re-run my scripts tomorrow and the day after and the day after... :)
Bottomline: Use only this
ffCapability.setCapability("binary", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); //for windows`
Hope it helps!
Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.
import pickle
class MyUser(object):
def __init__(self,name):
self.name = name
user = MyUser('Peter')
print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'
with open(filename,'wb') as file_object:
file_object.write(serialized)
with open(filename,'rb') as file_object:
raw_data = file_object.read()
deserialized = pickle.loads(raw_data)
print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
Create a method to recursively iterate through nested lists. If the current element is an instance of list, then call the same method again. If not, print the current element. Here's an example:
data = [1,2,3,[4,[5,6,7,[8,9]]]]
def print_list(the_list):
for each_item in the_list:
if isinstance(each_item, list):
print_list(each_item)
else:
print(each_item)
print_list(data)
Your class Delivery
has no access modifier, which means it defaults to internal
. If you then try to expose a property of that type as public
, it won't work. Your type (class) needs to have the same, or higher access as your property.
More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx
You need to open the project file of your program and it should appear on Management panel.
Right click on the project file, then select add file. You should add the 3 source code (secrypt.h, secrypt.cpp, and the trial.cpp)
Compile and enjoy. Hope, I could help you.
I believe the solutions,
,engine='python'
, error_bad_lines = False
will be good if it is dummy columns and you want to delete it. In my case, the second row really had more columns and I wanted those columns to be integrated and to have the number of columns = MAX(columns).
Please refer to the solution below that I could not read anywhere:
try:
df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep)
except pd.errors.ParserError as err:
str_find = 'saw '
int_position = int(str(err).find(str_find)) + len(str_find)
str_nbCol = str(err)[int_position:]
l_col = range(int(str_nbCol))
df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep, names = l_col)
Setting the environment variable NODE_PATH to point to your global node_modules
folder.
In Windows 7 or higher the path is something like %AppData%\npm\node_modules
while in UNIX could be something like /home/sg/.npm_global/lib/node_modules/
but it depends on user configuration.
The command npm config get prefix
could help finding out which is the correct path.
In UNIX systems you can accomplish it with the following command:
export NODE_PATH=`npm config get prefix`/lib/node_modules/
If you want to convert an existing string to raw string, then we can reassign that like below
s1 = "welcome\tto\tPython"
raw_s1 = "%r"%s1
print(raw_s1)
Will print
welcome\tto\tPython
Absolute path routing
There are 2 methods for navigation, .navigate()
and .navigateByUrl()
You can use the method .navigateByUrl()
for absolute path routing:
import {Router} from '@angular/router';
constructor(private router: Router) {}
navigateToLogin() {
this.router.navigateByUrl('/login');
}
You put the absolute path to the URL of the component you want to navigate to.
Note: Always specify the complete absolute path when calling router's navigateByUrl
method. Absolute paths must start with a leading /
// Absolute route - Goes up to root level
this.router.navigate(['/root/child/child']);
// Absolute route - Goes up to root level with route params
this.router.navigate(['/root/child', crisis.id]);
Relative path routing
If you want to use relative path routing, use the .navigate()
method.
NOTE: It's a little unintuitive how the routing works, particularly parent, sibling, and child routes:
// Parent route - Goes up one level
// (notice the how it seems like you're going up 2 levels)
this.router.navigate(['../../parent'], { relativeTo: this.route });
// Sibling route - Stays at the current level and moves laterally,
// (looks like up to parent then down to sibling)
this.router.navigate(['../sibling'], { relativeTo: this.route });
// Child route - Moves down one level
this.router.navigate(['./child'], { relativeTo: this.route });
// Moves laterally, and also add route parameters
// if you are at the root and crisis.id = 15, will result in '/sibling/15'
this.router.navigate(['../sibling', crisis.id], { relativeTo: this.route });
// Moves laterally, and also add multiple route parameters
// will result in '/sibling;id=15;foo=foo'.
// Note: this does not produce query string URL notation with ? and & ... instead it
// produces a matrix URL notation, an alternative way to pass parameters in a URL.
this.router.navigate(['../sibling', { id: crisis.id, foo: 'foo' }], { relativeTo: this.route });
Or if you just need to navigate within the current route path, but to a different route parameter:
// If crisis.id has a value of '15'
// This will take you from `/hero` to `/hero/15`
this.router.navigate([crisis.id], { relativeTo: this.route });
Link parameters array
A link parameters array holds the following ingredients for router navigation:
['/hero']
['/hero', hero.id]
or ['/hero', { id: hero.id, foo: baa }]
Directory-like syntax
The router supports directory-like syntax in a link parameters list to help guide route name lookup:
./
or no leading slash is relative to the current level.
../
to go up one level in the route path.
You can combine relative navigation syntax with an ancestor path. If you must navigate to a sibling route, you could use the ../<sibling>
convention to go up one level, then over and down the sibling route path.
Important notes about relative nagivation
To navigate a relative path with the Router.navigate
method, you must supply the ActivatedRoute
to give the router knowledge of where you are in the current route tree.
After the link parameters array, add an object with a relativeTo
property set to the ActivatedRoute
. The router then calculates the target URL based on the active route's location.
From official Angular Router Documentation
I personally don't like atoi
function. I would suggest sscanf
:
char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);
It's very standard, it's in the stdio.h
library :)
And in my opinion, it allows you much more freedom than atoi
, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.
EDIT
I just found this wonderful question here on the site that explains and compares 3 different ways to do it - atoi
, sscanf
and strtol
. Also, there is a nice more-detailed insight into sscanf
(actually, the whole family of *scanf
functions).
EDIT2
Looks like it's not just me personally disliking the atoi
function. Here's a link to an answer explaining that the atoi
function is deprecated and should not be used in newer code.
echo $this->config->config['ur config file']
If your config file also come to picture you have to access like this for example I include an app.php in config folder I have a variable
$config['50001'] = "your message"
Now I want access in my controller or model .
Try following two cases one should work
case1:
$msg = $this->config->item('ur config file');
echo $msg['50001']; //out put: "your message";
case2:
$msg = $this->config->item('50001');
echo $msg; //out put: "your message"
INSERT
INTO Employee
(emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT '001', 'John Doe', '1 River Walk, Green Street', state_id, position_id, manager_id
FROM dual
JOIN state s
ON s.state_name = 'New York'
JOIN positions p
ON p.position_name = 'Sales Executive'
JOIN manager m
ON m.manager_name = 'Barry Green'
Note that but a single spelling mistake (or an extra space) will result in a non-match and nothing will be inserted.
from jquery api
Added to jQuery in version 1.4, the .delay()
method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show()
or .hide()
which do not use the effects queue.
Try this
var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);
var i = 0, req_index = "";
$.each(json, function(index, value){
if(index == 'key2'){
req_index = i;
}
i++;
});
alert(req_index);
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
You might want to try Catel. It allows you to define a DataWindow class (instead of Window), and that class automatically creates the view model for you. This way, you can use the declaration of the ViewModel as you did in your original post, and the view model will still be created and set as DataContext.
See this article for an example.
To get .woff fonts first open the chrome dev tools panel (Ctrl+Shift+i
) go to Network and reload the page. There you will see everything the page downloads. Find the .woff file, right click and select Copy response.
The response will be a url so paste it in the navigation bar. A file will be downloaded, just add the .woff extension to it and voila.
There is an MSDN blog article on investigating this type of issues:
Troubleshooting ASP.NET – The remote certificate is invalid according to the validation procedure:
http://blogs.msdn.com/b/jpsanders/archive/2009/09/16/troubleshooting-asp-net-the-remote-certificate-is-invalid-according-to-the-validation-procedure.aspx
VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.
Dim val1 As Integer, val2 As Integer, i As Integer
For i = 1 To 333
Sheets("Feuil2").Activate
ActiveSheet.Cells(i, 1).Select
val1 = Cells(i, 1).Value
val2 = Cells(i, 2).Value
Sheets("Classeur2.csv").Select
Cells(val1, val2).Select
ActiveCell.FormulaR1C1 = "1"
Next i
The simplest way to do that
git fetch origin <branch> && git checkout <branch>
Example: I want to fetch uat branch from origin and switch to this as the current working branch.
git fetch origin uat && git checkout uat
var Global = 'Global';
function LocalToGlobalVariable() {
// This creates a local variable.
var Local = '5';
// Doing this makes the variable available for one session
// (a page refresh - it's the session not local)
sessionStorage.LocalToGlobalVar = Local;
// It can be named anything as long as the sessionStorage
// references the local variable.
// Otherwise it won't work.
// This refreshes the page to make the variable take
// effect instead of the last variable set.
location.reload(false);
};
// This calls the variable outside of the function for whatever use you want.
sessionStorage.LocalToGlobalVar;
I realize there is probably a lot of syntax errors in this but its the general idea... Thanks so much LayZee for pointing this out... You can find what a local and session Storage is at http://www.w3schools.com/html/html5_webstorage.asp. I have needed the same thing for my code and this was a really good idea.
Is this what you're after?
I added :text-align:center
to the div and image
Because margin
is ignored on tr
, I usually use a workaround, by setting a transparent border-bottom
or border-top
and setting the background-clip
property to padding-box
so the background-color
does not get painted underneath the border.
table {
border-collapse: collapse; /* [1] */
}
th, td {
border-bottom: 5px solid transparent; /* [2] */
background-color: gold; /* [3] */
background-clip: padding-box; /* [4] */
}
5px
value represents the margin that you want to achievebackground-color
of your row/cellbackground
get not painted underneath the border
see a demo here: http://codepen.io/meodai/pen/MJMVNR?editors=1100
background-clip
is supported in all modern browser. (And IE9+)
Alternatively you could use a border-spacing
. But this will not work with border-collapse
set to collapse
.
C++11 N3337 standard draft
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
19.3 Assertions
1 The header <cassert>, described in (Table 42), provides a macro for documenting C ++ program assertions and a mechanism for disabling the assertion checks.
2 The contents are the same as the Standard C library header <assert.h>.
C99 N1256 standard draft
http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf
7.2 Diagnostics <assert.h>
1 The header
<assert.h>
defines the assert macro and refers to another macro,NDEBUG
which is not defined by<assert.h>
. IfNDEBUG
is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro is defined simply as#define assert(ignore) ((void)0)
The assert macro is redefined according to the current state of NDEBUG each time that
<assert.h>
is included.2. The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.
7.2.1 Program diagnostics
7.2.1.1 The assert macro
Synopsis
1.
#include <assert.h> void assert(scalar expression);
Description
2 The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function — the latter are respectively the values of the preprocessing macros
__FILE__
and__LINE__
and of the identifier__func__
) on the standard error stream in an implementation-defined format. 165) It then calls the abort function.Returns
3 The assert macro returns no value.
I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.
Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.
// 1st
function Outer() {
var deferreds = GetAllData();
$.when.apply($, deferreds).done(function () {
// now you can do whatever you want with the updated page
});
}
// 2nd
function GetAllData() {
var deferreds = [];
$('.calculatedField').each(function (data) {
deferreds.push(GetIndividualData($(this)));
});
return deferreds;
}
// 3rd
function GetIndividualData(item) {
var def = new $.Deferred();
$.post('@Url.Action("GetData")', function (data) {
item.html(data.valueFromAjax);
def.resolve(data);
});
return def;
}
Attaching a Simple Snippet for renaming your current branch (local and on origin):
git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>
Explanation from git docs:
git branch -m or -M option, will be renamed to . If had a corresponding reflog, it is renamed to match , and a reflog entry is created to remember the branch renaming. If exists, -M must be used to force the rename to happen.
The special refspec : (or +: to allow non-fast-forward updates) directs Git to push "matching" branches: for every branch that exists on the local side, the remote side is updated if a branch of the same name already exists on the remote side.
--set-upstream Set up 's tracking information so is considered 's upstream branch. If no is specified, then it defaults to the current branch.
Sample DF:
In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
In [80]: df
Out[80]:
a b c
0 6 11 11
1 14 7 8
2 13 5 11
3 13 7 11
4 13 5 9
5 5 11 9
6 9 8 6
7 5 11 10
8 8 10 14
9 7 14 13
present only those rows where b > 10
In [81]: df[df.b > 10]
Out[81]:
a b c
0 6 11 11
5 5 11 9
7 5 11 10
9 7 14 13
Minimums (for all columns) for the rows satisfying b > 10
condition
In [82]: df[df.b > 10].min()
Out[82]:
a 5
b 11
c 9
dtype: int32
Minimum (for the b
column) for the rows satisfying b > 10
condition
In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11
UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.
If the browser has a pdf plugin installed it executes the object, if not it uses Google's PDF Viewer to display it as plain HTML:
<object data="your_url_to_pdf" type="application/pdf">
<iframe src="https://docs.google.com/viewer?url=your_url_to_pdf&embedded=true"></iframe>
</object>
Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)
#include <iostream>
int main()
{
std::cout<<"Hello World!\n";
return 0;
}
I came with same question but after google, I found there is no big difference :)
From Github
If you wish to create both an HTTP and HTTPS server you may do so with the "http" and "https" modules as shown here.
/**
* Listen for connections.
*
* A node `http.Server` is returned, with this
* application (which is a `Function`) as its
* callback. If you wish to create both an HTTP
* and HTTPS server you may do so with the "http"
* and "https" modules as shown here:
*
* var http = require('http')
* , https = require('https')
* , express = require('express')
* , app = express();
*
* http.createServer(app).listen(80);
* https.createServer({ ... }, app).listen(443);
*
* @return {http.Server}
* @api public
*/
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
Also if you want to work with socket.io see their example
See this
I prefer app.listen()
:)
Others already posted very good answers, but some people might still be looking for a classic way to find Mean(avg), so here I post this (code tested in Python 3.6):
def meanmanual(listt):
mean = 0
lsum = 0
lenoflist = len(listt)
for i in listt:
lsum += i
mean = lsum / lenoflist
return float(mean)
a = [1, 2, 3, 4, 5, 6]
meanmanual(a)
Answer: 3.5
Example for how one might use the Stopwatch class in VB.NET.
Dim Stopwatch As New Stopwatch
Stopwatch.Start()
''// Test Code
Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)
Stopwatch.Restart()
''// Test Again
Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)
Try with JQuery:
<script type="text/javascript">
function jquery_get_width_height()
{
var imgWidth = $("#img").width();
var imgHeight = $("#img").height();
alert("JQuery -- " + "imgWidth: " + imgWidth + " - imgHeight: " + imgHeight);
}
</script>
or
<script type="text/javascript">
function javascript_get_width_height()
{
var img = document.getElementById('img');
alert("JavaSript -- " + "imgWidth: " + img.width + " - imgHeight: " + img.height);
}
</script>
Customizing the Calendar and Date while Marshaling
Step 1 : Prepare jaxb binding xml for custom properties, In this case i prepared for date and calendar
<jaxb:bindings version="2.1" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jaxb:globalBindings generateElementProperty="false">
<jaxb:serializable uid="1" />
<jaxb:javaType name="java.util.Date" xmlType="xs:date"
parseMethod="org.apache.cxf.tools.common.DataTypeAdapter.parseDate"
printMethod="com.stech.jaxb.util.CalendarTypeConverter.printDate" />
<jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
printMethod="com.stech.jaxb.util.CalendarTypeConverter.printCalendar" />
Setp 2 : Add custom jaxb binding file to Apache or any related plugins at xsd option like mentioned below
<xsdOption>
<xsd>${project.basedir}/src/main/resources/tutorial/xsd/yourxsdfile.xsd</xsd>
<packagename>com.tutorial.xml.packagename</packagename>
<bindingFile>${project.basedir}/src/main/resources/xsd/jaxbbindings.xml</bindingFile>
</xsdOption>
Setp 3 : write the code for CalendarConverter class
package com.stech.jaxb.util;
import java.text.SimpleDateFormat;
/**
* To convert the calendar to JaxB customer format.
*
*/
public final class CalendarTypeConverter {
/**
* Calendar to custom format print to XML.
*
* @param val
* @return
*/
public static String printCalendar(java.util.Calendar val) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
return simpleDateFormat.format(val.getTime());
}
/**
* Date to custom format print to XML.
*
* @param val
* @return
*/
public static String printDate(java.util.Date val) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(val);
}
}
Setp 4 : Output
<xmlHeader>
<creationTime>2014-09-25T07:23:05</creationTime> Calendar class formatted
<fileDate>2014-09-25</fileDate> - Date class formatted
</xmlHeader>
Ah I think a understand now. Have a look if this really is what you want:
$(".start").keyup(function(){
$(this).closest('tr').find("input").each(function() {
alert(this.value)
});
});
This will give you all input values of a row.
Update:
To get the value of not all elements you can use :not()
:
$(this).closest('tr').find("input:not([name^=desc][name^=phone])").each(function() {
alert(this.value)
});
Actually I am not 100% sure whether it works this way, maybe you have to use two not
s instead of this one combining both conditions.
This was previously asked on R-Help, so that's worth reviewing.
One suggestion there was to use readChar()
and then do string manipulation on the result with strsplit()
and substr()
. You can see the logic involved in readChar is much less than read.table.
I don't know if memory is an issue here, but you might also want to take a look at the HadoopStreaming package. This uses Hadoop, which is a MapReduce framework designed for dealing with large data sets. For this, you would use the hsTableReader function. This is an example (but it has a learning curve to learn Hadoop):
str <- "key1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey2\t9.9\nkey2\"
cat(str)
cols = list(key='',val=0)
con <- textConnection(str, open = "r")
hsTableReader(con,cols,chunkSize=6,FUN=print,ignoreKey=TRUE)
close(con)
The basic idea here is to break the data import into chunks. You could even go so far as to use one of the parallel frameworks (e.g. snow) and run the data import in parallel by segmenting the file, but most likely for large data sets that won't help since you will run into memory constraints, which is why map-reduce is a better approach.
CTRL+D? http://www.scribd.com/doc/7580088/SQL-Developer-Hot-Keys
If that doesn't work, you might be able to set up an Accelerator: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b31695/intro.htm#sthref208
For those using Laravel, this https://github.com/sitepoint-editors/google-laravel-2FA is a nice way to solve this problem.
In 2020 using r115 it works very good with this:
const renderer = new THREE.WebGLRenderer({ alpha: true });
const scene = new THREE.Scene();
scene.background = null;
Convert dictionary into JSON (string)
import json
mydict = { "name" : "Don",
"surname" : "Mandol",
"age" : 43}
result = json.dumps(mydict)
print(result[0:20])
will get you:
{"name": "Don", "sur
Convert string into dictionary
back_to_mydict = json.loads(result)
I know this is an old question but anyway it might help someone.
I tend to use PHP_EOL
for this purposes (due to cross-platform compatibility).
echo "line 1".PHP_EOL."line 2".PHP_EOL;
If you're planning to show the result in a browser then you have to use "<br>"
.
EDIT: since your exact question is about emails, things are a bit different. For pure text emails see Brendan Bullen's accepted answer. For HTML emails you simply use HTML formatting.
A few years late but this might help someone if you are using eval or backtick substitution:
postDataJson="{\"guid\":\"$guid\",\"auth_token\":\"$token\"}"
Using sed to strip quotes from beginning and end of response
$(curl --silent -H "Content-Type: application/json" https://${target_host}/runs/get-work -d ${postDataJson} | sed -e 's/^"//' -e 's/"$//')
I just faced this issue.
didn't work on TextView
with constraint parameters. Adding android:lines="2"
seems to fix this.
You have everything right, but the problem is with getLine1Number()
function.
getLine1Number()- this method returns the phone number string for line 1, i.e the MSISDN for a GSM phone. Return null if it is unavailable.
this method works only for few cell phone but not all phones.
So, if you need to perform operations according to the sim(other than calling), then you should use getSimSerialNumber()
. It is always unique, valid and it always exists.
You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.
Turn the EXISTS clause into a subquery instead within an IF function
SELECT IF( EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?), 1, 0)
In fact, booleans are returned as 1 or 0
SELECT EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?)
You can look at the docs for the SlugField
to get to know more about it in more descriptive way.
Use control anchoring. Set property Anchor
of your GridView
to Top, Left, Right
and it will resize with container. If your GridView
are placed inside of some container (ex Panel
) then Panel
should be anchored too.
It sounds like you want something like the Perl chomp()
function.
That's trivial to do in Python:
def chomp(s):
return s[:-1] if s.endswith('\n') else s
... assuming you're using Python 2.6 or later. Otherwise just use the slightly more verbose:
def chomp(s):
if s.endwith('\n'):
return s[:-1]
else:
return s
If you want to remove all new lines from the end of a string (in the odd case where one might have multiple trailing newlines for some reason):
def chomps(s):
return s.rstrip('\n')
Obviously you should never see such a string returned by any normal Python file object's readline()
nor readlines()
methods.
I've seen people blindly remove the last characters (using s[:-1]
slicing) from the results of file readline()
and similar functions. This is a bad idea because it can lead to an error on the last line of the file (in the case where a file ends with anything other than a newline).
At first you might be lulled into a false sense of security when blindly stripping final characters off lines you've read. If you use a normal text editor to create your test suite files you'll have a newline silently added to the end of the last line by most of them. To create a valid test file use code something like:
f = open('sometest.txt', 'w')
f.write('some text')
f.close()
... and then if you re-open that file and use the readline()
or readlines()
file methods on it you'll find that the text is read without the trailing newline.
This failure to account for text files ending in non-newline characters has plagued many UNIX utilities and scripting languages for many years. It's a stupid corner base bug that creeps into code just often enough to be a pest but not often enough for people to learn from it. We could argue that "text" files without the ultimate newline are "corrupt" or non-standard; and that may be valid for some programming specifications.
However, it's all too easy to ignore corner cases in our coding and have that ignorance bite people who are depending on your code later. As my wife says: when it comes to programming ... practice safe hex!
<iframe title='YouTube video player' class='youtube-player' type='text/html'
width='030' height='030'
src='http://www.youtube.com/embed/ZFo8b9DbcMM?rel=0&border=&autoplay=1'
type='application/x-shockwave-flash'
allowscriptaccess='always' allowfullscreen='true'
frameborder='0'></iframe>
just insert your code after embed/
In JDBC world, the normal practice (according the JDBC API) is that you use Class#forName()
to load a JDBC driver. The JDBC driver should namely register itself in DriverManager
inside a static block:
package com.dbvendor.jdbc;
import java.sql.Driver;
import java.sql.DriverManager;
public class MyDriver implements Driver {
static {
DriverManager.registerDriver(new MyDriver());
}
public MyDriver() {
//
}
}
Invoking Class#forName()
will execute all static initializers. This way the DriverManager
can find the associated driver among the registered drivers by connection URL during getConnection()
which roughly look like follows:
public static Connection getConnection(String url) throws SQLException {
for (Driver driver : registeredDrivers) {
if (driver.acceptsURL(url)) {
return driver.connect(url);
}
}
throw new SQLException("No suitable driver");
}
But there were also buggy JDBC drivers, starting with the org.gjt.mm.mysql.Driver
as well known example, which incorrectly registers itself inside the Constructor instead of a static block:
package com.dbvendor.jdbc;
import java.sql.Driver;
import java.sql.DriverManager;
public class BadDriver implements Driver {
public BadDriver() {
DriverManager.registerDriver(this);
}
}
The only way to get it to work dynamically is to call newInstance()
afterwards! Otherwise you will face at first sight unexplainable "SQLException: no suitable driver". Once again, this is a bug in the JDBC driver, not in your own code. Nowadays, no one JDBC driver should contain this bug. So you can (and should) leave the newInstance()
away.
From:
it could be:
.html()
In an HTML document, .html()
can be used to get the contents of any element.
.text()
Unlike the .html()
method, .text()
can be used in both XML and HTML documents. The result of the .text()
method is a string containing the combined text of all matched elements.
.val()
The .val()
method is primarily used to get the values of form elements such as input
, select
and textarea
. When called on an empty collection, it returns undefined
.
I found a really cool library, try this out. this is really smooth and easy to use.
all above answers is correct but however
a = [];
len(list1) - 1 # where 0 - 1 = -1
to be more precisely
a = [];
index = len(a) - 1 if a else None;
if index == None : raise Exception("Empty Array")
since arrays is starting with 0
Just give an id
to the element and process it normally eg:
<div id="dv">
<a href="#"></a>
<span></span>
</div>
Now you can do like:
var div = document.getElementById('dv');
div.appendChild(......);
Or with jQuery:
$('#dv').get(0).appendChild(........);
This is how I would do it:
$terms = array('BMW', 'Audi', 'Porsche', 'Honda');
// -- purge 'make' Porsche from terms --
if (!empty($terms)) {
$pos = '';
$pos = array_search('Porsche', $terms);
if ($pos !== false) unset($terms[$pos]);
}
Probably the author won't need my answer anymore. Still, for sake of completeness i feel other users might find it useful. The best and most simple solution is to use $(window).load()
inside the body of the returned function. (alternatively you can use document.ready
. It really depends if you need all the images or not).
Using $timeout
in my humble opinion is a very weak option and may fail in some cases.
Here is the complete code i'd use:
.directive('directiveExample', function(){
return {
restrict: 'A',
link: function($scope, $elem, attrs){
$(window).load(function() {
//...JS here...
});
}
}
});
That's what i am currrently working, what a coincidence.
You also need to add the following lines into your LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// do your magic here
return redirect()->route('dashboard');
}
return redirect('/home');
}
/**
* Where to redirect users after login.
*
* @var string
*/
//protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
}
SIMPLE method may not be the best for all cases
<%
if (Session["Utype"].ToString() == "1")
{
%>
<li><a href="../forms/student.aspx"><i class="fa fa-users"></i><span>STUDENT DETAILS</span></a></li>
<li><a href="../forms/UserManage.aspx"><i class="fa fa-user-plus"></i><span>USER MANAGEMENT</span></a></li>
<%
}
else
{
%>
<li><a href="../forms/Package.aspx"><i class="fa fa-object-group"></i><span>PACKAGE</span></a></li>
<%
}
%>
Execute in command line on OS-X El Captain:
kill -kill `lsof -t -i tcp:3000`
Terse option of lsof returns just the PID.
If you want the actual HTTP Host header, see Daniel Roseman's comment on @Phsiao's answer. The other alternative is if you're using the contrib.sites framework, you can set a canonical domain name for a Site in the database (mapping the request domain to a settings file with the proper SITE_ID is something you have to do yourself via your webserver setup). In that case you're looking for:
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
current_site.domain
you'd have to put the current_site object into a template context yourself if you want to use it. If you're using it all over the place, you could package that up in a template context processor.
You can pass the id as part of the routeValues parameter of the RedirectToAction() method.
return RedirectToAction("Action", new { id = 99 });
This will cause a redirect to Site/Controller/Action/99. No need for temp or any kind of view data.
Please check the code below.
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
var nstr = "";
for (var i = 0; i < splitStr.length; i++) {
nstr += (splitStr[i].charAt(0).toUpperCase()+ splitStr[i].slice(1) + "
");
}
console.log(nstr);
}
var strng = "this is a new demo for checking the string";
titleCase(strng);
But always look out in the console / log for messages. If you see a notification that your query could not be converted to SQL and will be evaluated locally then you may need to rewrite it.
Entity Framework 7 (now renamed to Entity Framework Core 1.0 / 2.0) does not yet support GroupBy()
for translation to GROUP BY
in generated SQL (even in the final 1.0 release it won't). Any grouping logic will run on the client side, which could cause a lot of data to be loaded.
Eventually code written like this will automagically start using GROUP BY, but for now you need to be very cautious if loading your whole un-grouped dataset into memory will cause performance issues.
For scenarios where this is a deal-breaker you will have to write the SQL by hand and execute it through EF.
If in doubt fire up Sql Profiler and see what is generated - which you should probably be doing anyway.
https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2
Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
This would change your serif latex font. You can also specify the sans-serif Helvetica like so
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
Other options are cursive
and monospace
with their respective font names.
Your label would then be
fig.gca().set_xlabel(r'wavelength $5000 \AA$')
If the font doesn't supply an Angstrom symbol you can try using \mathring{A}
There is extensive paramiko API documentation you can find at: http://docs.paramiko.org/en/stable/index.html
I use the following method to execute commands on a password protected client:
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(command)
while True:
if session.recv_ready():
stdout_data.append(session.recv(nbytes))
if session.recv_stderr_ready():
stderr_data.append(session.recv_stderr(nbytes))
if session.exit_status_ready():
break
print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)
session.close()
client.close()
Yes, open a postscript()
device with a filename ending in .eps
, do your plot(s) and call dev.off()
.
To inspect your localStorage items you may type console.log(localStorage);
in your javascript console (firebug for example or in new FF versions the shipped js console).
You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:
localStorage.clear();
Another option, using list comprehension and join:
''.join([_str[i] for i in xrange(len(_str)) if i != 4])
Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.
public Childservice extends BaseService {
public void save(){
//some code
superSave();
}
void superSave(){
super.save();
}
}
The shortcut didn't work for me in Visual Studio 2015, also it was not in the edit menu.
Download and install the Productivity Power Tools for VS2015 and than you can find these options in the edit > advanced menu.
This is the most simple solution if you just need to refresh the entire page
refreshPage() {
window.location.reload();
}
There are two ways to know the about Sybase version,
1) Using this System procedure to get the information about Sybase version
> sp_version
> go
2) Using this command to get Sybase version
> select @@version
> go
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
IIS7 defines a defaultDocument section in its configuration files which can be found in the %WinDir%\System32\InetSrv\Config folder. Most likely, the file index.aspx is already defined as a default document in one of IIS7's configuration files and you are adding it again in your web.config.
I suspect that removing the line
<add value="index.aspx" />
from the defaultDocument/files section will fix your issue.
The defaultDocument section of your config will look like:
<defaultDocument>
<files>
<remove value="default.aspx" />
<remove value="index.html" />
<remove value="iisstart.htm" />
<remove value="index.htm" />
<remove value="Default.asp" />
<remove value="Default.htm" />
</files>
</defaultDocument>
Note that index.aspx will still appear in the list of default documents for your site in the IIS manager.
For more information about IIS7 configuration, click here.
I don't know why you are dividing by 100 but here my assumption int a;
int b = (int) Math.ceil( ((double)a) / 100);
or
int b = (int) Math.ceil( a / 100.0);
SELECT pid FROM planets WHERE userid is null;
Based on Stack Overflow questions Unix cut, remove first token and https://stackoverflow.com/a/15903654/781312:
(octal=$(echo -n ? | od -t o1 | head -1 | cut -d' ' -f2- | sed -e 's#\([0-9]\+\) *#\\0\1#g')
echo Octal representation is following $octal
echo -e "$octal")
Output is the following.
Octal representation is following \0342\0230\0240
?
Try to disable SELinux by this command /usr/sbin/setenforce 0
. In my case it solved the problem.
When you change an ASP.NET website's configuration file, it restarts the application to reflect the changes...
When you do an IIS reset, that restarts all applications running on that IIS instance.
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
More info:
If anyone's still stuck on this, the easiest solution I found was to "Retarget Solution". In my case, the project was built of SDK 8.1, upgrading to VS2017 brought with it SDK 10.0.xxx.
To retarget solution: Project->Retarget Solution->"Select whichever SDK you have installed"->OK
From there on you can simply build/debug your solution. Hope it helps
Here are instructions assuming you want to install Cygwin on a computer with no Internet connection. I assume that you have access to another computer with an Internet connection. Start on the connected computer:
Get the Cygwin install program ("setup.exe"). Direct download URL: x86 or x86_64.
When the setup asks "Choose a download source", choose Download Without Installing
Go through the rest of the setup (choose download directory, mirrors, software packages you want, etc)
Now you have a Cygwin repository right there on your hard disk. Copy this directory, along with the "setup.exe" program, over to your target computer (it does not need to be on a network).
On the target computer, run "setup.exe"
When the setup asks "Choose a download source", choose Install From Local Directory
Complete setup as usual. No Internet access is required.
$.get = $.ajax({type: 'GET'});
$.load()
is a helper function which only can be invoked on elements.
$.ajax()
gives you most control. you can specify if you want to POST data, got more callbacks etc.
You can also use a callable in the default field, such as:
b = models.CharField(max_length=7, default=foo)
And then define the callable:
def foo():
return 'bar'
You can't import conditionally, but you can do the opposite: export something conditionally. It depends on your use case, so this work around might not be for you.
You can do:
api.js
import mockAPI from './mockAPI'
import realAPI from './realAPI'
const exportedAPI = shouldUseMock ? mockAPI : realAPI
export default exportedAPI
apiConsumer.js
import API from './api'
...
I use that to mock analytics libs like mixpanel, etc... because I can't have multiple builds or our frontend currently. Not the most elegant, but works. I just have a few 'if' here and there depending on the environment because in the case of mixpanel, it needs initialization.
In my case i had an overload of function that was causing this Exception, once i changed the name of my second function it ran ok, guess web server doesnot support function overloading
On older browsers, :hover
only worked on <a>
elements. So you'd have to do something like this to get it to work.
<style>
a#aks
{
width:100px;
height:100px;
display:block;
}
a#aks:link
{
background-image: url('http://dummyimage.com/100x100/000/fff');
}
a#aks:hover
{
background-image: url('http://dummyimage.com/100x100/eb00eb/fff');
}
</style>
<a href="#" id="aks"></a>
To put in layman’s term :
without xmlns:android=”http://schemas.android.com/apk/res/android” android related tags wont be recognized in the xml document of our layout.
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
I use this
var e = document.getElementById('ticket_category_clone').value;
Notice that you don't need the '#' character in javascript.
function check () {
var str = document.getElementById('ticket_category_clone').value;
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);?
As mentioned by few users, below code can help find all the fields in a given class.
TestClass testObject= new TestClass().getClass();
Method[] methods = testObject.getMethods();
for (Method method:methods)
{
String name=method.getName();
if(name.startsWith("get"))
{
System.out.println(name.substring(3));
}else if(name.startsWith("is"))
{
System.out.println(name.substring(2));
}
}
However a more interesting approach is below:
With the help of Jackson library, I was able to find all class properties of type String/integer/double, and respective values in a Map class. (without using reflections api!)
TestClass testObject = new TestClass();
com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper();
Map<String,Object> props = m.convertValue(testObject, Map.class);
for(Map.Entry<String, Object> entry : props.entrySet()){
if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
}
To add on to KaZ answer, Whenever I am making a QML application I tend to add this to the main c++
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QStandardPaths>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// get the applications dir path and expose it to QML
QUrl appPath(QString("%1").arg(app.applicationDirPath()));
engine.rootContext()->setContextProperty("appPath", appPath);
// Get the QStandardPaths home location and expose it to QML
QUrl userPath;
const QStringList usersLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
if (usersLocation.isEmpty())
userPath = appPath.resolved(QUrl("/home/"));
else
userPath = QString("%1").arg(usersLocation.first());
engine.rootContext()->setContextProperty("userPath", userPath);
QUrl imagePath;
const QStringList picturesLocation = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
if (picturesLocation.isEmpty())
imagePath = appPath.resolved(QUrl("images"));
else
imagePath = QString("%1").arg(picturesLocation.first());
engine.rootContext()->setContextProperty("imagePath", imagePath);
QUrl videoPath;
const QStringList moviesLocation = QStandardPaths::standardLocations(QStandardPaths::MoviesLocation);
if (moviesLocation.isEmpty())
videoPath = appPath.resolved(QUrl("./"));
else
videoPath = QString("%1").arg(moviesLocation.first());
engine.rootContext()->setContextProperty("videoPath", videoPath);
QUrl homePath;
const QStringList homesLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
if (homesLocation.isEmpty())
homePath = appPath.resolved(QUrl("/"));
else
homePath = QString("%1").arg(homesLocation.first());
engine.rootContext()->setContextProperty("homePath", homePath);
QUrl desktopPath;
const QStringList desktopsLocation = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
if (desktopsLocation.isEmpty())
desktopPath = appPath.resolved(QUrl("/"));
else
desktopPath = QString("%1").arg(desktopsLocation.first());
engine.rootContext()->setContextProperty("desktopPath", desktopPath);
QUrl docPath;
const QStringList docsLocation = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
if (docsLocation.isEmpty())
docPath = appPath.resolved(QUrl("/"));
else
docPath = QString("%1").arg(docsLocation.first());
engine.rootContext()->setContextProperty("docPath", docPath);
QUrl tempPath;
const QStringList tempsLocation = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
if (tempsLocation.isEmpty())
tempPath = appPath.resolved(QUrl("/"));
else
tempPath = QString("%1").arg(tempsLocation.first());
engine.rootContext()->setContextProperty("tempPath", tempPath);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
Using it in QML
....
........
............
Text{
text:"This is the applications path: " + appPath
+ "\nThis is the users home directory: " + homePath
+ "\nThis is the Desktop path: " desktopPath;
}
Maven is not designed to work that way, but a workaround exists to achieve this goal (maybe with side effects, you will have to give a try). The trick is to tell the child project to find its parent via its relative path rather than its pure maven coordinates, and in addition to externalize the version number in a property :
<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>${global.version}</version>
<packaging>pom</packaging>
<properties>
<!-- Unique entry point for version number management -->
<global.version>0.1-SNAPSHOT</global.version>
</properties>
<parent>
<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>${global.version}</version>
<relativePath>..</relativePath>
</parent>
<groupId>com.dummy.bla.sub</groupId>
<artifactId>kid</artifactId>
I used that trick for a while for one of my project, with no specific problem, except the fact that maven logs a lot of warnings at the beginning of the build, which is not very elegant.
Seems maven 3.0.4 does not allow such a configuration anymore.
When you need an outer join the second syntax is not always required:
Oracle:
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x(+)
MSSQLServer (although it's been deprecated in 2000 version)/Sybase:
SELECT a.foo, b.foo
FROM a, b
WHERE a.x *= b.x
But returning to your question. I don't know the answer, but it is probably related to the fact that a join is more natural (syntactically, at least) than adding an expression to a where clause when you are doing exactly that: joining.
Adding
onClick={this.delta.bind(this)}
will solve the problem . this error comes when we try to call the function of ES6 class , So we need to bind the method.
You can turn off foreign key checks:
SET FOREIGN_KEY_CHECKS = 0;
/* DO WHAT YOU NEED HERE */
SET FOREIGN_KEY_CHECKS = 1;
Please make sure to NOT use this on production and have a backup.
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
So you can use:
myvar = getURLParameter('myvar');
Have you tried .innerText
or .value
instead of .innerHTML
?
sklearn >= 0.22.0
sklearn.metrics
has a mean_squared_error
function with a squared
kwarg (defaults to True
). Setting squared
to False
will return the RMSE.
from sklearn.metrics import mean_squared_error
rms = mean_squared_error(y_actual, y_predicted, squared=False)
sklearn < 0.22.0
sklearn.metrics
has a mean_squared_error
function. The RMSE is just the square root of whatever it returns.
from sklearn.metrics import mean_squared_error
from math import sqrt
rms = sqrt(mean_squared_error(y_actual, y_predicted))
declare @iMonth int
declare @sYear varchar(4)
declare @sMonth varchar(2)
set @iMonth = 0
while @iMonth > -12
begin
set @sYear = year(DATEADD(month,@iMonth,GETDATE()))
set @sMonth = right('0'+cast(month(DATEADD(month,@iMonth,GETDATE())) as varchar(2)),2)
select @sYear + @sMonth
set @iMonth = @iMonth - 1
end
This is a mismatch between assemblies: a DLL referenced from an assembly doesn't have a method signature that's expected.
Clean the solution, rebuild everything, and try again.
Also, be careful if this is a reference to something that's in the GAC; it could be that something somewhere is pointing to an incorrect version. Make sure (through the Properties of each reference) that the correct version is chosen or that Specific Version is set false.
There should be templates already included in Visio 2007 for software architecture but you might want to check out Visio 2007 templates.
With rlang 0.4.0
we have curly-curly operators ({{}}
) which makes this very easy.
library(dplyr)
library(rlang)
iris1 <- tbl_df(iris)
multipetal <- function(df, n) {
varname <- paste("petal", n , sep=".")
mutate(df, {{varname}} := Petal.Width * n)
}
multipetal(iris1, 4)
# A tibble: 150 x 6
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species petal.4
# <dbl> <dbl> <dbl> <dbl> <fct> <dbl>
# 1 5.1 3.5 1.4 0.2 setosa 0.8
# 2 4.9 3 1.4 0.2 setosa 0.8
# 3 4.7 3.2 1.3 0.2 setosa 0.8
# 4 4.6 3.1 1.5 0.2 setosa 0.8
# 5 5 3.6 1.4 0.2 setosa 0.8
# 6 5.4 3.9 1.7 0.4 setosa 1.6
# 7 4.6 3.4 1.4 0.3 setosa 1.2
# 8 5 3.4 1.5 0.2 setosa 0.8
# 9 4.4 2.9 1.4 0.2 setosa 0.8
#10 4.9 3.1 1.5 0.1 setosa 0.4
# … with 140 more rows
We can also pass quoted/unquoted variable names to be assigned as column names.
multipetal <- function(df, name, n) {
mutate(df, {{name}} := Petal.Width * n)
}
multipetal(iris1, temp, 3)
# A tibble: 150 x 6
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species temp
# <dbl> <dbl> <dbl> <dbl> <fct> <dbl>
# 1 5.1 3.5 1.4 0.2 setosa 0.6
# 2 4.9 3 1.4 0.2 setosa 0.6
# 3 4.7 3.2 1.3 0.2 setosa 0.6
# 4 4.6 3.1 1.5 0.2 setosa 0.6
# 5 5 3.6 1.4 0.2 setosa 0.6
# 6 5.4 3.9 1.7 0.4 setosa 1.2
# 7 4.6 3.4 1.4 0.3 setosa 0.900
# 8 5 3.4 1.5 0.2 setosa 0.6
# 9 4.4 2.9 1.4 0.2 setosa 0.6
#10 4.9 3.1 1.5 0.1 setosa 0.3
# … with 140 more rows
It works the same with
multipetal(iris1, "temp", 3)
From angular's documentation,
ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit
onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude
The major difference between them is when used with ng-include.
<div ng-include="partialViewUrl" onload="myFunction()"></div>
In this case, myFunction is called everytime the partial view is loaded.
<div ng-include="partialViewUrl" ng-init="myFunction()"></div>
Whereas, in this case, myFunction is called only once when the parent view is loaded.
There is no difference. Both will work in the same way.
CSS background properties are used to define the background effects of an element.
CSS properties used for background effects:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
Background property includes all of this properties and you can just write them in one line.
You can check the User-Agent string. In JavaScript, that's really easy, it's just a property of the navigator object.
var useragent = navigator.userAgent;
You can check if the device if iPhone or Blackberry in JS with something like
var isIphone = !!agent.match(/iPhone/i),
isBlackberry = !!agent.match(/blackberry/i);
if isIphone is true you are accessing the site from an Iphone, if isBlackBerry you are accessing the site from a Blackberry.
You can use "UserAgent Switcher" plugin for firefox to test that.
If you are also interested, it may be worth it checking out my script "redirection_mobile.js" hosted on github here https://github.com/sebarmeli/JS-Redirection-Mobile-Site and you can read more details in one of my article here:
while (rs.next())
{
if (f.exists() && !f.isDirectory())
continue;
//proceed
}
gravity--Applies to its own view.
layout-gravity---Applies to view related to its parent.
You can issue the following query from the command line:
mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name LIKE "%dir"'
Output (on Linux):
+---------------------------+----------------------------+
| Variable_name | Value |
+---------------------------+----------------------------+
| basedir | /usr |
| character_sets_dir | /usr/share/mysql/charsets/ |
| datadir | /var/lib/mysql/ |
| innodb_data_home_dir | |
| innodb_log_group_home_dir | ./ |
| lc_messages_dir | /usr/share/mysql/ |
| plugin_dir | /usr/lib/mysql/plugin/ |
| slave_load_tmpdir | /tmp |
| tmpdir | /tmp |
+---------------------------+----------------------------+
Output (on macOS Sierra):
+---------------------------+-----------------------------------------------------------+
| Variable_name | Value |
+---------------------------+-----------------------------------------------------------+
| basedir | /usr/local/mysql-5.7.17-macos10.12-x86_64/ |
| character_sets_dir | /usr/local/mysql-5.7.17-macos10.12-x86_64/share/charsets/ |
| datadir | /usr/local/mysql/data/ |
| innodb_data_home_dir | |
| innodb_log_group_home_dir | ./ |
| innodb_tmpdir | |
| lc_messages_dir | /usr/local/mysql-5.7.17-macos10.12-x86_64/share/ |
| plugin_dir | /usr/local/mysql/lib/plugin/ |
| slave_load_tmpdir | /var/folders/zz/zyxvpxvq6csfxvn_n000009800002_/T/ |
| tmpdir | /var/folders/zz/zyxvpxvq6csfxvn_n000009800002_/T/ |
+---------------------------+-----------------------------------------------------------+
Or if you want only the data dir use:
mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"'
These commands work on Windows too, but you need to invert the single and double quotes.
Btw, when executing which mysql
in Linux as you told, you'll not get the installation directory on Linux. You'll only get the binary path, which is /usr/bin
on Linux, but you see the mysql installation is using multiple folders to store files.
If you need the value of datadir as output, and only that, without column headers etc, but you don't have a GNU environment (awk|grep|sed ...) then use the following command line:
mysql -s -N -uUSER -p information_schema -e 'SELECT Variable_Value FROM GLOBAL_VARIABLES WHERE Variable_Name = "datadir"'
The command will select the value only from mysql's internal information_schema
database and disables the tabular output and column headers.
Output on Linux:
/var/lib/mysql
You can do it using the same page on the action attribute: action='<yourpage>'
With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.
Private Sub Open_multiple_sub_pages_from_main_page()
Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True
' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"
' Wait while IE loading...
While IE.Busy
DoEvents
Wend
Set objCollection = IE.Document.getElementsByTagName("input")
i = 0
While i < objCollection.Length
If objCollection(i).Name = "txtUserName" Then
' Set text for search
objCollection(i).Value = "1234"
End If
If objCollection(i).Name = "txtPwd" Then
' Set text for search
objCollection(i).Value = "password"
End If
If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
Set objElement = objCollection(i)
End If
i = i + 1
Wend
objElement.Click ' click button to load page
' Wait while IE re-loading...
While IE.Busy
DoEvents
Wend
' Show IE
IE.Visible = True
Set Doc = IE.Document
Dim links, link
Dim j As Integer 'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n 'loop to go thru all "a" item so it loads next page
links(j).Click
While IE.Busy
DoEvents
Wend
'-------------Do stuff here: copy field value and paste in excel sheet. Will post another question for this------------------------
IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click 'save
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click 'close
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
j = j + 2
Wend
End Sub
If
should be if
. Your program should look like this:
answer = raw_input("Is the information correct? Enter Y for yes or N for no")
if answer.upper() == 'Y':
print("this will do the calculation")
else:
exit()
Note also that the indentation is important, because it marks a block in Python.
I think this might help you:
Here is the JSFiddle demo:
And here is the code:
var stIsIE = /*@cc_on!@*/ false;_x000D_
sorttable = {_x000D_
init: function() {_x000D_
if (arguments.callee.done) return;_x000D_
arguments.callee.done = true;_x000D_
if (_timer) clearInterval(_timer);_x000D_
if (!document.createElement || !document.getElementsByTagName) return;_x000D_
sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;_x000D_
forEach(document.getElementsByTagName('table'), function(table) {_x000D_
if (table.className.search(/\bsortable\b/) != -1) {_x000D_
sorttable.makeSortable(table);_x000D_
}_x000D_
});_x000D_
},_x000D_
makeSortable: function(table) {_x000D_
if (table.getElementsByTagName('thead').length == 0) {_x000D_
the = document.createElement('thead');_x000D_
the.appendChild(table.rows[0]);_x000D_
table.insertBefore(the, table.firstChild);_x000D_
}_x000D_
if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];_x000D_
if (table.tHead.rows.length != 1) return;_x000D_
sortbottomrows = [];_x000D_
for (var i = 0; i < table.rows.length; i++) {_x000D_
if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {_x000D_
sortbottomrows[sortbottomrows.length] = table.rows[i];_x000D_
}_x000D_
}_x000D_
if (sortbottomrows) {_x000D_
if (table.tFoot == null) {_x000D_
tfo = document.createElement('tfoot');_x000D_
table.appendChild(tfo);_x000D_
}_x000D_
for (var i = 0; i < sortbottomrows.length; i++) {_x000D_
tfo.appendChild(sortbottomrows[i]);_x000D_
}_x000D_
delete sortbottomrows;_x000D_
}_x000D_
headrow = table.tHead.rows[0].cells;_x000D_
for (var i = 0; i < headrow.length; i++) {_x000D_
if (!headrow[i].className.match(/\bsorttable_nosort\b/)) {_x000D_
mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);_x000D_
if (mtch) {_x000D_
override = mtch[1];_x000D_
}_x000D_
if (mtch && typeof sorttable["sort_" + override] == 'function') {_x000D_
headrow[i].sorttable_sortfunction = sorttable["sort_" + override];_x000D_
} else {_x000D_
headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);_x000D_
}_x000D_
headrow[i].sorttable_columnindex = i;_x000D_
headrow[i].sorttable_tbody = table.tBodies[0];_x000D_
dean_addEvent(headrow[i], "click", sorttable.innerSortFunction = function(e) {_x000D_
_x000D_
if (this.className.search(/\bsorttable_sorted\b/) != -1) {_x000D_
sorttable.reverse(this.sorttable_tbody);_x000D_
this.className = this.className.replace('sorttable_sorted',_x000D_
'sorttable_sorted_reverse');_x000D_
this.removeChild(document.getElementById('sorttable_sortfwdind'));_x000D_
sortrevind = document.createElement('span');_x000D_
sortrevind.id = "sorttable_sortrevind";_x000D_
sortrevind.innerHTML = stIsIE ? ' <font face="webdings">5</font>' : ' ▴';_x000D_
this.appendChild(sortrevind);_x000D_
return;_x000D_
}_x000D_
if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {_x000D_
sorttable.reverse(this.sorttable_tbody);_x000D_
this.className = this.className.replace('sorttable_sorted_reverse',_x000D_
'sorttable_sorted');_x000D_
this.removeChild(document.getElementById('sorttable_sortrevind'));_x000D_
sortfwdind = document.createElement('span');_x000D_
sortfwdind.id = "sorttable_sortfwdind";_x000D_
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';_x000D_
this.appendChild(sortfwdind);_x000D_
return;_x000D_
}_x000D_
theadrow = this.parentNode;_x000D_
forEach(theadrow.childNodes, function(cell) {_x000D_
if (cell.nodeType == 1) {_x000D_
cell.className = cell.className.replace('sorttable_sorted_reverse', '');_x000D_
cell.className = cell.className.replace('sorttable_sorted', '');_x000D_
}_x000D_
});_x000D_
sortfwdind = document.getElementById('sorttable_sortfwdind');_x000D_
if (sortfwdind) {_x000D_
sortfwdind.parentNode.removeChild(sortfwdind);_x000D_
}_x000D_
sortrevind = document.getElementById('sorttable_sortrevind');_x000D_
if (sortrevind) {_x000D_
sortrevind.parentNode.removeChild(sortrevind);_x000D_
}_x000D_
_x000D_
this.className += ' sorttable_sorted';_x000D_
sortfwdind = document.createElement('span');_x000D_
sortfwdind.id = "sorttable_sortfwdind";_x000D_
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';_x000D_
this.appendChild(sortfwdind);_x000D_
row_array = [];_x000D_
col = this.sorttable_columnindex;_x000D_
rows = this.sorttable_tbody.rows;_x000D_
for (var j = 0; j < rows.length; j++) {_x000D_
row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];_x000D_
}_x000D_
row_array.sort(this.sorttable_sortfunction);_x000D_
tb = this.sorttable_tbody;_x000D_
for (var j = 0; j < row_array.length; j++) {_x000D_
tb.appendChild(row_array[j][1]);_x000D_
}_x000D_
delete row_array;_x000D_
});_x000D_
}_x000D_
}_x000D_
},_x000D_
_x000D_
guessType: function(table, column) {_x000D_
sortfn = sorttable.sort_alpha;_x000D_
for (var i = 0; i < table.tBodies[0].rows.length; i++) {_x000D_
text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);_x000D_
if (text != '') {_x000D_
if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {_x000D_
return sorttable.sort_numeric;_x000D_
}_x000D_
possdate = text.match(sorttable.DATE_RE)_x000D_
if (possdate) {_x000D_
first = parseInt(possdate[1]);_x000D_
second = parseInt(possdate[2]);_x000D_
if (first > 12) {_x000D_
return sorttable.sort_ddmm;_x000D_
} else if (second > 12) {_x000D_
return sorttable.sort_mmdd;_x000D_
} else {_x000D_
sortfn = sorttable.sort_ddmm;_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
return sortfn;_x000D_
},_x000D_
getInnerText: function(node) {_x000D_
if (!node) return "";_x000D_
hasInputs = (typeof node.getElementsByTagName == 'function') &&_x000D_
node.getElementsByTagName('input').length;_x000D_
if (node.getAttribute("sorttable_customkey") != null) {_x000D_
return node.getAttribute("sorttable_customkey");_x000D_
} else if (typeof node.textContent != 'undefined' && !hasInputs) {_x000D_
return node.textContent.replace(/^\s+|\s+$/g, '');_x000D_
} else if (typeof node.innerText != 'undefined' && !hasInputs) {_x000D_
return node.innerText.replace(/^\s+|\s+$/g, '');_x000D_
} else if (typeof node.text != 'undefined' && !hasInputs) {_x000D_
return node.text.replace(/^\s+|\s+$/g, '');_x000D_
} else {_x000D_
switch (node.nodeType) {_x000D_
case 3:_x000D_
if (node.nodeName.toLowerCase() == 'input') {_x000D_
return node.value.replace(/^\s+|\s+$/g, '');_x000D_
}_x000D_
case 4:_x000D_
return node.nodeValue.replace(/^\s+|\s+$/g, '');_x000D_
break;_x000D_
case 1:_x000D_
case 11:_x000D_
var innerText = '';_x000D_
for (var i = 0; i < node.childNodes.length; i++) {_x000D_
innerText += sorttable.getInnerText(node.childNodes[i]);_x000D_
}_x000D_
return innerText.replace(/^\s+|\s+$/g, '');_x000D_
break;_x000D_
default:_x000D_
return '';_x000D_
}_x000D_
}_x000D_
},_x000D_
reverse: function(tbody) {_x000D_
// reverse the rows in a tbody_x000D_
newrows = [];_x000D_
for (var i = 0; i < tbody.rows.length; i++) {_x000D_
newrows[newrows.length] = tbody.rows[i];_x000D_
}_x000D_
for (var i = newrows.length - 1; i >= 0; i--) {_x000D_
tbody.appendChild(newrows[i]);_x000D_
}_x000D_
delete newrows;_x000D_
},_x000D_
sort_numeric: function(a, b) {_x000D_
aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));_x000D_
if (isNaN(aa)) aa = 0;_x000D_
bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));_x000D_
if (isNaN(bb)) bb = 0;_x000D_
return aa - bb;_x000D_
},_x000D_
sort_alpha: function(a, b) {_x000D_
if (a[0] == b[0]) return 0;_x000D_
if (a[0] < b[0]) return -1;_x000D_
return 1;_x000D_
},_x000D_
sort_ddmm: function(a, b) {_x000D_
mtch = a[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
m = mtch[2];_x000D_
d = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt1 = y + m + d;_x000D_
mtch = b[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
m = mtch[2];_x000D_
d = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt2 = y + m + d;_x000D_
if (dt1 == dt2) return 0;_x000D_
if (dt1 < dt2) return -1;_x000D_
return 1;_x000D_
},_x000D_
sort_mmdd: function(a, b) {_x000D_
mtch = a[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
d = mtch[2];_x000D_
m = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt1 = y + m + d;_x000D_
mtch = b[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
d = mtch[2];_x000D_
m = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt2 = y + m + d;_x000D_
if (dt1 == dt2) return 0;_x000D_
if (dt1 < dt2) return -1;_x000D_
return 1;_x000D_
},_x000D_
shaker_sort: function(list, comp_func) {_x000D_
var b = 0;_x000D_
var t = list.length - 1;_x000D_
var swap = true;_x000D_
while (swap) {_x000D_
swap = false;_x000D_
for (var i = b; i < t; ++i) {_x000D_
if (comp_func(list[i], list[i + 1]) > 0) {_x000D_
var q = list[i];_x000D_
list[i] = list[i + 1];_x000D_
list[i + 1] = q;_x000D_
swap = true;_x000D_
}_x000D_
}_x000D_
t--;_x000D_
_x000D_
if (!swap) break;_x000D_
_x000D_
for (var i = t; i > b; --i) {_x000D_
if (comp_func(list[i], list[i - 1]) < 0) {_x000D_
var q = list[i];_x000D_
list[i] = list[i - 1];_x000D_
list[i - 1] = q;_x000D_
swap = true;_x000D_
}_x000D_
}_x000D_
b++;_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
if (document.addEventListener) {_x000D_
document.addEventListener("DOMContentLoaded", sorttable.init, false);_x000D_
}_x000D_
/* for Internet Explorer */_x000D_
/*@cc_on @*/_x000D_
/*@if (@_win32)_x000D_
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");_x000D_
var script = document.getElementById("__ie_onload");_x000D_
script.onreadystatechange = function() {_x000D_
if (this.readyState == "complete") {_x000D_
sorttable.init(); // call the onload handler_x000D_
}_x000D_
};_x000D_
/*@end @*/_x000D_
/* for Safari */_x000D_
if (/WebKit/i.test(navigator.userAgent)) { // sniff_x000D_
var _timer = setInterval(function() {_x000D_
if (/loaded|complete/.test(document.readyState)) {_x000D_
sorttable.init(); // call the onload handler_x000D_
}_x000D_
}, 10);_x000D_
}_x000D_
/* for other browsers */_x000D_
window.onload = sorttable.init;_x000D_
_x000D_
function dean_addEvent(element, type, handler) {_x000D_
if (element.addEventListener) {_x000D_
element.addEventListener(type, handler, false);_x000D_
} else {_x000D_
if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;_x000D_
if (!element.events) element.events = {};_x000D_
var handlers = element.events[type];_x000D_
if (!handlers) {_x000D_
handlers = element.events[type] = {};_x000D_
if (element["on" + type]) {_x000D_
handlers[0] = element["on" + type];_x000D_
}_x000D_
}_x000D_
handlers[handler.$$guid] = handler;_x000D_
element["on" + type] = handleEvent;_x000D_
}_x000D_
};_x000D_
dean_addEvent.guid = 1;_x000D_
_x000D_
function removeEvent(element, type, handler) {_x000D_
if (element.removeEventListener) {_x000D_
element.removeEventListener(type, handler, false);_x000D_
} else {_x000D_
if (element.events && element.events[type]) {_x000D_
delete element.events[type][handler.$$guid];_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
function handleEvent(event) {_x000D_
var returnValue = true;_x000D_
event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);_x000D_
var handlers = this.events[event.type];_x000D_
for (var i in handlers) {_x000D_
this.$$handleEvent = handlers[i];_x000D_
if (this.$$handleEvent(event) === false) {_x000D_
returnValue = false;_x000D_
}_x000D_
}_x000D_
return returnValue;_x000D_
};_x000D_
_x000D_
function fixEvent(event) {_x000D_
event.preventDefault = fixEvent.preventDefault;_x000D_
event.stopPropagation = fixEvent.stopPropagation;_x000D_
return event;_x000D_
};_x000D_
fixEvent.preventDefault = function() {_x000D_
this.returnValue = false;_x000D_
};_x000D_
fixEvent.stopPropagation = function() {_x000D_
this.cancelBubble = true;_x000D_
}_x000D_
if (!Array.forEach) {_x000D_
Array.forEach = function(array, block, context) {_x000D_
for (var i = 0; i < array.length; i++) {_x000D_
block.call(context, array[i], i, array);_x000D_
}_x000D_
};_x000D_
}_x000D_
Function.prototype.forEach = function(object, block, context) {_x000D_
for (var key in object) {_x000D_
if (typeof this.prototype[key] == "undefined") {_x000D_
block.call(context, object[key], key, object);_x000D_
}_x000D_
}_x000D_
};_x000D_
String.forEach = function(string, block, context) {_x000D_
Array.forEach(string.split(""), function(chr, index) {_x000D_
block.call(context, chr, index, string);_x000D_
});_x000D_
};_x000D_
var forEach = function(object, block, context) {_x000D_
if (object) {_x000D_
var resolve = Object;_x000D_
if (object instanceof Function) {_x000D_
resolve = Function;_x000D_
} else if (object.forEach instanceof Function) {_x000D_
object.forEach(block, context);_x000D_
return;_x000D_
} else if (typeof object == "string") {_x000D_
resolve = String;_x000D_
} else if (typeof object.length == "number") {_x000D_
resolve = Array;_x000D_
}_x000D_
resolve.forEach(object, block, context);_x000D_
}_x000D_
}
_x000D_
table.sortable thead {_x000D_
background-color: #eee;_x000D_
color: #666666;_x000D_
font-weight: bold;_x000D_
cursor: default;_x000D_
}
_x000D_
<table class="sortable">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>S.L.</th>_x000D_
<th>name</th>_x000D_
<th>Goal</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>Ronaldo</td>_x000D_
<td>120</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>Messi</td>_x000D_
<td>66</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>Ribery</td>_x000D_
<td>10</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>Bale</td>_x000D_
<td>22</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
JS is used here without any other JQuery Plugin.
You want the Thread.Join()
method, or one of its overloads.
This is how I was able to trigger a button click when the page loads.
<li ng-repeat="a in array">
<a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
{{a.name}}
</a>
</li>
A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.
angular
.module("myApp")
.directive('onLoadClicker', function ($timeout) {
return {
restrict: 'A',
scope: {
index: '=index'
},
link: function($scope, iElm) {
if ($scope.index == 0) {
$timeout(function() {
iElm.triggerHandler('click');
}, 0);
}
}
};
});
This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click();
Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.
Do a quick 'record macro' to see the color number associated with the color you're looking for (yellow highlight is 65535). Then erase the code and put
Sub Name()
Selection.Interior.Color = 65535 '(your number may be different depending on the above)
End Sub
Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);
customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));
Here's an alternative following the last answer
declare @t tinyint,@v tinyint
set @t=23
set @v=232
Select replace(str(@t,4),' ','0'),replace(str(@t,5),' ','0')
This will work on any number and by varying the length of the str()
function you can stipulate how many leading zeros you require. Provided of course that your string length is always >= maximum number of digits your number type can hold.
You are not the first one to think about a "revision number" in Git, but 'wc
' is quite dangerous, since commit can be erased or squashed, and the history revisited.
The "revision number" was especially important for Subversion since it was needed in case of merge (SVN1.5 and 1.6 have improved on that front).
You could end up with a pre-commit hook which would include a revision number in the comment, with an algorithm not involving looking up the all history of a branch to determine the correct number.
Bazaar actually came up with such an algorithm , and it may be a good starting point for what you want to do.
(As Bombe's answer points out, Git has actually an algorithm of its own, based on the latest tag, plus the number of commits, plus a bit of an SHA-1 key). You should see (and upvote) his answer if it works for you.
To illustrate Aaron's idea, you can also append the Git commit hash into an application’s "info" file you are distributing with your application.
That way, the about box would look like:
The applicative number is part of the commit, but the 'application’s "info" file' is generated during the packaging process, effectively linking an applicative build number to a technical revision id.
var test = $('input[name="testing"]:hidden');
test.val('work!');
I am using Red-Gate's software: http://www.red-gate.com
You can't extend Enum
as it's a static class. You can only extend instances of a type. With this in mind, you're going to have to create a static method yourself to do this; the following should work when combined with your existing method GetDescription
:
public static class EnumHelper
{
public static T GetEnumFromString<T>(string value)
{
if (Enum.IsDefined(typeof(T), value))
{
return (T)Enum.Parse(typeof(T), value, true);
}
else
{
string[] enumNames = Enum.GetNames(typeof(T));
foreach (string enumName in enumNames)
{
object e = Enum.Parse(typeof(T), enumName);
if (value == GetDescription((Enum)e))
{
return (T)e;
}
}
}
throw new ArgumentException("The value '" + value
+ "' does not match a valid enum name or description.");
}
}
And the usage of it would be something like this:
Animal giantPanda = EnumHelper.GetEnumFromString<Animal>("Giant Panda");
ASCII to int:
ord('a')
gives 97
And back to a string:
str(unichr(97))
chr(97)
gives 'a'
Update: Try this
inNumber = [32, 12.5, 'e', 82, 52, 92, '1224.5', '12,53',
10000.000, '10,000459',
'This is a sentance, with comma number 1 and dot.', '121.124']
try:
def find_float(num):
num = num.split('.')
if num[-1] is not None and num[-1].isdigit():
return True
else:
return False
for i in inNumber:
i = str(i).replace(',', '.')
if '.' in i and find_float(i):
print('This is float', i)
elif i.isnumeric():
print('This is an integer', i)
else:
print('This is not a number ?', i)
except Exception as err:
print(err)
You could go a step further and break into the puppet code using a breakpoint.
http://logicminds.github.io/blog/2017/04/25/break-into-your-puppet-code/
This would only work with puppet apply or using a rspec test. Or you can manually type your code into the debugger console. Note: puppet still needs to know where your module code is at if you haven't set already.
gem install puppet puppet-debugger
puppet module install nwops/debug
cat > test.pp <<'EOF'
$var1 = 'test'
debug::break()
EOF
Should show something like.
puppet apply test.pp
From file: test.pp
1: $var1 = 'test'
2: # add 'debug::break()' where you want to stop in your code
=> 3: debug::break()
1:>> $var1
=> "test"
2:>>
My guess is that you are trying to restore in lower versions which wont work
This is a specific issue for Windows Vista, 7, 8 (and presumably newer).
User Account Control (UAC) is a feature in Windows that can help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of your user account.
This is applied mostly to C:\Program Files. You may have noticed sometimes, that some applications can see files in C:\Program Files that does not exist there. You know why? Windows now tend to have "C:\Program Files" folder customized for every user. For example, old applications store config files (like .ini) in the same folder where the executable files are stored. In the good old days all users had the same configurations for such apps. In nowadays Windows stores configs in the special folder tied to the user account. Thus, now different users may have different configs while application still think that config files are in the same folder with the executables.
XAMPP does not like to have different config for different users. In fact it is not a config file for XAMPP, it is folders where you keep your projects and databases. The idea of XAMPP is to make projects same for all users. This is a source of a conflict with Windows.
All you need is to avoid installing XAMPP into C:\Program Files. Thus XAMPP will always use the original files for all users and there would be no confusion.
I recommend to install XAMPP into the special folder in root directory like in C:\XAMPP. But before you choose the folder you need to click on this warning message.
Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :
- offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.
On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :
- clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.
ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:
- scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.
From wikipedia:
In computer science, an array data structure or simply array is a data structure consisting of a collection of elements (values or variables), each identified by one or more integer indices, stored so that the address of each element can be computed from its index tuple by a simple mathematical formula.
So when you say byte array, you're referring to an array of some defined length (e.g. number of elements) that contains a collection of byte (8 bits) sized elements.
In C# a byte array could look like:
byte[] bytes = { 3, 10, 8, 25 };
The sample above defines an array of 4 elements, where each element can be up to a Byte in length.
You can also try lodash:
const isNumeric = number =>
_.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))
You're doing nothing wrong! You've changed the directory, but only within the subshell that runs the script.
You can run the script in your current process with the "dot" command:
. proj
But I'd prefer Greg's suggestion to use an alias in this simple case.
You could have used DISTINCT
or just remove the PARTITION BY
portions and use GROUP BY
:
SELECT BrandId
,SUM(ICount)
,TotalICount = SUM(ICount) OVER ()
,Percentage = SUM(ICount) OVER ()*1.0 / SUM(ICount)
FROM Table
WHERE DateId = 20130618
GROUP BY BrandID
Not sure why you are dividing the total by the count per BrandID, if that's a mistake and you want percent of total then reverse those bits above to:
SELECT BrandId
,SUM(ICount)
,TotalICount = SUM(ICount) OVER ()
,Percentage = SUM(ICount)*1.0 / SUM(ICount) OVER ()
FROM Table
WHERE DateId = 20130618
GROUP BY BrandID
/* Portrait and Landscape */
@media only screen
and (min-device-width: 375px)
and (max-device-width: 812px)
and (-webkit-min-device-pixel-ratio: 3)
/* uncomment for only portrait: */
/* and (orientation: portrait) */
/* uncomment for only landscape: */
/* and (orientation: landscape) */ {
}
/* Portrait and Landscape */
@media only screen
and (min-device-width: 414px)
and (max-device-width: 736px)
and (-webkit-min-device-pixel-ratio: 3)
/* uncomment for only portrait: */
/* and (orientation: portrait) */
/* uncomment for only landscape: */
/* and (orientation: landscape) */ {
}
/* Portrait and Landscape */
@media only screen
and (min-device-width: 375px)
and (max-device-width: 667px)
and (-webkit-min-device-pixel-ratio: 2)
/* uncomment for only portrait: */
/* and (orientation: portrait) */
/* uncomment for only landscape: */
/* and (orientation: landscape) */ {
}
Well, Pavel was close, but there's even a more simple and elegant solution to initialize a sequential container from a c style array.
In your case:
w_ (array, std::end(array))
You can give variable names as project files. For instance in you plugin configuration give only one tag as below:-
<projectFile>${projectName}</projectFile>
Then on command line you can pass the project name as parameter:-
mvn [your-command] -DprojectName=[name of project]
This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with sendto
command.
clientSocket.sendto(message.encode(),(serverName, serverPort))
Similarly you would use .decode()
to receive the data on the UDP server side, if you want to print it exactly as it was sent.