The largest number that can be represented by an n digit number in base b is bn - 1. Hence, the largest number that can be represented in N binary digits is 2N - 1. We need the smallest integer N such that:
2N - 1 = bn - 1
? 2N = bn
Taking the base 2 logarithm of both sides of the last expression gives:
log2 2N = log2 bn
? N = log2 bn
? N = log bn / log 2
Since we want the smallest integer N that satisfies the last relation, to find N, find log bn / log 2 and take the ceiling.
In the last expression, any base is fine for the logarithms, so long as both bases are the same. It is convenient here, since we are interested in the case where b = 10, to use base 10 logarithms taking advantage of log1010n == n.
For n = 3:
N = ?3 / log10 2? = 10
For n = 4:
N = ?4 / log10 2? = 14
For n = 6:
N = ?6 / log10 2? = 20
And in general, for n decimal digits:
N = ?n / log10 2?
Had a similar problem, where I had to set the form back to pristine, but also to untouched, since $invalid and $error were both used to show error messages. Only using setPristine() was not enough to clear the error messages.
I solved it by using setPristine() and setUntouched(). (See Angular's documentation: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController)
So, in my controller, I used:
$scope.form.setPristine();
$scope.form.setUntouched();
These two functions reset the complete form to $pristine and back to $untouched, so that all error messages were cleared.
I spent more than a week to convert the whole project and came to a solution below:
First, de-integrate the cocopods dependency from the project and then start converting the project to the latest swift version.
Go to Project Directory in the Terminal and Type:
pod deintegrate
This will de-integrate cocopods from the project and No traces of CocoaPods will be left in the project. But at the same time, it won't delete the xcworkspace and podfiles. It's ok if they are present.
Now you have to open xcodeproj(not xcworkspace) and you will get lots of errors because you have called cocoapods dependency methods in your main projects.
So to remove those errors you have two options:
Once all the errors get removed you can convert the code to the latest swift version.
Sometimes if you are getting weird errors then try cleaning derived data and try again.
Unity also Provide its own Source version control. before unity5 it was unityAsset Server but now its depreciated. and launch a new SVN control system called unity collaborate.but the main problem using unity and any SVN is committing and merging scene . but Non of svn give us way to solve this kind of conflicts or merge scene . so depend upon you which SVN you are familiar with . I am using SmartSVN tool on Mac . and turtle on windows .
I got the same error and this is what helped me:
$ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
$launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
$mysql -uroot
mysql>
var result = Regex.Replace("123- abcd33", @"[0-9\-]", string.Empty);
This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container
has display: flex;
and flex-direction: column;
, while the columns have flex: 3;
and flex: 2;
(where "One value, unitless number" determines the flex-grow
property) per MDN flex
docs.
#Container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
flex: 3;_x000D_
background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
<div class="Content">_x000D_
<div id="Detail"></div>_x000D_
<div id="ThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
What you are trying to achieve is equivalent to
interface Event {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.
If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:
PARAMETERS SomeParam Text(10);
SELECT Field FROM Table
WHERE OtherField=SomeParam
You can also say:
CREATE PROCEDURE ProcedureName
(Parameter1 datatype, Parameter2 datatype) AS
SQLStatement
From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs
Note that the procedure contains only one statement.
self::staticMethod();
Unless you have more style sheets than that, you've messed up your break points:
#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)
The 3rd media query is probably meant to be min-width: 901px
. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.
Edit for updated question:
(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)
Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width
for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:
(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)
Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.
Free for non-commercial use.
Includes plugins for jQuery, Node.js, WordPress, Drupal, Joomla, Microsoft TypeScript, etc...
Some screenshots of some of the demos:
If you are using Sql Server 2008 or better, you can use something called a Table-Valued Parameter (TVP) instead of serializing & deserializing your list data every time you want to pass it to a stored procedure.
Let's start by creating a simple schema to serve as our playground:
CREATE DATABASE [TestbedDb]
GO
USE [TestbedDb]
GO
/* First, setup the sample program's account & credentials*/
CREATE LOGIN [testbedUser] WITH PASSWORD=N'µ×?
?S[°¿Q¥½q?_Ĭ¼Ð)3õļ%dv', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON
GO
CREATE USER [testbedUser] FOR LOGIN [testbedUser] WITH DEFAULT_SCHEMA=[dbo]
GO
EXEC sp_addrolemember N'db_owner', N'testbedUser'
GO
/* Now setup the schema */
CREATE TABLE dbo.Table1 ( t1Id INT NOT NULL PRIMARY KEY );
GO
INSERT INTO dbo.Table1 (t1Id)
VALUES
(1),
(2),
(3),
(4),
(5),
(6),
(7),
(8),
(9),
(10);
GO
With our schema and sample data in place, we are now ready to create our TVP stored procedure:
CREATE TYPE T1Ids AS Table (
t1Id INT
);
GO
CREATE PROCEDURE dbo.FindMatchingRowsInTable1( @Table1Ids AS T1Ids READONLY )
AS
BEGIN
SET NOCOUNT ON;
SELECT Table1.t1Id FROM dbo.Table1 AS Table1
JOIN @Table1Ids AS paramTable1Ids ON Table1.t1Id = paramTable1Ids.t1Id;
END
GO
With both our schema and API in place, we can call the TVP stored procedure from our program like so:
// Curry the TVP data
DataTable t1Ids = new DataTable( );
t1Ids.Columns.Add( "t1Id",
typeof( int ) );
int[] listOfIdsToFind = new[] {1, 5, 9};
foreach ( int id in listOfIdsToFind )
{
t1Ids.Rows.Add( id );
}
// Prepare the connection details
SqlConnection testbedConnection =
new SqlConnection(
@"Data Source=.\SQLExpress;Initial Catalog=TestbedDb;Persist Security Info=True;User ID=testbedUser;Password=letmein12;Connect Timeout=5" );
try
{
testbedConnection.Open( );
// Prepare a call to the stored procedure
SqlCommand findMatchingRowsInTable1 = new SqlCommand( "dbo.FindMatchingRowsInTable1",
testbedConnection );
findMatchingRowsInTable1.CommandType = CommandType.StoredProcedure;
// Curry up the TVP parameter
SqlParameter sqlParameter = new SqlParameter( "Table1Ids",
t1Ids );
findMatchingRowsInTable1.Parameters.Add( sqlParameter );
// Execute the stored procedure
SqlDataReader sqlDataReader = findMatchingRowsInTable1.ExecuteReader( );
while ( sqlDataReader.Read( ) )
{
Console.WriteLine( "Matching t1ID: {0}",
sqlDataReader[ "t1Id" ] );
}
}
catch ( Exception e )
{
Console.WriteLine( e.ToString( ) );
}
/* Output:
* Matching t1ID: 1
* Matching t1ID: 5
* Matching t1ID: 9
*/
There is probably a less painful way to do this using a more abstract API, such as Entity Framework. However, I do not have the time to see for myself at this time.
if you downloaded redis yourself (not apt-get install redis-server) and then edited the redis.conf with
the above suggestions, make sure your start redis with the config
like so: ./src/redis-server redis.conf
std::string s(v.begin(), v.end());
Where v is pretty much anything iterable. (Specifically begin() and end() must return InputIterators.)
Below is example to call synchronously but you can easily change to async by using await-sync:
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("login", "abc")
};
var content = new FormUrlEncodedContent(pairs);
var client = new HttpClient {BaseAddress = new Uri("http://localhost:6740")};
// call sync
var response = client.PostAsync("/api/membership/exist", content).Result;
if (response.IsSuccessStatusCode)
{
}
In answer to Shubham Patwa: This way, the page is "jumpy" soon as the class "navbar-fixed-top" applies. That's because the #mainnav is throwen in and out of the document's DOM flow. This can result in an ugly UX if the page has a "critical height", jumping between fixed and un-fixed #mainnav position.
I altered the code this way, which seems to work fine (not pixel-perfect, but fine):
$(document).ready(function() {
var navpos = $('#mainnav').offset();
var navheight = $('#mainnav').outerHeight();
$(window).bind('scroll', function() {
if ($(window).scrollTop() > navpos.top) {
$('#mainnav').addClass('navbar-fixed-top');
$('body').css('marginTop',navheight);
}
else {
$('#mainnav').removeClass('navbar-fixed-top');
$('body').css('marginTop','0');
}
});
You can create a configuration file named config
in your ~/.ssh
folder. It can contain:
Host aws
HostName *yourip*
User *youruser*
IdentityFile *idFile*
This will allow you to connect to machines like this
ssh aws
You can also use this direct command line to open the Advanced System Properties:
sysdm.cpl
Then go to the Advanced Tab -> Environment Variables
with open('target.txt','w') as out:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print("I'm going to write these to the file.")
out.write('{}\n{}\n{}\n'.format(line1,line2,line3))
Try writing all the errors to a file.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
Something like that.
Running nginx -t
through your commandline will issue out a test and append the output with the filepath to the configuration file (with either an error or success message).
For passing an object (including String) by reference in java, you might pass it as member of a surrounding adapter. A solution with a generic is here:
import java.io.Serializable;
public class ByRef<T extends Object> implements Serializable
{
private static final long serialVersionUID = 6310102145974374589L;
T v;
public ByRef(T v)
{
this.v = v;
}
public ByRef()
{
v = null;
}
public void set(T nv)
{
v = nv;
}
public T get()
{
return v;
}
// ------------------------------------------------------------------
static void fillString(ByRef<String> zText)
{
zText.set(zText.get() + "foo");
}
public static void main(String args[])
{
final ByRef<String> zText = new ByRef<String>(new String(""));
fillString(zText);
System.out.println(zText.get());
}
}
use below statement if safe_mode
is off
set_time_limit(0);
In order to clarify the question, I would rather categorize the usage of 'static' keyword in three different forms:
(A). variables
(B). functions
(C). member variables/functions of classes
the explanation follows below for each of the sub headings:
(A) 'static' keyword for variables
This one can be little tricky however if explained and understood properly, it's pretty straightforward.
To explain this, first it is really useful to know about the scope, duration and linkage of variables, without which things are always difficult to see through the murky concept of staic keyword
1. Scope : Determines where in the file, the variable is accessible. It can be of two types: (i) Local or Block Scope. (ii) Global Scope
2. Duration : Determines when a variable is created and destroyed. Again it's of two types: (i) Automatic Storage Duration (for variables having Local or Block scope). (ii) Static Storage Duration (for variables having Global Scope or local variables (in a function or a in a code block) with static specifier).
3. Linkage: Determines whether a variable can be accessed (or linked ) in another file. Again ( and luckily) it is of two types: (i) Internal Linkage (for variables having Block Scope and Global Scope/File Scope/Global Namespace scope) (ii) External Linkage (for variables having only for Global Scope/File Scope/Global Namespace Scope)
Let's refer an example below for better understanding of plain global and local variables (no local variables with static storage duration) :
//main file
#include <iostream>
int global_var1; //has global scope
const global_var2(1.618); //has global scope
int main()
{
//these variables are local to the block main.
//they have automatic duration, i.e, they are created when the main() is
// executed and destroyed, when main goes out of scope
int local_var1(23);
const double local_var2(3.14);
{
/* this is yet another block, all variables declared within this block are
have local scope limited within this block. */
// all variables declared within this block too have automatic duration, i.e,
/*they are created at the point of definition within this block,
and destroyed as soon as this block ends */
char block_char1;
int local_var1(32) //NOTE: this has been re-declared within the block,
//it shadows the local_var1 declared outside
std::cout << local_var1 <<"\n"; //prints 32
}//end of block
//local_var1 declared inside goes out of scope
std::cout << local_var1 << "\n"; //prints 23
global_var1 = 29; //global_var1 has been declared outside main (global scope)
std::cout << global_var1 << "\n"; //prints 29
std::cout << global_var2 << "\n"; //prints 1.618
return 0;
} //local_var1, local_var2 go out of scope as main ends
//global_var1, global_var2 go out of scope as the program terminates
//(in this case program ends with end of main, so both local and global
//variable go out of scope together
Now comes the concept of Linkage. When a global variable defined in one file is intended to be used in another file, the linkage of the variable plays an important role.
The Linkage of global variables is specified by the keywords: (i) static , and, (ii) extern
( Now you get the explanation )
static keyword can be applied to variables with local and global scope, and in both the cases, they mean different things. I will first explain the usage of 'static' keyword in variables with global scope ( where I also clarify the usage of keyword 'extern') and later the for those with local scope.
Global variables have static duration, meaning they don't go out of scope when a particular block of code (for e.g main() ) in which it is used ends . Depending upon the linkage, they can be either accessed only within the same file where they are declared (for static global variable), or outside the file even outside the file in which they are declared (extern type global variables)
In the case of a global variable having extern specifier, and if this variable is being accessed outside the file in which it has been initialized, it has to be forward declared in the file where it's being used, just like a function has to be forward declared if it's definition is in a file different from where it's being used.
In contrast, if the global variable has static keyword, it cannot be used in a file outside of which it has been declared.
(see example below for clarification)
eg:
//main2.cpp
static int global_var3 = 23; /*static global variable, cannot be
accessed in anyother file */
extern double global_var4 = 71; /*can be accessed outside this file linked to main2.cpp */
int main() { return 0; }
main3.cpp
//main3.cpp
#include <iostream>
int main()
{
extern int gloabl_var4; /*this variable refers to the gloabal_var4
defined in the main2.cpp file */
std::cout << global_var4 << "\n"; //prints 71;
return 0;
}
now any variable in c++ can be either a const or a non-const and for each 'const-ness' we get two case of default c++ linkage, in case none is specified:
(i) If a global variable is non-const, its linkage is extern by default, i.e, the non-const global variable can be accessed in another .cpp file by forward declaration using the extern keyword (in other words, non const global variables have external linkage ( with static duration of course)). Also usage of extern keyword in the original file where it has been defined is redundant. In this case to make a non-const global variable inaccessible to external file, use the specifier 'static' before the type of the variable.
(ii) If a global variable is const, its linkage is static by default, i.e a const global variable cannot be accessed in a file other than where it is defined, (in other words, const global variables have internal linkage (with static duration of course)). Also usage of static keyword to prevent a const global variable from being accessed in another file is redundant. Here, to make a const global variable have an external linkage, use the specifier 'extern' before the type of the variable
Here's a summary for global scope variables with various linkages
//globalVariables1.cpp
// defining uninitialized vairbles
int globalVar1; // uninitialized global variable with external linkage
static int globalVar2; // uninitialized global variable with internal linkage
const int globalVar3; // error, since const variables must be initialized upon declaration
const int globalVar4 = 23; //correct, but with static linkage (cannot be accessed outside the file where it has been declared*/
extern const double globalVar5 = 1.57; //this const variable ca be accessed outside the file where it has been declared
Next we investigate how the above global variables behave when accessed in a different file.
//using_globalVariables1.cpp (eg for the usage of global variables above)
// Forward declaration via extern keyword:
extern int globalVar1; // correct since globalVar1 is not a const or static
extern int globalVar2; //incorrect since globalVar2 has internal linkage
extern const int globalVar4; /* incorrect since globalVar4 has no extern
specifier, limited to internal linkage by
default (static specifier for const variables) */
extern const double globalVar5; /*correct since in the previous file, it
has extern specifier, no need to initialize the
const variable here, since it has already been
legitimately defined perviously */
Updates (August 2019) on static keyword for variables in local scope
This further can be subdivided in two categories :
(i) static keyword for variables within a function block, and (ii) static keyword for variables within a unnamed local block.
(i) static keyword for variables within a function block.
Earlier, I mentioned that variables with local scope have automatic duration, i.e they come to exist when the block is entered ( be it a normal block, be it a function block) and cease to exist when the block ends, long story short, variables with local scope have automatic duration and automatic duration variables (and objects) have no linkage meaning they are not visible outside the code block.
If static specifier is applied to a local variable within a function block, it changes the duration of the variable from automatic to static and its life time is the entire duration of the program which means it has a fixed memory location and its value is initialized only once prior to program start up as mentioned in cpp reference(initialization should not be confused with assignment)
lets take a look at an example.
//localVarDemo1.cpp
int localNextID()
{
int tempID = 1; //tempID created here
return tempID++; //copy of tempID returned and tempID incremented to 2
} //tempID destroyed here, hence value of tempID lost
int newNextID()
{
static int newID = 0;//newID has static duration, with internal linkage
return newID++; //copy of newID returned and newID incremented by 1
} //newID doesn't get destroyed here :-)
int main()
{
int employeeID1 = localNextID(); //employeeID1 = 1
int employeeID2 = localNextID(); // employeeID2 = 1 again (not desired)
int employeeID3 = newNextID(); //employeeID3 = 0;
int employeeID4 = newNextID(); //employeeID4 = 1;
int employeeID5 = newNextID(); //employeeID5 = 2;
return 0;
}
Looking at the above criterion for static local variables and static global variables, one might be tempted to ask, what the difference between them could be. While global variables are accessible at any point in within the code (in same as well as different translation unit depending upon the const-ness and extern-ness), a static variable defined within a function block is not directly accessible. The variable has to be returned by the function value or reference. Lets demonstrate this by an example:
//localVarDemo2.cpp
//static storage duration with global scope
//note this variable can be accessed from outside the file
//in a different compilation unit by using `extern` specifier
//which might not be desirable for certain use case.
static int globalId = 0;
int newNextID()
{
static int newID = 0;//newID has static duration, with internal linkage
return newID++; //copy of newID returned and newID incremented by 1
} //newID doesn't get destroyed here
int main()
{
//since globalId is accessible we use it directly
const int globalEmployee1Id = globalId++; //globalEmployeeId1 = 0;
const int globalEmployee2Id = globalId++; //globalEmployeeId1 = 1;
//const int employeeID1 = newID++; //this will lead to compilation error since newID++ is not accessible direcly.
int employeeID2 = newNextID(); //employeeID3 = 0;
int employeeID2 = newNextID(); //employeeID3 = 1;
return 0;
}
More explaination about choice of static global and static local variable could be found on this stackoverflow thread
(ii) static keyword for variables within a unnamed local block.
static variables within a local block (not a function block) cannot be accessed outside the block once the local block goes out of scope. No caveats to this rule.
//localVarDemo3.cpp
int main()
{
{
const static int static_local_scoped_variable {99};
}//static_local_scoped_variable goes out of scope
//the line below causes compilation error
//do_something is an arbitrary function
do_something(static_local_scoped_variable);
return 0;
}
C++11 introduced the keyword constexpr
which guarantees the evaluation of an expression at compile time and allows compiler to optimize the code. Now if the value of a static const variable within a scope is known at compile time, the code is optimized in a manner similar to the one with constexpr
. Here's a small example
I recommend readers also to look up the difference between constexpr
and static const
for variables in this stackoverflow thread.
this concludes my explanation for the static keyword applied to variables.
B. 'static' keyword used for functions
in terms of functions, the static keyword has a straightforward meaning. Here, it refers to linkage of the function Normally all functions declared within a cpp file have external linkage by default, i.e a function defined in one file can be used in another cpp file by forward declaration.
using a static keyword before the function declaration limits its linkage to internal , i.e a static function cannot be used within a file outside of its definition.
C. Staitc Keyword used for member variables and functions of classes
1. 'static' keyword for member variables of classes
I start directly with an example here
#include <iostream>
class DesignNumber
{
private:
static int m_designNum; //design number
int m_iteration; // number of iterations performed for the design
public:
DesignNumber() { } //default constructor
int getItrNum() //get the iteration number of design
{
m_iteration = m_designNum++;
return m_iteration;
}
static int m_anyNumber; //public static variable
};
int DesignNumber::m_designNum = 0; // starting with design id = 0
// note : no need of static keyword here
//causes compiler error if static keyword used
int DesignNumber::m_anyNumber = 99; /* initialization of inclass public
static member */
enter code here
int main()
{
DesignNumber firstDesign, secondDesign, thirdDesign;
std::cout << firstDesign.getItrNum() << "\n"; //prints 0
std::cout << secondDesign.getItrNum() << "\n"; //prints 1
std::cout << thirdDesign.getItrNum() << "\n"; //prints 2
std::cout << DesignNumber::m_anyNumber++ << "\n"; /* no object
associated with m_anyNumber */
std::cout << DesignNumber::m_anyNumber++ << "\n"; //prints 100
std::cout << DesignNumber::m_anyNumber++ << "\n"; //prints 101
return 0;
}
In this example, the static variable m_designNum retains its value and this single private member variable (because it's static) is shared b/w all the variables of the object type DesignNumber
Also like other member variables, static member variables of a class are not associated with any class object, which is demonstrated by the printing of anyNumber in the main function
const vs non-const static member variables in class
(i) non-const class static member variables In the previous example the static members (both public and private) were non constants. ISO standard forbids non-const static members to be initialized in the class. Hence as in previous example, they must be initalized after the class definition, with the caveat that the static keyword needs to be omitted
(ii) const-static member variables of class this is straightforward and goes with the convention of other const member variable initialization, i.e the const static member variables of a class can be initialized at the point of declaration and they can be initialized at the end of the class declaration with one caveat that the keyword const needs to be added to the static member when being initialized after the class definition.
I would however, recommend to initialize the const static member variables at the point of declaration. This goes with the standard C++ convention and makes the code look cleaner
for more examples on static member variables in a class look up the following link from learncpp.com http://www.learncpp.com/cpp-tutorial/811-static-member-variables/
2. 'static' keyword for member function of classes
Just like member variables of classes can ,be static, so can member functions of classes. Normal member functions of classes are always associated with a object of the class type. In contrast, static member functions of a class are not associated with any object of the class, i.e they have no *this pointer.
Secondly since the static member functions of the class have no *this pointer, they can be called using the class name and scope resolution operator in the main function (ClassName::functionName(); )
Thirdly static member functions of a class can only access static member variables of a class, since non-static member variables of a class must belong to a class object.
for more examples on static member functions in a class look up the following link from learncpp.com
http://www.learncpp.com/cpp-tutorial/812-static-member-functions/
If you have to wait there is a method presenceOfNestedElementLocatedBy
that takes the "parent" element and a locator, e.g. a By.xpath
:
WebElement subNode = new WebDriverWait(driver,10).until(
ExpectedConditions.presenceOfNestedElementLocatedBy(
divA, By.xpath(".//div/span")
)
);
This part from React v16 documentation will answer your question, read on about componentDidMount():
componentDidMount()
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().
As you see, componentDidMount is considered the best place and cycle to do the api call, also access the node, means by this time it's safe to do the call, update the view or whatever you could do when document is ready, if you are using jQuery, it should somehow remind you document.ready() function, where you could make sure everything is ready for whatever you want to do in your code...
In lightsail a virtual machine, SSD-based storage, data transfer, DNS management, and a static IP are all offered as a package. Whereas in normal case you provision an EC2 instance and then setup the rest of these things.Also Bandwidth included in the price, no security groups to set up, no need to worry about EBS volumes sizing.
Try this it is simple and short and it works with my code whereas I have the video full screen and behind other elements I simply use z-index -1;
<video autoplay loop id="myVideo">
Good afternoon, you could always use a little LINQ to get the selected list items and then do what you want with the results:
var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...
Just to complete, you could send 3 arguments like this:
objShell.Run "TestScript.vbs 42 ""an arg containing spaces"" foo"
Here is Bjarne Stroustrup's wordings,
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.
you can use sort() in C++ STL. sort() function Syntax :
sort(array_name, array_name+size)
So you use sort(v, v+2000);
The answers above are still using the old Python 3.4 style coroutines. Here is what you would write if you got Python 3.5+.
aiohttp
supports http proxy now
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'http://python.org',
'https://google.com',
'http://yifei.me'
]
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
tasks.append(fetch(session, url))
htmls = await asyncio.gather(*tasks)
for html in htmls:
print(html[:100])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
This is a comprehensive answer to this question. I have done this because this page is high on the Google search results and the answer does not go into enough detail. This post assumes that you are competent at using Visual Studio C# forms. This is based on VS2012.
Start by simply dragging a ContextMenuStrip onto the form. It will just put it into the top left corner where you can add your menu items and rename it as you see fit.
You will have to view code and enter in an event yourself on the form. Create a mouse down event for the item in question and then assign a right click event for it like so (I have called the ContextMenuStrip "rightClickMenuStrip"):
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
switch (e.Button)
{
case MouseButtons.Right:
{
rightClickMenuStrip.Show(this, new Point(e.X, e.Y));//places the menu at the pointer position
}
break;
}
}
Assign the event handler manually to the form.designer (you may need to add a "using" for System.Windows.Forms; You can just resolve it):
this.pictureBox1.MouseDown += new MouseEventHandler(this.pictureBox1_MouseDown);
All that is needed at this point is to simply double click each menu item and do the desired operations for each click event in the same way you would for any other button.
This is the basic code for this operation. You can obviously modify it to fit in with your coding practices.
REST is an architecture.
REST will give human-readable results.
REST is stateless.
REST services are easily cacheable.
SOAP is a protocol. It can run on top of JMS, FTP, and HTTP.
I've used this method (reported here )
export class AppComponent {
constructor() {
if(document.getElementById("testScript"))
document.getElementById("testScript").remove();
var testScript = document.createElement("script");
testScript.setAttribute("id", "testScript");
testScript.setAttribute("src", "assets/js/test.js");
document.body.appendChild(testScript);
}
}
it worked for me since I wanted to execute a javascript file AFTER THE COMPONENT RENDERED.
I've found that these errors sometimes are from lack of permissions when compiling a project - so I run as administrator to get it to work properly.
You can use
function echo(content) {
var e = document.createElement("p");
e.innerHTML = content;
document.currentScript.parentElement.replaceChild(document.currentScript, e);
}
which will replace the currently executing script who called the echo function with the text in the content argument.
Assuming that by "string" you're talking about std::string in C++, you might have a look at the Tokenizer package in Boost.
As the other answers have described, lit
and typedLit
are how to add constant columns to DataFrames. lit
is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.
You'll commonly be using lit
to create org.apache.spark.sql.Column
objects because that's the column type required by most of the org.apache.spark.sql.functions
.
Suppose you have a DataFrame with a some_date
DateType column and would like to add a column with the days between December 31, 2020 and some_date
.
Here's your DataFrame:
+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+
Here's how to calculate the days till the year end:
val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
.withColumn("days_till_yearend", diff)
.show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23| 99|
|2020-01-05| 361|
|2020-04-12| 263|
+----------+-----------------+
You could also use lit
to create a year_end
column and compute the days_till_yearend
like so:
import java.sql.Date
df
.withColumn("yearend", lit(Date.valueOf("2020-12-31")))
.withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
.show()
+----------+----------+-----------------+
| some_date| yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31| 99|
|2020-01-05|2020-12-31| 361|
|2020-04-12|2020-12-31| 263|
+----------+----------+-----------------+
Most of the time, you don't need to use lit
to append a constant column to a DataFrame. You just need to use lit
to convert a Scala type to a org.apache.spark.sql.Column
object because that's what's required by the function.
See the datediff
function signature:
As you can see, datediff
requires two Column arguments.
You need to create an extension of String and call this method
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.height)
}
You must send the width of your label
Option 1: Put this in your procedure to print 'comment' to stdout when it runs.
SELECT 'Comment';
Option 2: Put this in your procedure to print a variable with it to stdout:
declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);
This prints myvar is 5
to stdout when the procedure runs.
Option 3, Create a table with one text column called tmptable
, and push messages to it:
declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);
You could put the above in a stored procedure, so all you would have to write is this:
CALL log(concat('the value is', myvar));
Which saves a few keystrokes.
Option 4, Log messages to file
select "penguin" as log into outfile '/tmp/result.txt';
There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.
Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
Add to doc header:
\usepackage{ amssymb }
Then at the desired location add:
$ \blacksquare $
Standing on the shoulders of charles-clayton and @vikas-gautam, I added the string test which is needed if a column has strings as in OP.
return isNaN(a-b) ? (a === b) ? 0 : (a < b) ? -1 : 1 : a-b ;
The test isNaN(a-b)
determines if the strings cannot be coerced to numbers. If they can then the a-b
test is valid.
Note that sorting a column of mixed types will always give an entertaining result as the strict equality test (a === b)
will always return false.
See MDN here
This is the full script with Logger test - using Google Apps Script.
function testSort(){
function sortByCol(arr, colIndex){
arr.sort(sortFunction);
function sortFunction(a, b) {
a = a[colIndex];
b = b[colIndex];
return isNaN(a-b) ? (a === b) ? 0 : (a < b) ? -1 : 1 : a-b ; // test if text string - ie cannot be coerced to numbers.
// Note that sorting a column of mixed types will always give an entertaining result as the strict equality test will always return false
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
}
}
// Usage
var a = [ [12,'12', 'AAA'],
[12,'11', 'AAB'],
[58,'120', 'CCC'],
[28,'08', 'BBB'],
[18,'80', 'DDD'],
]
var arr1 = a.map(function (i){return i;}).sort(); // use map to ensure tests are not corrupted by a sort in-place.
Logger.log("Original unsorted:\n " + JSON.stringify(a));
Logger.log("Vanilla sort:\n " + JSON.stringify(arr1));
sortByCol(a, 0);
Logger.log("By col 0:\n " + JSON.stringify(a));
sortByCol(a, 1);
Logger.log("By col 1:\n " + JSON.stringify(a));
sortByCol(a, 2);
Logger.log("By col 2:\n " + JSON.stringify(a));
/* vanilla sort returns " [
[12,"11","AAB"],
[12,"12","AAA"],
[18,"80","DDD"],
[28,"08","BBB"],
[58,"120","CCC"]
]
if col 0 then returns "[
[12,'12',"AAA"],
[12,'11', 'AAB'],
[18,'80',"DDD"],
[28,'08',"BBB"],
[58,'120',"CCC"]
]"
if col 1 then returns "[
[28,'08',"BBB"],
[12,'11', 'AAB'],
[12,'12',"AAA"],
[18,'80',"DDD"],
[58,'120',"CCC"],
]"
if col 2 then returns "[
[12,'12',"AAA"],
[12,'11', 'AAB'],
[28,'08',"BBB"],
[58,'120',"CCC"],
[18,'80',"DDD"],
]"
*/
}
Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing:
...in VB.NET:
String.Join(",", CType(TargetArrayList.ToArray(Type.GetType("System.String")), String()))
...in C#
string.Join(",", (string[])TargetArrayList.ToArray(Type.GetType("System.String")))
The only "gotcha" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly.
EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up!
String.Join(",", TargetList.ToArray())
Try the notepad++ plugin JSMinNpp(Changed name to JSTool since 1.15)
Based on responses and comments below, the following was the simple solution for my issue and THIS WORKED. Now my app, Match4app, is fully compatible with latest iOS versions!
For Asp.Net core you better use
<partial name="_MyPartialView" model="MyModel" />
So for example
@foreach (var item in Model)
{
<partial name="_MyItemView" model="item" />
}
I Don't know what do you mean exactly, but technially speaking, this is not possible without a loop.
May be you mean using a LINQ, like for example:
list.Where(x=>x.Title == title)
It's worth mentioning that the iteration over is not skipped, but simply wrapped into the LINQ query.
Hope this helps.
EDIT
In other words if you really concerned about performance, keep coding the way you already doing. Otherwise choose LINQ for more concise and clear syntax.
Add to server.xml :
<Context docBase="c:/dirtoshare" path="/dir" />
Enable dir file listing parameter in web.xml :
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
Your have dropped the Project in your workspace, and then trying to import it, that's the problem.
This has two solutions:
1. More your project folder outside your workspace in some other location and then try.
2. Go to File ---> new Project ---> Select the existing project radio button ---> browse to the project folder in your workspace ---> finish
Assume D:\MyDirectory\MyWorkSpace - Path of your WorkSpace
Drop your project which you want to import in Eclipse in MyDirectory folder Not in MyWorkSpace, and try.
Set the background color of the src to none and allow transparencey.
[WITHIN SCR PAGE STYLE]
<style type="text/css">
body
{
background:none transparent;
}
</style>
[IFRAME]
<iframe src="#" allowtransparency="true">Error, iFrame failed to load.</iframe>
NOTE: I code my CSS a little different to how everyone else does.
I am not going to write the code but just the idea. How about to make a thread that print a number per second, and then another thread kill the first thread after 1000 seconds?
note: the first thread generate numbers by recursion.
To export data to csv/excel from Kibana follow the following steps:-
Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.
Click on caret symbol (^) which is present at the bottom of the visualization.
Then you will get an option of Export:Raw Formatted as the bottom of the page.
Please find below attached image showing Export option after clicking on caret symbol.
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
This is my function (based on this) to clean the dataset of nan
, Inf
, and missing cells (for skewed datasets):
import pandas as pd
def clean_dataset(df):
assert isinstance(df, pd.DataFrame), "df needs to be a pd.DataFrame"
df.dropna(inplace=True)
indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(1)
return df[indices_to_keep].astype(np.float64)
FWIW - Here's a directive I've used for a basic confirm/alert bootstrap modal, without the need for a <form>
(just switch out the jQuery click action for whatever you like, and add data-easy-dismiss
to your modal tag)
app.directive('easyDismiss', function() {
return {
restrict: 'A',
link: function ($scope, $element) {
var clickSubmit = function (e) {
if (e.which == 13) {
$element.find('[type="submit"]').click();
}
};
$element.on('show.bs.modal', function() {
$(document).on('keypress', clickSubmit);
});
$element.on('hide.bs.modal', function() {
$(document).off('keypress', clickSubmit);
});
}
};
});
You can always use the ( <condition> ? <value if true> : <value if false> )
syntax (it's called the ternary operator - thanks to Mark for remining me :) ).
If <condition>
is true, the statement would be evaluated as <value if true>
. If not, it would be evaluated as <value if false>
For instance:
$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";
This is the same as:
$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
echo "Fourteen is more than twelve";
}else{
echo "Fourteen is not more than twelve";
}
string name = "Paul Creasey";
if (name.contains(" ")) {
}
The how-to-prevent-xss has been asked several times. You will find a lot of information in StackOverflow. Also, OWASP website has an XSS prevention cheat sheet that you should go through.
On the libraries to use, OWASP's ESAPI library has a java flavour. You should try that out. Besides that, every framework that you use has some protection against XSS. Again, OWASP website has information on most popular frameworks, so I would recommend going through their site.
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
You don't need to use bi-directional association instead of your code, you have just to add CascaType.Remove as a property to ManyToOne annotation, then use @OnDelete(action = OnDeleteAction.CASCADE), it's works fine for me.
The other answers address the main thrust of the question, but just to comment on this part...
PS C:\> [array]$foo = @("bar") PS C:\> $foo -eq $null PS C:\>
How can "-eq $null" give no results? It's either $null or it's not.
It's confusing at first, but that is giving you the result of $foo -eq $null
, it's just that the result has no displayable representation.
Since $foo
holds an array, $foo -eq $null
means "return an array containing the elements of $foo
that are equal to $null
". Are there any elements of $foo
that are equal to $null
? No, so $foo -eq $null
should return an empty array. That's exactly what it does, the problem is that when an empty array is displayed at the console you see...nothing...
PS> @()
PS>
The array is still there, even if you can't see its elements...
PS> @().GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> @().Length
0
We can use similar commands to confirm that $foo -eq $null
is returning an array that we're not able to "see"...
PS> $foo -eq $null
PS> ($foo -eq $null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> ($foo -eq $null).Length
0
PS> ($foo -eq $null).GetValue(0)
Exception calling "GetValue" with "1" argument(s): "Index was outside the bounds of the array."
At line:1 char:1
+ ($foo -eq $null).GetValue(0)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IndexOutOfRangeException
Note that I am calling the Array.GetValue
method instead of using the indexer (i.e. ($foo -eq $null)[0]
) because the latter returns $null
for invalid indices and there's no way to distinguish them from a valid index that happens to contain $null
.
We see similar behavior if we test for $null
in/against an array that contains $null
elements...
PS> $bar = @($null)
PS> $bar -eq $null
PS> ($bar -eq $null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> ($bar -eq $null).Length
1
PS> ($bar -eq $null).GetValue(0)
PS> $null -eq ($bar -eq $null).GetValue(0)
True
PS> ($bar -eq $null).GetValue(0) -eq $null
True
PS> ($bar -eq $null).GetValue(1)
Exception calling "GetValue" with "1" argument(s): "Index was outside the bounds of the array."
At line:1 char:1
+ ($bar -eq $null).GetValue(1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IndexOutOfRangeException
In this case, $bar -eq $null
returns an array containing one element, $null
, which has no visual representation at the console...
PS> @($null)
PS> @($null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> @($null).Length
1
The XLSB format is also dedicated to the macros embeded in an hidden workbook file located in excel startup folder (XLSTART).
A quick & dirty test with a xlsm or xlsb in XLSTART folder:
Measure-Command { $x = New-Object -com Excel.Application ;$x.Visible = $True ; $x.Quit() }
0,89s with a xlsb (binary) versus 1,3s with the same content in xlsm format (xml in a zip file) ... :)
Primary key fields should be declared as not null (this is non standard as the definition of a primary key is that it must be unique and not null). But below is a good practice for all multi-column primary keys in any DBMS.
create table foo
(
fooint integer not null
,foobar string not null
,fooval real
,primary key (fooint, foobar)
)
;
You will have to use the fluent API to do this.
Try adding the following to your DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
If you want to cut the whitespaces before and behind the word, but keep the middle ones.
You could use:
word = ' Hello World '
stripped = word.strip()
print(stripped)
That's my workaround.
@property
def language(self):
return self._language
@language.setter
def language(self, value):
# WORKAROUND to get a "getter-only" behavior
# set the value only if the attribute does not exist
try:
if self.language == value:
pass
print("WARNING: Cannot set attribute \'language\'.")
except AttributeError:
self._language = value
You need to make it a generic method, like this:
public static T ConfigSetting<T>(string settingName)
{
return /* code to convert the setting to T... */
}
But the caller will have to specify the type they expect. You could then potentially use Convert.ChangeType
, assuming that all the relevant types are supported:
public static T ConfigSetting<T>(string settingName)
{
object value = ConfigurationManager.AppSettings[settingName];
return (T) Convert.ChangeType(value, typeof(T));
}
I'm not entirely convinced that all this is a good idea, mind you...
I had the same problem as you mentioned here above and my code was doing great all day yesterday.
I kept on programming this morning and when I opened my application (my file with an Auto_Open sub), I got the Run-time error '13' Type mismatch, I went on the web to find answers, I tried a lot of things, modifications and at one point I remembered that I read somewhere about "Ghost" data that stays in a cell even if we don't see it.
My code do only data transfer from one file I opened previously to another and Sum it. My code stopped at the third SheetTab (So it went right for the 2 previous SheetTab where the same code went without stopping) with the Type mismatch message. And it does that every time at the same SheetTab when I restart my code.
So I selected the cell where it stopped, manually entered 0,00 (Because the Type mismatch comes from a Summation variables declared in a DIM as Double) and copied that cell in all the subsequent cells where the same problem occurred. It solved the problem. Never had the message again. Nothing to do with my code but the "Ghost" or data from the past. It is like when you want to use the Control+End and Excel takes you where you had data once and deleted it. Had to "Save" and close the file when you wanted to use the Control+End to make sure Excel pointed you to the right cell.
This worked for me. Thank you Rody!
y="HELLO"
val=$(echo $y | tr '[:upper:]' '[:lower:]')
string="$val world"
one small modification, if you are using underscore next to the variable You need to encapsulate the variable name in {}.
string="${val}_world"
Yes, if it is .NET RegEx-engine. .Net engine supports finite state machine supplied with an external stack. see details
Practically speaking size_t
represents the number of bytes you can address. On most modern architectures for the last 10-15 years that has been 32 bits which has also been the size of a unsigned int. However we are moving to 64bit addressing while the uint
will most likely stay at 32bits (it's size is not guaranteed in the c++ standard). To make your code that depends on the memory size portable across architectures you should use a size_t
. For example things like array sizes should always use size_t
's. If you look at the standard containers the ::size()
always returns a size_t
.
Also note, visual studio has a compile option that can check for these types of errors called "Detect 64-bit Portability Issues".
I don't think there's a recommended order, as long as it compiles! What's annoying is when some headers require other headers to be included first... That's a problem with the headers themselves, not with the order of includes.
My personal preference is to go from local to global, each subsection in alphabetical order, i.e.:
My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #include
d without prerequisites (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
I think the easiest way (with jQuery) to check if checkbox is checked or NOT is:
if 'checked':
if ($(this).is(':checked')) {
// I'm checked let's do something
}
if NOT 'checked':
if (!$(this).is(':checked')) {
// I'm NOT checked let's do something
}
Run all Collection in a folder in parallel:
'use strict';
global.Promise = require('bluebird');
const path = require('path');
const newman = Promise.promisifyAll(require('newman'));
const fs = Promise.promisifyAll(require('fs'));
const environment = 'postman_environment.json';
const FOLDER = path.join(__dirname, 'Collections_Folder');
let files = fs.readdirSync(FOLDER);
files = files.map(file=> path.join(FOLDER, file))
console.log(files);
Promise.map(files, file => {
return newman.runAsync({
collection: file, // your collection
environment: path.join(__dirname, environment), //your env
reporters: ['cli']
});
}, {
concurrency: 2
});
json = File.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\" +download_file[0]);
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
it's easy with the id of the div container : (I didn't put the close button inside the <a>
because that's does work properly on all browser.
<div id="myDiv">
<button class="close" onclick="document.getElementById('myDiv').style.display='none'" >Close</button>
<a class="fragment" href="http://google.com">
<div>
<img src ="http://placehold.it/116x116" alt="some description"/>
<h3>the title will go here</h3>
<h4> www.myurlwill.com </h4>
<p class="text">
this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc
</p>
</div>
</a>
</div>
According to the source code of codeigniter, the function set
is defined as:
public function set($key, $value = '', $escape = TRUE)
{
$key = $this->_object_to_array($key);
if ( ! is_array($key))
{
$key = array($key => $value);
}
foreach ($key as $k => $v)
{
if ($escape === FALSE)
{
$this->ar_set[$this->_protect_identifiers($k)] = $v;
}
else
{
$this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
}
}
return $this;
}
Apparently, if $key
is an array, codeigniter will simply ignore the second parameter $value
, but the third parameter $escape
will still work throughout the iteration of $key
, so in this situation, the following codes work (using the chain method):
$this->db->set(array(
'name' => $name ,
'email' => $email,
'time' => 'NOW()'), '', FALSE)->insert('mytable');
However, this will unescape all the data, so you can break your data into two parts:
$this->db->set(array(
'name' => $name ,
'email' => $email))->set(array('time' => 'NOW()'), '', FALSE)->insert('mytable');
Hopefully, this will be of value to someone out there - I went through half a dozen stackoverflow posts trying to figure out relative imports similar to whats posted above here. I set up everything as suggested but I was still hitting ModuleNotFoundError: No module named 'my_module_name'
Since I was just developing locally and playing around, I hadn't created/run a setup.py
file. I also hadn't apparently set my PYTHONPATH
.
I realized that when I ran my code as I had been when the tests were in the same directory as the module, I couldn't find my module:
$ python3 test/my_module/module_test.py 2.4.0
Traceback (most recent call last):
File "test/my_module/module_test.py", line 6, in <module>
from my_module.module import *
ModuleNotFoundError: No module named 'my_module'
However, when I explicitly specified the path things started to work:
$ PYTHONPATH=. python3 test/my_module/module_test.py 2.4.0
...........
----------------------------------------------------------------------
Ran 11 tests in 0.001s
OK
So, in the event that anyone has tried a few suggestions, believes their code is structured correctly and still finds themselves in a similar situation as myself try either of the following if you don't export the current directory to your PYTHONPATH:
$ PYTHONPATH=. python3 test/my_module/module_test.py
PYTHONPATH=.
, create a setup.py
file with contents like the following and run python setup.py development
to add packages to the path:# setup.py from setuptools import setup, find_packages setup( name='sample', packages=find_packages() )
recreate()
(as mentioned by TPReal) will only restart current activity, but the previous activities will still be in back stack and theme will not be applied to them.
So, another solution for this problem is to recreate the task stack completely, like this:
TaskStackBuilder.create(getActivity())
.addNextIntent(new Intent(getActivity(), MainActivity.class))
.addNextIntent(getActivity().getIntent())
.startActivities();
EDIT:
Just put the code above after you perform changing of theme on the UI or somewhere else. All your activities should have method setTheme()
called before onCreate()
, probably in some parent activity. It is also a normal approach to store the theme chosen in SharedPreferences
, read it and then set using setTheme()
method.
This usually happens when you update the java, the easiest way to solve this is to just uninstall the JDK & then reinstall it. NOTE: This doesnt remove the path or classpath so no need to worry.
Look for an open listener on port 1433 (the default port). If you get any response after creating a tcp connection there, the server's probably up.
dim result as dialogresult
result = MessageBox.Show("message", "caption", MessageBoxButtons.YesNoCancel)
If result = DialogResult.Cancel Then
MessageBox.Show("Cancel pressed")
ElseIf result = DialogResult.No Then
MessageBox.Show("No pressed")
ElseIf result = DialogResult.Yes Then
MessageBox.Show("Yes pressed")
End If
Get cursor on top, where white header with file name, then press Alt. To set top menu by default always visible. You needed in top menu selected: FILE -> Config... -> autoHideMenuBar: true (change it to autoHideMenuBar: false) Save it.
Note that the '=' is optional in C++11 universal initialization syntax, and it is generally considered better style to write :
char myarray[ARRAY_SIZE] {0}
this works:
window.onscroll = function (e) {
// called when the window is scrolled.
}
edit:
you said this is a function in a TimeInterval..
Try doing it like so:
userHasScrolled = false;
window.onscroll = function (e)
{
userHasScrolled = true;
}
then inside your Interval insert this:
if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}
I use Wireshark in most cases, but I have found Fiddler to be less of a hassle when dealing with encrypted data.
The following categories of variables are classified as initially unassigned:
The following categories of variables are classified as initially assigned:
class() exactly works like Javascript's typeof operator.
To get more details about variables you can use whos command or whos() function.
Here is the example code executed on MATLAB R2017a's Command Window.
>> % Define a number
>> num = 67
num =
67
>> % Get type of variable num
>> class(num)
ans =
'double'
>> % Define character vector
>> myName = 'Rishikesh Agrawani'
myName =
'Rishikesh Agrwani'
>> % Check type of myName
>> class(myName)
ans =
'char'
>> % Define a cell array
>> cellArr = {'This ', 'is ', 'a ', 'big chance to learn ', 'MATLAB.'}; % Cell array
>>
>> class(cellArr)
ans =
'cell'
>> % Get more details including type
>> whos num
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos myName
Name Size Bytes Class Attributes
myName 1x17 34 char
>> whos cellArr
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> % Another way to use whos i.e using whos(char_vector)
>> whos('cellArr')
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> whos('num')
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos('myName')
Name Size Bytes Class Attributes
myName 1x17 34 char
>>
If you need the difference in days accounting up to the second:
SELECT TIMESTAMPDIFF(SECOND,'2010-09-21 21:40:36','2010-10-08 18:23:13')/86400 AS diff
It will return
diff
16.8629
A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.
If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?
You should \usepackage{longtable}
.
Length of characters to be matched.
{n,m} n <= length <= m
{n} length == n
{n,} length >= n
And by default, the engine is greedy to match this pattern. For example, if the input is 123456789, \d{2,5} will match 12345 which is with length 5.
If you want the engine returns when length of 2 matched, use \d{2,5}?
I had the same error while following the tutorial on "Getting Started with ASP.NET MVC 5 | Microsoft Docs". I was on Visual Studio 2015. I opened View-> SQL Server Object Explorer and deleted the database named after the tutorial, then it could work. see Delete .mdf file from app_data causes exception cannot attach the file as database
This is a way to determine it for all css properties including visibility:
html:
<div id="element">div content</div>
css:
#element
{
visibility:hidden;
}
javascript:
var element = document.getElementById('element');
if(element.style.visibility == 'hidden'){
alert('hidden');
}
else
{
alert('visible');
}
It works for any css property and is very versatile and reliable.
A simpler approach is set use css
combined with setting the minRowsToShow
and virtualizationThreshold
value dynamically.
In stylesheet:
.ui-grid, .ui-grid-viewport {
height: auto !important;
}
In code, call the below function every time you change your data
in gridOptions
. maxRowToShow
is the value you pre-defined, for my use case, I set it to 25.
ES5:
setMinRowsToShow(){
//if data length is smaller, we shrink. otherwise we can do pagination.
$scope.gridOptions.minRowsToShow = Math.min($scope.gridOptions.data.length, $scope.maxRowToShow);
$scope.gridOptions.virtualizationThreshold = $scope.gridOptions.minRowsToShow ;
}
is
is identity testing and ==
is equality testing (see the Python documentation).
In most cases, if a is b
, then a == b
. But there are exceptions, for example:
>>> nan = float('nan')
>>> nan is nan
True
>>> nan == nan
False
So, you can only use is
for identity tests, never equality tests.
Don't use your raw url
Instead of:
cookieManager.setCookie(myUrl, cookieString);
use it like this:
cookieManager.setCookie("your url host", cookieString);
From :help opening-window
(search for "Closing a window" - /Closing a window
)
:q[uit]
close the current window and buffer. If it is the last window it will also exit vim:bd[elete]
unload the current buffer and close the current window:qa[all]
or :quita[ll]
will close all buffers and windows and exit vim (:qa!
to force without saving changes):clo[se]
close the current window but keep the buffer open. If there is only one window this command fails:hid[e]
hide the buffer in the current window (Read more at :help hidden
):on[ly]
close all other windows but leave all buffers openI use Windows 7 Professional 64-bit and have both the 32-bit and 64-bit Java 7u9 jre's installed. Chrome refused to work until I deleted the following registry key.
HKEY_LOCAL_MACHINE/Software/MozillaPlugins/@java.com/DTPlugin,version=10.9.2
Then I refreshed Chrome and the Applet loaded with a Warning that the plugin was out of date. I seleted "Run this time" and everything worked as expected.
function chkicon(num,allsize) {
var flagicon = document.getElementById("flagicon"+num).value;
if(flagicon=="plus"){
//alert("P== "+flagicon);
for (var i = 0; i < allsize; i++) {
if(document.getElementById("flagicon"+i).value !=""){
document.getElementById("flagicon"+i).value = "plus";
document.images["pic"+i].src = "../images/plus.gif";
}
}
document.images["pic"+num].src = "../images/minus.gif";
document.getElementById("flagicon"+num).value = "minus";
}else if(flagicon=="minus"){
//alert("M== "+flagicon);
document.images["pic"+num].src = "../images/plus.gif";
document.getElementById("flagicon"+num).value = "plus";
}else{
for (var i = 0; i < allsize; i++) {
if(document.getElementById("flagicon"+i).value !=""){
document.getElementById("flagicon"+i).value = "plus";
document.images["pic"+i].src = "../images/plus.gif";
}
}
}
}
If you're already using jQuery, you could look at using the jQuery Number Format plugin.
The plugin can return formatted numbers as a string, you can set decimal, and thousands separators, and you can choose the number of decimals to show.
$.number( 123, 2 ); // Returns '123.00'
You can also get jQuery Number Format from GitHub.
You can use filter
, like so:
$desired_object = $food->filter(function($item) {
return $item->id == 24;
})->first();
filter
will also return a Collection
, but since you know there will be only one, you can call first
on that Collection
.
You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first
:
$desired_object = $food->first(function($item) {
return $item->id == 24;
});
Follow the steps given below:
Stop your MySQL server completely. This can be done by accessing the Services window inside Windows XP and Windows Server 2003, where you can stop the MySQL service.
Open your MS-DOS command prompt using "cmd" inside the Run window. Inside it navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.
Execute the following command in the command prompt: mysqld.exe -u root --skip-grant-tables
Leave the current MS-DOS command prompt as it is, and open a new MS-DOS command prompt window.
Navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.
Enter mysql
and press enter.
You should now have the MySQL command prompt working. Type use mysql;
so that we switch to the "mysql" database.
Execute the following command to update the password:
UPDATE user SET Password = PASSWORD('NEW_PASSWORD') WHERE User = 'root';
However, you can now run any SQL command that you wish.
After you are finished close the first command prompt and type exit;
in the second command prompt windows to disconnect successfully. You can now start the MySQL service.
Answer above did not work for me on Chrome. The change event was been fired after I clicked out of the field somewhere, which did not help because the datepicker window is also closed too when you click out of the field.
I did use this code and it worked pretty well. You can place it after calling .datepicker();
HTML
<input type="text" class="datepicker-input" placeholder="click to show datepicker" />
JavaScript
$(".datepicker-input").each(function() {
$(this).datepicker();
});
$(".datepicker-input").click(function() {
$(".datepicker-days .day").click(function() {
$('.datepicker').hide();
});
});
Or you can use the ANDROID_ID setting from Android.Provider.Settings.System (as described here strazerre.com).
This has the advantage that it doesn't require special permissions but can change if another application has write access and changes it (which is apparently unusual but not impossible).
Just for reference here is the code from the blog:
import android.provider.Settings;
import android.provider.Settings.System;
String androidID = System.getString(this.getContentResolver(),Secure.ANDROID_ID);
Implementation note: if the ID is critical to the system architecture you need to be aware that in practice some of the very low end Android phones & tablets have been found reusing the same ANDROID_ID (9774d56d682e549c was the value showing up in our logs)
If your csv data happens to not contain newlines in any of the fields, you can load your data with textFile()
and parse it
import csv
import StringIO
def loadRecord(line):
input = StringIO.StringIO(line)
reader = csv.DictReader(input, fieldnames=["name1", "name2"])
return reader.next()
input = sc.textFile(inputFile).map(loadRecord)
Have a look at my primer on exactly this topic.
UPDATE:
var sio = require('socket.io'),
app = require('express').createServer();
app.listen(8080);
sio = sio.listen(app);
sio.on('connection', function (client) {
console.log('client connected');
// send the clients id to the client itself.
client.send(client.id);
client.on('disconnect', function () {
console.log('client disconnected');
});
});
Andrew had a great response but I wanted to tweek it a little. The way this is different is that I like my ModelViews to not have overhead data in them. Just the data for the object. It seem that ViewData fits the bill for over head data, but of course I'm new at this. I suggest doing something like this.
Controller
virtual public ActionResult DisplaySomeWidget(int id)
{
SomeModelView returnData = someDataMapper.getbyid(1);
var serializer = new JavaScriptSerializer();
ViewData["JSON"] = serializer.Serialize(returnData);
return View(myview, returnData);
}
View
//create base js object;
var myWidget= new Widget(); //Widget is a class with a public member variable called data.
myWidget.data= <%= ViewData["JSON"] %>;
What This does for you is it gives you the same data in your JSON as in your ModelView so you can potentially return the JSON back to your controller and it would have all the parts. This is similar to just requesting it via a JSONRequest however it requires one less call so it saves you that overhead. BTW this is funky for Dates but that seems like another thread.
Switching to another branch in git. Straightforward answer,
git-checkout - Switch branches or restore working tree files
git fetch origin <----this will fetch the branch
git checkout branch_name <--- Switching the branch
Before switching the branch make sure you don't have any modified files, in that case, you can commit the changes or you can stash it.
First, given that you have a complex data retrieval scenario, are you sure even SQLite is overkill?
You'll end up having an ad hoc, informally-specified, bug-ridden, slow implementation of half of SQLite, paraphrasing Greenspun's Tenth Rule.
That said, you are very right in saying that choosing a single data structure will impact one or more of searching, sorting or counting, so if performance is paramount and your data is constant, you could consider having more than one structure for different purposes.
Above all, measure what operations will be more common and decide which structure will end up costing less.
You might as well just use the ctype facet's narrow method directly:
#include <clocale> #include <locale> #include <string> #include <vector> inline std::string narrow(std::wstring const& text) { std::locale const loc(""); wchar_t const* from = text.c_str(); std::size_t const len = text.size(); std::vector<char> buffer(len + 1); std::use_facet<std::ctype<wchar_t> >(loc).narrow(from, from + len, '_', &buffer[0]); return std::string(&buffer[0], &buffer[len]); }
You can use the css property white-space and set it to pre-wrap to the enclosing div element.
div {
white-space: pre-wrap;
}
In Managed C++, static class syntax is:-
public ref class BitParser abstract sealed
{
public:
static bool GetBitAt(...)
{
...
}
}
... better late than never...
if you looking for a way how to download temporary file, do stuff and delete it try this gem https://github.com/equivalent/pull_tempfile
require 'pull_tempfile'
PullTempfile.transaction(url: 'https://mycompany.org/stupid-csv-report.csv', original_filename: 'dont-care.csv') do |tmp_file|
CSV.foreach(tmp_file.path) do |row|
# ....
end
end
If you want to make exceptions, you can apply the following "hack". It requires a user with DELETE
and INSERT
privilege for mysql.plugin
system table.
uninstall plugin validate_password;
SET PASSWORD FOR 'app' = PASSWORD('abcd');
INSTALL PLUGIN validate_password SONAME 'validate_password.so';
Bland security disclaimer: Consider, why you are making your password shorter or easier and perhaps consider replacing it with one that is more complex. However, I understand the "it's 3AM and just needs to work" moments, just make sure you don't build a system of hacks, lest you yourself be hacked
For Python 2.5 and older:
>>> [(a, b, c) for a in [1,2,3] for b in ['a','b'] for c in [4,5]]
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4),
(2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5),
(3, 'b', 4), (3, 'b', 5)]
Here's a recursive version of product()
(just an illustration):
def product(*args):
if not args:
return iter(((),)) # yield tuple()
return (items + (item,)
for items in product(*args[:-1]) for item in args[-1])
Example:
>>> list(product([1,2,3], ['a','b'], [4,5]))
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4),
(2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5),
(3, 'b', 4), (3, 'b', 5)]
>>> list(product([1,2,3]))
[(1,), (2,), (3,)]
>>> list(product([]))
[]
>>> list(product())
[()]
Type hint are a recent addition to a dynamic language where for decades folks swore naming conventions as simple as Hungarian (object label with first letter b = Boolean, c = character, d = dictionary, i = integer, l = list, n = numeric, s = string, t= tuple) were not needed, too cumbersome, but now have decided that, oh wait ... it is way too much trouble to use the language (type()) to recognize objects, and our fancy IDEs need help doing anything that complicated, and that dynamically assigned object values make them completely useless anyhow, whereas a simple naming convention could have resolved all of it, for any developer, at a mere glance.
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
$('#submit').click(function(){
if($('#myMessage').val() == ''){
alert('Input can not be left blank');
}
});
Update
If you don't want whitespace also u can remove them using jQuery.trim()
Description: Remove the whitespace from the beginning and end of a string.
$('#submit').click(function(){
if($.trim($('#myMessage').val()) == ''){
alert('Input can not be left blank');
}
});
Saxon will do this not only for XPath 2.0, but also for XQuery 1.0 and (in the commercial version) 3.0. It doesn't come as a Linux package, but as a jar file. Syntax (which you can easily wrap in a simple script) is
java net.sf.saxon.Query -s:source.xml -qs://element/attribute
2020 UPDATE
Saxon 10.0 includes the Gizmo tool, which can be used interactively or in batch from the command line. For example
java net.sf.saxon.Gizmo -s:source.xml
/>show //element/@attribute
/>quit
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
You might find it easier to understand by using a simple subquery
SELECT `settings`.*, (
SELECT `value` FROM `character_settings`
WHERE `character_settings`.`setting_id` = `settings`.`id`
AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`
The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.
Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.
SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'
WhatsApp has chosen Erlang a language built for writing scalable applications that are designed to withstand errors. Erlang uses an abstraction called the Actor model for it's concurrency - http://en.wikipedia.org/wiki/Actor_(programming_language) Instead of the more traditional shared memory approach, actors communicate by sending each other messages. Actors unlike threads are designed to be lightweight. Actors could be on the same machine or on different machines and the message passing abstractions works for both. A simple implementation of WhatsApp could be: Each user/device is represented as an actor. This actor is responsible for handling the inbox of the user, how it gets serialized to disk, the messages that the user sends and the messages that the user receives. Let's assume that Alice and Bob are friends on WhatsApp. So there is an an Alice actor and a Bob actor.
Let's trace a series of messages flowing back and forth:
Alice decides to message Bob. Alice's phone establishes a connection to the WhatsApp server and it is established that this connection is definitely from Alice's phone. Alice now sends via TCP the following message: "For Bob: A giant monster is attacking the Golden Gate Bridge". One of the WhatsApp front end server deserializes this message and delivers this message to the actor called Alice.
Alice the actor decides to serialize this and store it in a file called "Alice's Sent Messages", stored on a replicated file system to prevent data loss due to unpredictable monster rampage. Alice the actor then decides to forward this message to Bob the actor by passing it a message "Msg1 from Alice: A giant monster is attacking the Golden Gate Bridge". Alice the actor can retry with exponential back-off till Bob the actor acknowledges receiving the message.
Bob the actor eventually receives the message from (2) and decides to store this message in a file called "Bob's Inbox". Once it has stored this message durably Bob the actor will acknowledge receiving the message by sending Alice the actor a message of it's own saying "I received Msg1". Alice the actor can now stop it's retry efforts. Bob the actor then checks to see if Bob's phone has an active connection to the server. It does and so Bob the actor streams this message to the device via TCP.
Bob sees this message and replies with "For Alice: Let's create giant robots to fight them". This is now received by Bob the actor as outlined in Step 1. Bob the actor then repeats Step 2 and 3 to make sure Alice eventually receives the idea that will save mankind.
WhatsApp actually uses the XMPP protocol instead of the vastly superior protocol that I outlined above, but you get the point.
I think this is what you need if I'm understanding you correctly:
<div id="wrapperHeader">
<div id="header">
<img src="images/logo.png" alt="logo" />
</div>
</div>
div#wrapperHeader {
width:100%;
height;200px; /* height of the background image? */
background:url(images/header.png) repeat-x 0 0;
text-align:center;
}
div#wrapperHeader div#header {
width:1000px;
height:200px;
margin:0 auto;
}
div#wrapperHeader div#header img {
width:; /* the width of the logo image */
height:; /* the height of the logo image */
margin:0 auto;
}
You can implement an OnClickListener via OnTouchListener:
webView.setOnTouchListener(new View.OnTouchListener() {
public final static int FINGER_RELEASED = 0;
public final static int FINGER_TOUCHED = 1;
public final static int FINGER_DRAGGING = 2;
public final static int FINGER_UNDEFINED = 3;
private int fingerState = FINGER_RELEASED;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if (fingerState == FINGER_RELEASED) fingerState = FINGER_TOUCHED;
else fingerState = FINGER_UNDEFINED;
break;
case MotionEvent.ACTION_UP:
if(fingerState != FINGER_DRAGGING) {
fingerState = FINGER_RELEASED;
// Your onClick codes
}
else if (fingerState == FINGER_DRAGGING) fingerState = FINGER_RELEASED;
else fingerState = FINGER_UNDEFINED;
break;
case MotionEvent.ACTION_MOVE:
if (fingerState == FINGER_TOUCHED || fingerState == FINGER_DRAGGING) fingerState = FINGER_DRAGGING;
else fingerState = FINGER_UNDEFINED;
break;
default:
fingerState = FINGER_UNDEFINED;
}
return false;
}
});
I'd use absolute positioning:
#play_button {
position:absolute;
transition: .5s ease;
left: 202px;
top: 198px;
}
I believe @AnujGupta's answer is correct. However the rollback can itself raise an exception which you should catch and handle:
from django.db import transaction, DatabaseError
try:
a.save()
except DatabaseError:
try:
transaction.rollback()
except transaction.TransactionManagementError:
# Log or handle otherwise
If you find you're rewriting this code in various save()
locations, you can extract-method:
import traceback
def try_rolling_back():
try:
transaction.rollback()
log.warning('rolled back') # example handling
except transaction.TransactionManagementError:
log.exception(traceback.format_exc()) # example handling
Finally, you can prettify it using a decorator that protects methods which use save()
:
from functools import wraps
def try_rolling_back_on_exception(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
try:
return fn(*args, **kwargs)
except:
traceback.print_exc()
try_rolling_back()
return wrapped
@try_rolling_back_on_exception
def some_saving_method():
# ...
model.save()
# ...
Even if you implement the decorator above, it's still convenient to keep try_rolling_back()
as an extracted method in case you need to use it manually for cases where specific handling is required, and the generic decorator handling isn't enough.
I wanted to use wildcards to plot multiple files often placed in different directories, while working from any directory. The solution i found was to create the following function in ~/.bashrc
plo () {
local arg="w l"
local str="set term wxt size 900,500 title 'wild plotting'
set format y '%g'
set logs
plot"
while [ $# -gt 0 ]
do str="$str '$1' $arg,"
shift
done
echo "$str" | gnuplot -persist
}
and use it e.g. like plo *.dat ../../dir2/*.out
, to plot all .dat
files in the current directory and all .out
files in a directory that happens to be a level up and is called dir2
.
Open the Windows > Preferences menu.
Expand the Run/Debug > Console preferences.
Set the Console buffer size (characters)
to something much bigger. 2147383647
/ ~2GB is the upper limit (or 1000000
/ ~1MB in older releases). Or just uncheck the Limit console output
.
Use shorthand property for the background property and type the folder name where thje image had been located.
.btn-pTool{
margin:0;
padding:0;
background:url("../folder name/slide_button.png") no-repeat;
}
.btn-pToolName{
text-align: center;
width: 26px;
height: 190px;
display: block;
color: #fff;
text-decoration: none;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
line-height: 32px;
}
Something like...
greetings = 'Hello {name}'.format(name = 'John')
Hello John
In case this can help anyone, here's simple CSS as a jumping off point. Turns it into a basic rounded square big enough for thumbs with a toggled background color.
input[type='checkbox'] {_x000D_
-webkit-appearance:none;_x000D_
width:30px;_x000D_
height:30px;_x000D_
background:white;_x000D_
border-radius:5px;_x000D_
border:2px solid #555;_x000D_
}_x000D_
input[type='checkbox']:checked {_x000D_
background: #abd;_x000D_
}
_x000D_
<input type="checkbox" />
_x000D_
Bower maintains a single version of modules, it only tries to help you select the correct/best one for you.
NPM is better for node modules because there is a module system and you're working locally. Bower is good for the browser because currently there is only the global scope, and you want to be very selective about the version you work with.
If you want to temporarily revert the commits of a feature, then you can use the series of following commands.
git log --pretty=oneline | grep 'feature_name' | cut -d ' ' -f1 | xargs -n1 git revert --no-edit
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1')
change day/month position.
I also think it is important to note that Python dict
object type is a hash table (more on this here), and thus is not capable of being sorted without converting its keys/values to lists. What this allows is dict
item retrieval in constant time O(1)
, no matter the size/number of elements in a dictionary.
Having said that, once you sort its keys - sorted(data.keys())
, or values - sorted(data.values())
, you can then use that list to access keys/values in design patterns such as these:
for sortedKey in sorted(dictionary):
print dictionary[sortedKeY] # gives the values sorted by key
for sortedValue in sorted(dictionary.values()):
print sortedValue # gives the values sorted by value
Hope this helps.
A bit more to your question.
I used gTTS package to generate audio from text and then play that audio using Playsound when I was learning webscraping and created a coursera downloader(only free courses).
text2speech = gTTS("Your course " + course_name +
" is downloaded to " + downloads + ". Check it fast.")
text2speech.save("temp.mp3")
winsound.Beep(2500, 1000)
playsound("temp.mp3")
Today, I can use Promise
in Node.js
as a plain Javascript method.
A simple and basic example to Promise
(with KISS way):
Plain Javascript Async API code:
function divisionAPI (number, divider, successCallback, errorCallback) {
if (divider == 0) {
return errorCallback( new Error("Division by zero") )
}
successCallback( number / divider )
}
Promise
Javascript Async API code:
function divisionAPI (number, divider) {
return new Promise(function (fulfilled, rejected) {
if (divider == 0) {
return rejected( new Error("Division by zero") )
}
fulfilled( number / divider )
})
}
(I recommend visiting this beautiful source)
Also Promise
can be used with together async\await
in ES7
to make the program flow wait for a fullfiled
result like the following:
function getName () {
return new Promise(function (fulfilled, rejected) {
var name = "John Doe";
// wait 3000 milliseconds before calling fulfilled() method
setTimeout (
function() {
fulfilled( name )
},
3000
)
})
}
async function foo () {
var name = await getName(); // awaits for a fulfilled result!
console.log(name); // the console writes "John Doe" after 3000 milliseconds
}
foo() // calling the foo() method to run the code
Another usage with the same code by using .then()
method
function getName () {
return new Promise(function (fulfilled, rejected) {
var name = "John Doe";
// wait 3000 milliseconds before calling fulfilled() method
setTimeout (
function() {
fulfilled( name )
},
3000
)
})
}
// the console writes "John Doe" after 3000 milliseconds
getName().then(function(name){ console.log(name) })
Promise
can also be used on any platform that is based on Node.js like react-native
.
Bonus: An hybrid method
(The callback method is assumed to have two parameters as error and result)
function divisionAPI (number, divider, callback) {
return new Promise(function (fulfilled, rejected) {
if (divider == 0) {
let error = new Error("Division by zero")
callback && callback( error )
return rejected( error )
}
let result = number / divider
callback && callback( null, result )
fulfilled( result )
})
}
The above method can respond result for old fashion callback and Promise usages.
Hope this helps.
While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding
(or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:
sys.stdout.buffer.write(some_bytes_object)
This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.
The answer about threading is good, but you need to be a bit more specific about what you want to do.
If you have two functions that both use a lot of CPU, threading (in CPython) will probably get you nowhere. Then you might want to have a look at the multiprocessing module or possibly you might want to use jython/IronPython.
If CPU-bound performance is the reason, you could even implement things in (non-threaded) C and get a much bigger speedup than doing two parallel things in python.
Without more information, it isn't easy to come up with a good answer.
I used
<p align='right'>Farhan Khan</p>
and it worked for me on Google Colaboratory. Funnily enough it does not work anywhere else?
Or, you can go to your android-studio\bin
folder and change these -Xmx and -Xms values in studio.exe.vmoptions
or studio64.exe.vmoptions
files (depending on which version you are running).
We resolved our issues by re-installing the Oracle Database Client. Somehow the installation wasn't successful on 1 of the workstations (even though there was no logging), however when comparing size/files/folders of the Oracle directory to a working client workstation, there was a significant amount of files that were missing. Once we performed a clean install, everything worked perfectly.
The way I often deal with the situation you describe is to use the .to_csv()
method and write to stdout:
import sys
df.to_csv(sys.stdout)
Update: it should now be possible to just use None
instead of sys.stdout
with similar effect!
This should dump the whole dataframe, including the entirety of any strings. You can use the to_csv parameters to configure column separators, whether the index is printed, etc. It will be less pretty than rendering it properly though.
I posted this originally in answer to the somewhat-related question at Output data from all columns in a dataframe in pandas
=ADDRESS(ROW(),COLUMN())
=ADDRESS(ROW(),COLUMN(),1)
=ADDRESS(ROW(),COLUMN(),2)
=ADDRESS(ROW(),COLUMN(),3)
=ADDRESS(ROW(),COLUMN(),4)
There is an easy way to fix it. Just install a plugin and active it. For more : https://www.aitlp.com/wordpress-5-3-is-not-a-function-fix/ .
Tested with Wordpress version 5.3.
You can use the append function to add another element to it. Only, make a series of the new element, before you append it:
test = test.append(pd.Series(200, index=[101]))
You could use IIF
statement like in the next example:
SELECT
IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
TABLE_NAME
for window :
pip install mysqlclient pymysql
then:
import pymysql pymysql.install_as_MySQLdb()
for python 3 Ubuntu
sudo apt-get install -y python3-mysqldb
I know this is old question, but this command helped me!
Go to your Tomcat Directory
Just type this command in your terminal:
./catalina.sh start
Reminder:
Func<X, Y, R>
is a function with two inputs of typeX
andY
, that returns a result of typeR
.
Enumerable.Aggregate has three overloads:
Overload 1:
A Aggregate<A>(IEnumerable<A> a, Func<A, A, A> f)
Example:
new[]{1,2,3,4}.Aggregate((x, y) => x + y); // 10
This overload is simple, but it has the following limitations:
InvalidOperationException
.Overload 2:
B Aggregate<A, B>(IEnumerable<A> a, B bIn, Func<B, A, B> f)
Example:
var hayStack = new[] {"straw", "needle", "straw", "straw", "needle"};
var nNeedles = hayStack.Aggregate(0, (n, e) => e == "needle" ? n+1 : n); // 2
This overload is more general:
bIn
).Overload 3:
C Aggregate<A,B,C>(IEnumerable<A> a, B bIn, Func<B,A,B> f, Func<B,C> f2)
The third overload is not very useful IMO.
The same can be written more succinctly by using overload 2 followed by a function that transforms its result.
The illustrations are adapted from this excellent blogpost.
Queue<String> qe=new LinkedList<String>();
qe.add("b");
qe.add("a");
qe.add("c");
Since Queue
is an interface, you can't create an instance of it as you illustrated
You will need to Build and Archive your project. You may need to check what code signing settings you have in the project and executable.
Use the Organiser to select your archive version and then you can Share that version of your project. You will need to select the correct code signing again. It will allow you to save the .ipa file where you want.
Drag and drop the .ipa file into iTunes and then sync with your iPhone.
finally, I found a solution
Window window = ((Node)(event.getSource())).getScene().getWindow();
if (window instanceof Stage){
((Stage) window).close();
}
IntelliJ 2019 community edition has line number by default. If you want to show or hide line numbers, go to the following settings to change the appearance.
go to ? File ? Setting ? Editor ? General ? Appearance ? [Check] Show line numbers
To ignore some folder from eslint rules we could create the file .eslintignore
in root directory and add there the path to the folder we want omit (the same way as for .gitignore
).
Here is the example from the ESLint docs on Ignoring Files and Directories:
# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default
# Ignore built files except build/index.js
build/*
!build/index.js
To follow up on the answer by user183038, here is a shell script to batch rename all xlsx files to csv while preserving the file names. The xlsx2csv tool needs to be installed prior to running.
for i in *.xlsx;
do
filename=$(basename "$i" .xlsx);
outext=".csv"
xlsx2csv $i $filename$outext
done
you can make guid variable to accept null first using ? operator then you use Guid.Empty or typecast it to null using (Guid?)null;
eg:
Guid? id = Guid.Empty;
or
Guid? id = (Guid?)null;
Using a regex, you can clean everything inside <>
:
import re
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
Some HTML texts can also contain entities that are not enclosed in brackets, such as '&nsbm
'. If that is the case, then you might want to write the regex as
cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
This link contains more details on this.
You could also use BeautifulSoup
additional package to find out all the raw text.
You will need to explicitly set a parser when calling BeautifulSoup
I recommend "lxml"
as mentioned in alternative answers (much more robust than the default one (html.parser
) (i.e. available without additional install).
from bs4 import BeautifulSoup
cleantext = BeautifulSoup(raw_html, "lxml").text
But it doesn't prevent you from using external libraries, so I recommend the first solution.
EDIT: To use lxml
you need to pip install lxml
.
why make is sooooo hard people when it can be soooo easy :)
//here is the pull from the form
$your_form_text = $_POST['your_form_text'];
//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);
//email away
$message = "Comments: $your_form_text";
mail("[email protected]", "Website Form Submission", $message, $headers);
you will obviously need headers and likely have more fields, but this is your textarea take care of
If you are using androidx 1.0.0 and are using a custom fab size, you will have to specify the custom size using
app:fabCustomSize="your custom size in dp"
By deafult the size is 56dp and there is another variation that is the small sized fab which is 40dp, if you are using anything you will have to specify it for the padding to be calculated correctly
One is a column (aka Series), while the other is a DataFrame:
In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [2]: df
Out[2]:
a b
0 1 2
1 3 4
The column 'b' (aka Series):
In [3]: df['b']
Out[3]:
0 2
1 4
Name: b, dtype: int64
The subdataframe with columns (position) in [1]:
In [4]: df[[1]]
Out[4]:
b
0 2
1 4
Note: it's preferable (and less ambiguous) to specify whether you're talking about the column name e.g. ['b'] or the integer location, since sometimes you can have columns named as integers:
In [5]: df.iloc[:, [1]]
Out[5]:
b
0 2
1 4
In [6]: df.loc[:, ['b']]
Out[6]:
b
0 2
1 4
In [7]: df.loc[:, 'b']
Out[7]:
0 2
1 4
Name: b, dtype: int64
Your concatenation syntax is correct.
Most likely the callback function isn't even being called. You can test that by putting an alert()
, console.log()
or debugger
line in that function.
If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail()
handler after $.post()
to find out what the error is, e.g.:
$.post('ajaxskeleton.php', {
red: text
}, function(){
$('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(arguments);
});
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl
A bit similar to @bpile answer, my case was a my.cnf entry setting collation-server = utf8_general_ci
. After I realized that (and after trying everything above), I forcefully switched my database to utf8_general_ci instead of utf8_unicode_ci and that was it:
ALTER DATABASE `db` CHARACTER SET utf8 COLLATE utf8_general_ci;
A combination of the answers to this question provides the most robust solution.
It worked for us in production-grade scripts with great support of dependencies and directory structure:
#!/bin/bash # Full path of the current script THIS=`readlink -f "${BASH_SOURCE[0]}" 2>/dev/null||echo $0` # The directory where current script resides DIR=`dirname "${THIS}"` # 'Dot' means 'source', i.e. 'include': . "$DIR/compile.sh"
The method supports all of these:
readlink
)${BASH_SOURCE[0]}
is more robust than $0
You should be aware of a few key factors...
First, there are two types of compression: Lossless and Lossy.
There are also different colour depths (palettes): Indexed color and Direct color.
BMP - Lossless / Indexed and Direct
This is an old format. It is Lossless (no image data is lost on save) but there's also little to no compression at all, meaning saving as BMP results in VERY large file sizes. It can have palettes of both Indexed and Direct, but that's a small consolation. The file sizes are so unnecessarily large that nobody ever really uses this format.
Good for: Nothing really. There isn't anything BMP excels at, or isn't done better by other formats.
GIF - Lossless / Indexed only
GIF uses lossless compression, meaning that you can save the image over and over and never lose any data. The file sizes are much smaller than BMP, because good compression is actually used, but it can only store an Indexed palette. This means that for most use cases, there can only be a maximum of 256 different colours in the file. That sounds like quite a small amount, and it is.
GIF images can also be animated and have transparency.
Good for: Logos, line drawings, and other simple images that need to be small. Only really used for websites.
JPEG - Lossy / Direct
JPEGs images were designed to make detailed photographic images as small as possible by removing information that the human eye won't notice. As a result it's a Lossy format, and saving the same file over and over will result in more data being lost over time. It has a palette of thousands of colours and so is great for photographs, but the lossy compression means it's bad for logos and line drawings: Not only will they look fuzzy, but such images will also have a larger file-size compared to GIFs!
Good for: Photographs. Also, gradients.
PNG-8 - Lossless / Indexed
PNG is a newer format, and PNG-8 (the indexed version of PNG) is really a good replacement for GIFs. Sadly, however, it has a few drawbacks: Firstly it cannot support animation like GIF can (well it can, but only Firefox seems to support it, unlike GIF animation which is supported by every browser). Secondly it has some support issues with older browsers like IE6. Thirdly, important software like Photoshop have very poor implementation of the format. (Damn you, Adobe!) PNG-8 can only store 256 colours, like GIFs.
Good for: The main thing that PNG-8 does better than GIFs is having support for Alpha Transparency.
PNG-24 - Lossless / Direct
PNG-24 is a great format that combines Lossless encoding with Direct color (thousands of colours, just like JPEG). It's very much like BMP in that regard, except that PNG actually compresses images, so it results in much smaller files. Unfortunately PNG-24 files will still be bigger than JPEGs (for photos), and GIFs/PNG-8s (for logos and graphics), so you still need to consider if you really want to use one.
Even though PNG-24s allow thousands of colours while having compression, they are not intended to replace JPEG images. A photograph saved as a PNG-24 will likely be at least 5 times larger than a equivalent JPEG image, with very little improvement in visible quality. (Of course, this may be a desirable outcome if you're not concerned about filesize, and want to get the best quality image you can.)
Just like PNG-8, PNG-24 supports alpha-transparency, too.
SVG - Lossless / Vector
A filetype that is currently growing in popularity is SVG, which is different than all the above in that it's a vector file format (the above are all raster). This means that it's actually comprised of lines and curves instead of pixels. When you zoom in on a vector image, you still see a curve or a line. When you zoom in on a raster image, you will see pixels.
For example:
This means SVG is perfect for logos and icons you wish to retain sharpness on Retina screens or at different sizes. It also means a small SVG logo can be used at a much larger (bigger) size without degradation in image quality -- something that would require a separate larger (in terms of filesize) file with raster formats.
SVG file sizes are often tiny, even if they're visually very large, which is great. It's worth bearing in mind, however, that it does depend on the complexity of the shapes used. SVGs require more computing power than raster images because mathematical calculations are involved in drawing the curves and lines. If your logo is especially complicated it could slow down a user's computer, and even have a very large file size. It's important that you simplify your vector shapes as much as possible.
Additionally, SVG files are written in XML, and so can be opened and edited in a text editor(!). This means its values can be manipulated on the fly. For example, you could use JavaScript to change the colour of an SVG icon on a website, much like you would some text (ie. no need for a second image), or even animate them.
In all, they are best for simple flat shapes like logos or graphs.
I hope that helps!
Note that there's a weird problem if you're using Bootstrap's JS buttons and the 'loading' state. I don't know why this happens, but here's how to fix it.
Say you have a button and you set it to the loading state:
var myButton = $('#myBootstrapButton');
myButton.button('loading');
Now you want to take it out of the loading state, but also disable it (e.g. the button was a Save button, the loading state indicated an ongoing validation and the validation failed). This looks like reasonable Bootstrap JS:
myButton.button('reset').prop('disabled', true); // DOES NOT WORK
Unfortunately, that will reset the button, but not disable it. Apparently, button()
performs some delayed task. So you'll also have to postpone your disabling:
myButton.button('reset');
setTimeout(function() { myButton.prop('disabled', true); }, 0);
A bit annoying, but it's a pattern I'm using a lot.
The problem with opacity
is that it will also affect the content, when often you do not want this to happen.
If you just want your element to be transparent, it's really as easy as :
background-color: transparent;
But if you want it to be in colors, you can use:
background-color: rgba(255, 0, 0, 0.4);
Or define a background image (1px
by 1px
) saved with the right alpha
.
(To do so, use Gimp
, Paint.Net
or any other image software that allows you to do that.
Just create a new image, delete the background and put a semi-transparent color in it, then save it in png.)
As said by René, the best thing to do would be to mix both, with the rgba
first and the 1px
by 1px
image as a fallback if the browser doesn't support alpha :
background: url('img/red_transparent_background.png');
background: rgba(255, 0, 0, 0.4);
See also : http://www.w3schools.com/cssref/css_colors_legal.asp.
Demo : My JSFiddle
According to the Apache site this is the Gradle dependency you need to include, if you use Android API 23 or newer:
dependencies {
compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}
Source: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html
Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.
Sigh, it took me 45 minutes to find the answer to this simple question. The answer is: grepl(needle, haystack, fixed=TRUE)
# Correct
> grepl("1+2", "1+2", fixed=TRUE)
[1] TRUE
> grepl("1+2", "123+456", fixed=TRUE)
[1] FALSE
# Incorrect
> grepl("1+2", "1+2")
[1] FALSE
> grepl("1+2", "123+456")
[1] TRUE
grep
is named after the linux executable, which is itself an acronym of "Global Regular Expression Print", it would read lines of input and then print them if they matched the arguments you gave. "Global" meant the match could occur anywhere on the input line, I'll explain "Regular Expression" below, but the idea is it's a smarter way to match the string (R calls this "character", eg class("abc")
), and "Print" because it's a command line program, emitting output means it prints to its output string.
Now, the grep
program is basically a filter, from lines of input, to lines of output. And it seems that R's grep
function similarly will take an array of inputs. For reasons that are utterly unknown to me (I only started playing with R about an hour ago), it returns a vector of the indexes that match, rather than a list of matches.
But, back to your original question, what we really want is to know whether we found the needle in the haystack, a true/false value. They apparently decided to name this function grepl
, as in "grep" but with a "Logical" return value (they call true and false logical values, eg class(TRUE)
).
So, now we know where the name came from and what it's supposed to do. Lets get back to Regular Expressions. The arguments, even though they are strings, they are used to build regular expressions (henceforth: regex). A regex is a way to match a string (if this definition irritates you, let it go). For example, the regex a
matches the character "a"
, the regex a*
matches the character "a"
0 or more times, and the regex a+
would match the character "a"
1 or more times. Hence in the example above, the needle we are searching for 1+2
, when treated as a regex, means "one or more 1 followed by a 2"... but ours is followed by a plus!
So, if you used the grepl
without setting fixed
, your needles would accidentally be haystacks, and that would accidentally work quite often, we can see it even works for the OP's example. But that's a latent bug! We need to tell it the input is a string, not a regex, which is apparently what fixed
is for. Why fixed? No clue, bookmark this answer b/c you're probably going to have to look it up 5 more times before you get it memorized.
The better your code is, the less history you have to know to make sense of it. Every argument can have at least two interesting values (otherwise it wouldn't need to be an argument), the docs list 9 arguments here, which means there's at least 2^9=512 ways to invoke it, that's a lot of work to write, test, and remember... decouple such functions (split them up, remove dependencies on each other, string things are different than regex things are different than vector things). Some of the options are also mutually exclusive, don't give users incorrect ways to use the code, ie the problematic invocation should be structurally nonsensical (such as passing an option that doesn't exist), not logically nonsensical (where you have to emit a warning to explain it). Put metaphorically: replacing the front door in the side of the 10th floor with a wall is better than hanging a sign that warns against its use, but either is better than neither. In an interface, the function defines what the arguments should look like, not the caller (because the caller depends on the function, inferring everything that everyone might ever want to call it with makes the function depend on the callers, too, and this type of cyclical dependency will quickly clog a system up and never provide the benefits you expect). Be very wary of equivocating types, it's a design flaw that things like TRUE
and 0
and "abc"
are all vectors.
See excerpt from official documentation for containment
option:
containment
Default:
false
Constrains dragging to within the bounds of the specified element or region.
Multiple types supported:
- Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
- Element: The draggable element will be contained to the bounding box of this element.
- String: Possible values:
"parent"
,"document"
,"window"
.- Array: An array defining a bounding box in the form
[ x1, y1, x2, y2 ]
.Code examples:
Initialize the draggable with thecontainment
option specified:$( ".selector" ).draggable({ containment: "parent" });
Get or set the
containment
option, after initialization:// Getter var containment = $( ".selector" ).draggable( "option", "containment" ); // Setter $( ".selector" ).draggable( "option", "containment", "parent" );
Just only copy and paste this code it will get your page content.
<?php
$pageid = get_the_id();
$content_post = get_post($pageid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>
By default, all one-to-many
and many-to-many
associations are fetched lazily upon being accessed for the first time.
In your use case, you could overcome this issue by wrapping all DAO operations into one logical transaction:
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus transactionStatus) {
int startingCount = sfdao.count();
sfdao.create( sf );
SecurityFiling sf2 = sfdao.read( sf.getId() );
sfdao.delete( sf );
int endingCount = sfdao.count();
assertTrue( startingCount == endingCount );
assertTrue( sf.getId().longValue() == sf2.getId().longValue() );
assertTrue( sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() ) );
assertTrue( sf.getSfTransactionNumber().equals( sf2.getSfTransactionNumber() ) );
return null;
}
});
Another option is to fetch all LAZY associations upon loading your entity, so that:
SecurityFiling sf2 = sfdao.read( sf.getId() );
should fetch the LAZY submissionType
too:
select sf
from SecurityFiling sf
left join fetch.sf.submissionType
This way, you eagerly fetch all lazy properties and you can access them after the Session gets closed too.
You can fetch as many [one|many]-to-one
associations and one "[one|many]-to-many" List associations (because of running a Cartesian Product).
To initialize multiple "[one|many]-to-many", you should use Hibernate.initialize(collection), right after loading your root entity.
You can use the DataFrame apply
method:
order_df['Value'] = order_df.apply(lambda row: (row['Prices']*row['Amount']
if row['Action']=='Sell'
else -row['Prices']*row['Amount']),
axis=1)
It is usually faster to use these methods rather than over for loops.
You should not add to your list using c
inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element)
, the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N)
. If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg
i <- 1
while(...) {
l[[i]] <- new_element
i <- i + 1
}
For more info have a look at Patrick Burns' The R Inferno (Chapter 2).
This problem normally appears while copy pasting the tag lib URL from the internet. Usually the quotes ""
in which the URL http://www.springframework.org/tags is embedded might not be correct. Try removing quotes and type them manually. This resolved the issue for me.
This is simple but the developer gets confused due to multiple views having the same attributes in different configurations/namespaces.
In the case of the TextInputLayout we have every time a different view and with params either with TextInputEditText or directly to TextInputLayout.
I was using all the above fixes: But I found that I was using
app:textColorHint="@color/textcolor_black"
actually i should be using
android:textColorHint="@color/textcolor_black"
As an attribute of TextinputLayout
textcolor_black.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/black_txt" android:state_enabled="true" />
<item android:color="@color/black_txt" android:state_selected="true" />
<item android:color="@color/txtColorGray" android:state_selected="false" />
<item android:color="@color/txtColorGray" android:state_enabled="false" />
</selector>
OK realized a mistake .. it has to be /:id/:id2
Anyway didn't find this in any tutorial or other StackOverflow question.
@RouteConfig([{path: '/component/:id/:id2',name: 'MyCompB', component:MyCompB}])
export class MyCompA {
onClick(){
this._router.navigate( ['MyCompB', {id: "someId", id2: "another ID"}]);
}
}
It is an old question but i want to add that if you want to resize image according to viewport size only with css; you can use viewport units "vh (viewport height) or vw (viewport width)".
.img {
width: 100vw;
height: 100vh;
}
here are my personal ~/.vimrc backup settings
" backup to ~/.tmp
set backup
set backupdir=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
set backupskip=/tmp/*,/private/tmp/*
set directory=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
set writebackup
Expanding on brettdj's answer, in order to parse disjoint embedded digits into separate numbers:
Sub TestNumList()
Dim NumList As Variant 'Array
NumList = GetNums("34d1fgd43g1 dg5d999gdg2076")
Dim i As Integer
For i = LBound(NumList) To UBound(NumList)
MsgBox i + 1 & ": " & NumList(i)
Next i
End Sub
Function GetNums(ByVal strIn As String) As Variant 'Array of numeric strings
Dim RegExpObj As Object
Dim NumStr As String
Set RegExpObj = CreateObject("vbscript.regexp")
With RegExpObj
.Global = True
.Pattern = "[^\d]+"
NumStr = .Replace(strIn, " ")
End With
GetNums = Split(Trim(NumStr), " ")
End Function
Update for the new 64bit arch
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -9223372036854775808
LONG_MAX: 9223372036854775807
ULONG_MAX: 18446744073709551615
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
I had a similar requirement when I stumbled on this post. I wanted a fast way to build a String that can grow from both sides ie. add new letters on the front as well as back arbitrarily. I know this is an old post, but it inspired me to try out a few ways to create strings and I thought I'd share my findings. I am also using some Java 8 constructs in this, which could have optimised the speed in cases 4 and 5.
https://gist.github.com/SidWagz/e41e836dec65ff24f78afdf8669e6420
The Gist above has the detailed code that anyone can run. I took few ways of growing strings in this; 1) Append to StringBuilder, 2) Insert to front of StringBuilder as as shown by @Mehrdad, 3) Partially insert from front as well as end of the StringBuilder, 4) Using a list to append from end, 5) Using a Deque to append from the front.
// Case 2
StringBuilder build3 = new StringBuilder();
IntStream.range(0, MAX_STR)
.sequential()
.forEach(i -> {
if (i%2 == 0) build3.append(Integer.toString(i)); else build3.insert(0, Integer.toString(i));
});
String build3Out = build3.toString();
//Case 5
Deque<String> deque = new ArrayDeque<>();
IntStream.range(0, MAX_STR)
.sequential()
.forEach(i -> {
if (i%2 == 0) deque.addLast(Integer.toString(i)); else deque.addFirst(Integer.toString(i));
});
String dequeOut = deque.stream().collect(Collectors.joining(""));
I'll focus on the front append only cases ie. case 2 and case 5. The implementation of StringBuilder internally decides how the internal buffer grows, which apart from moving all buffer left to right in case of front appending limits the speed. While time taken when inserting directly to the front of the StringBuilder grows to really high values, as shown by @Mehrdad, if the need is to only have strings of length less than 90k characters (which is still a lot), the front insert will build a String in the same time as it would take to build a String of the same length by appending at the end. What I am saying is that time time penalty indeed kicks and is huge, but only when you have to build really huge strings. One could use a deque and join the strings at the end as shown in my example. But StringBuilder is a bit more intuitive to read and code, and the penalty would not matter for smaller strings.
Actually the performance for case 2 is much faster than case 1, which I don't seem to understand. I assume the growth for the internal buffer in StringBuilder would be the same in case of front append and back append. I even set the minimum heap to a very large amount to avoid delay in heap growth, if that would have played a role. Maybe someone who has a better understanding can comment below.
The ifelse
function would be a quick and easy way to do this.
You should be able to download the file using
window.open("data:application/pdf;base64," + Base64.encode(out));
There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.
However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.
Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]
UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact
There's a lot of manual solutions to this, but I wanted to reiterate and update Julie's answer above. Use google collections Joiner class.
Joiner.on(", ").join(34, 26, ..., 2)
It handles var args, iterables and arrays and properly handles separators of more than one char (unlike gimmel's answer). It will also handle null values in your list if you need it to.
The floor() method doesn't work for negative numbers. This works every time:
$num = 5.7;
$whole = (int) $num; // 5
$frac = $num - $whole; // .7
...also works for negatives (same code, different number):
$num = -5.7;
$whole = (int) $num; // -5
$frac = $num - $whole; // -.7
To install the plugin manually, try: