First of all: officially, the correct question would be
web services + WSDL + SOAP
vsREST
.Because, although the web service, is used in the loose sense, when using the HTTP protocol to transfer data instead of web pages, officially it is a very specific form of that idea. According to the definition, REST is not "web service".
In practice however, everyone ignores that, so let's ignore it too
There are already technical answers, so I'll try to provide some intuition.
Let's say you want to call a function in a remote computer, implemented in some other programming language (this is often called remote procedure call/RPC). Assume that function can be found at a specific URL, provided by the person who wrote it. You have to (somehow) send it a message, and get some response. So, there are two main questions to consider.
For the first question, the official definition is WSDL. This is an XML file which describes, in detailed and strict format, what are the parameters, what are their types, names, default values, the name of the function to be called, etc. An example WSDL here shows that the file is human-readable (but not easily).
For the second question, there are various answers. However, the only one used in practice is SOAP. Its main idea is: wrap the previous XML (the actual message) into yet another XML (containing encoding info and other helpful stuff), and send it over HTTP. The POST method of the HTTP is used to send the message, since there is always a body.
The main idea of this whole approach is that you map a URL to a function, that is, to an action. So, if you have a list of customers in some server, and you want to view/update/delete one, you must have 3 URLS:
myapp/read-customer
and in the body of the message, pass the id of the customer to be read.myapp/update-customer
and in the body, pass the id of the customer, as well as the new datamyapp/delete-customer
and the id in the bodyThe REST approach sees things differently. A URL should not represent an action, but a thing (called resource in the REST lingo). Since the HTTP protocol (which we are already using) supports verbs, use those verbs to specify what actions to perform on the thing.
So, with the REST approach, customer number 12 would be found on URL myapp/customers/12
. To view the customer data, you hit the URL with a GET request. To delete it, the same URL, with a DELETE verb. To update it, again, the same URL with a POST verb, and the new content in the request body.
For more details about the requirements that a service has to fulfil to be considered truly RESTful, see the Richardson maturity model. The article gives examples, and, more importantly, explains why a (so-called) SOAP service, is a level-0 REST service (although, level-0 means low compliance to this model, it's not offensive, and it is still useful in many cases).
Declaration
Declarations tell the compiler that a program element or name exists. A declaration introduces one or more names into a program. Declarations can occur more than once in a program. Therefore, classes, structures, enumerated types, and other user-defined types can be declared for each compilation unit.
Definition
Definitions specify what code or data the name describes. A name must be declared before it can be used.
Unit testing is directed at the smallest part of the implementation possible. In Java this means you are testing a single class. If the class depends on other classes these are faked.
When your test calls more than one class, it's an integration test.
Full test suites can take a long time to run, so after a change many teams run some quick to complete tests to detect significant breakages. For example, you have broken the URIs to essential resources. These are the smoke tests.
Regression tests run on every build and allow you to refactor effectively by catching what you break. Any kind of test can be regression test, but I find unit tests are most helpful finding the source of fault.
This formulation of the LSP is way too strong:
If for each object o1 of type S there is an object o2 of type T such that for all programs P de?ned in terms of T, the behavior of P is unchanged when o1 is substituted for o2, then S is a subtype of T.
Which basically means that S is another, completely encapsulated implementation of the exact same thing as T. And I could be bold and decide that performance is part of the behavior of P...
So, basically, any use of late-binding violates the LSP. It's the whole point of OO to to obtain a different behavior when we substitute an object of one kind for one of another kind!
The formulation cited by wikipedia is better since the property depends on the context and does not necessarily include the whole behavior of the program.
It is hard to keep track of what is happening with loops. Loops which don't terminate or terminate without achieving their goal behavior is a common problem in computer programming. Loop invariants help. A loop invariant is a formal statement about the relationship between variables in your program which holds true just before the loop is ever run (establishing the invariant) and is true again at the bottom of the loop, each time through the loop (maintaining the invariant). Here is the general pattern of the use of Loop Invariants in your code:
...
// the Loop Invariant must be true here
while ( TEST CONDITION ) {
// top of the loop
...
// bottom of the loop
// the Loop Invariant must be true here
}
// Termination + Loop Invariant = Goal
...
Between the top and bottom of the loop, headway is presumably being made towards reaching the loop's goal. This might disturb (make false) the invariant. The point of Loop Invariants is the promise that the invariant will be restored before repeating the loop body each time.
There are two advantages to this:
Work is not carried forward to the next pass in complicated, data dependent ways. Each pass through the loop in independent of all others, with the invariant serving to bind the passes together into a working whole. Reasoning that your loop works is reduced to reasoning that the loop invariant is restored with each pass through the loop. This breaks the complicated overall behavior of the loop into small simple steps, each which can be considered separately. The test condition of the loop is not part of the invariant. It is what makes the loop terminate. You consider separately two things: why the loop should ever terminate, and why the loop achieves its goal when it terminates. The loop will terminate if each time through the loop you move closer to satisfying the termination condition. It is often easy to assure this: e.g. stepping a counter variable by one until it reaches a fixed upper limit. Sometimes the reasoning behind termination is more difficult.
The loop invariant should be created so that when the condition of termination is attained, and the invariant is true, then the goal is reached:
invariant + termination => goal
It takes practice to create invariants which are simple and relate which capture all of goal attainment except for termination. It is best to use mathematical symbols to express loop invariants, but when this leads to over-complicated situations, we rely on clear prose and common-sense.
You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).
http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx
But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends
http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx
Your code also seems a bit strange, like you are nesting lists?
Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.
Define variable with var
outside the function (and of course before it) and then assign 10
to it inside function:
var value;
$(function() {
value = "10";
});
console.log(value); // 10
Note that you shouldn't omit the first line in this code (var value;
), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;
) and assigning value to a variable (variable = value;
) are two different things. You can't assign value to variable that you haven't defined.
It might be irrelevant here, but $(function() {})
is a shortcut for $(document).ready(function() {})
, which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined
until it has loaded, so console.log(value);
placed right after $(function() {})
will return undefined
. In other words, it would execute in following order:
var value;
console.log(value);
value = "10";
See also:
NUnit loads the unit tests in a seperate AppDomain, and I assume the entry point is not being called (probably not needed), hence the entry assembly is null.
select pg_get_viewdef('viewname', true)
A list of all those functions is available in the manual:
http://www.postgresql.org/docs/current/static/functions-info.html
I will explain you this with a practical example and no theory stuff:
A developer writes the code. No GUI is implemented yet. The testing at this level verifies that the functions work correctly and the data types are correct. This phase of testing is called Unit testing.
When a GUI is developed, and application is assigned to a tester, he verifies business requirements with a client and executes the different scenarios. This is called functional testing. Here we are mapping the client requirements with application flows.
Integration testing: let's say our application has two modules: HR and Finance. HR module was delivered and tested previously. Now Finance is developed and is available to test. The interdependent features are also available now, so in this phase, you will test communication points between the two and will verify they are working as requested in requirements.
Regression testing is another important phase, which is done after any new development or bug fixes. Its aim is to verify previously working functions.
Actually I don't think that there is a lot in common between them. Some algorithm use heuristics in their logic (often to make fewer calculations or get faster results). Usually heuristics are used in the so called greedy algorithms.
Heuristics is some "knowledge" that we assume is good to use in order to get the best choice in our algorithm (when a choice should be taken). For example ... a heuristics in chess could be (always take the opponents' queen if you can, since you know this is the stronger figure). Heuristics do not guarantee you that will lead you to the correct answer, but (if the assumptions is correct) often get answer which are close to the best in much shorter time.
Both are equivalent. Take a look at the following:
int[] array;
// is equivalent to
int array[];
int var, array[];
// is equivalent to
int var;
int[] array;
int[] array1, array2[];
// is equivalent to
int[] array1;
int[][] array2;
public static int[] getArray()
{
// ..
}
// is equivalent to
public static int getArray()[]
{
// ..
}
Just change the ADD to MODIFY and it will works !
Replace
ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT
To
ALTER TABLE users MODIFY id int NOT NULL AUTO_INCREMENT;
Interface is a contract you should comply to or given to, depending if you are implementer or a user.
Personally, I like this one:
"The designer is concerned with what happens when a user presses a button, and the architect is concerned with what happens when ten thousand users press a button."
SCEA for Java™ EE Study Guide by Mark Cade and Humphrey Sheil
To sum it up,in object oriented programming, everything is modeled into classes and objects. Classes contain properties and methods. Public, private and protected keywords are used to specify access to these members(properties and methods) of a class from other classes or other .dlls or even other applications.
I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format
<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here
I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o
file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!
the thing that you assert on it,is called a mock object and everything else that just helped the test run, is a stub.
A good example of understanding an idempotent operation might be locking a car with remote key.
log(Car.state) // unlocked
Remote.lock();
log(Car.state) // locked
Remote.lock();
Remote.lock();
Remote.lock();
log(Car.state) // locked
lock
is an idempotent operation. Even if there are some side effect each time you run lock
, like blinking, the car is still in the same locked state, no matter how many times you run lock operation.
"Hard Coding" means something that you want to embeded with your program or any project that can not be changed directly. For example if you are using a database server, then you must hardcode to connect your database with your project and that can not be changed by user. Because you have hard coded.
y-combinator in JavaScript:
var Y = function(f) {
return (function(g) {
return g(g);
})(function(h) {
return function() {
return f(h(h)).apply(null, arguments);
};
});
};
var factorial = Y(function(recurse) {
return function(x) {
return x == 0 ? 1 : x * recurse(x-1);
};
});
factorial(5) // -> 120
Edit: I learn a lot from looking at code, but this one is a bit tough to swallow without some background - sorry about that. With some general knowledge presented by other answers, you can begin to pick apart what is happening.
The Y function is the "y-combinator". Now take a look at the var factorial
line where Y is used. Notice you pass a function to it that has a parameter (in this example, recurse
) that is also used later on in the inner function. The parameter name basically becomes the name of the inner function allowing it to perform a recursive call (since it uses recurse()
in it's definition.) The y-combinator performs the magic of associating the otherwise anonymous inner function with the parameter name of the function passed to Y.
For the full explanation of how Y does the magic, checked out the linked article (not by me btw.)
Let me explain the difference between process and threads first.
A process can have {1..N} number of threads. A small explanation on virtual memory and virtual processor.
Virtual memory
Used as a swap space so that a process thinks that it is sitting on the primary memory for execution.
Virtual processor
The same concept as virtual memory except this is for processor. To a process, it will look it's the only thing that is using the processor.
OS will take care of allocating the virtual memory and virtual processor to a process and performing the swap between processes and doing execution.
All the threads within a process will share the same virtual memory. But, each thread will have their individual virtual processor assigned to them so that they can be executed individually.
Thus saving the memory as well as utilizing the CPU to its potential.
Here is a highly simplified but hopefully relevant view of what happens when you build your code in C++.
C++ splits the load of generating machine executable code in following different phases -
Preprocessing - This is where any macros - #define
s etc you might be using get expanded.
Compiling - Each cpp file along with all the #include
d files in that file directly or indirectly (together called a compilation unit) is converted into machine readable object code.
This is where C++ also checks that all functions defined (i.e. containing a body in {
}
e.g.
void Foo( int x){ return Boo(x); })
are referring to other functions in a valid manner.
The way it does that is by insisting that you provide at least a declaration of these other functions (e.g. void Boo(int);
) before you call it so it can check that you are calling it properly among other things. This can be done either directly in the cpp file where it is called or usually in an included header file.
Note that only the machine code that corresponds to functions defined in this cpp and included files gets built as the object (binary) version of this compilation unit (e.g. Foo) and not the ones that are merely declared (e.g. Boo).
Linking - This is the stage where C++ goes hunting for stuff declared and called in each compilation unit and links it to the places where it is getting called. Now if there was no definition found of this function the linker gives up and errors out. Similarly if it finds multiple definitions of the same function signature (essentially the name and parameter types it takes) it also errors out as it considers it ambiguous and doesn't want to pick one arbitrarily.
The latter is what is happening in your case. By doing a #include
of the fun.cpp
file, both fun.cpp
and mainfile.cpp
have a definition of funct()
and the linker doesn't know which one to use in your program and is complaining about it.
The fix as Vaughn mentioned above is to not include the cpp file with the definition of funct()
in mainfile.cpp
and instead move the declaration of funct()
in a separate header file and include that in mainline.cpp
. This way the compiler will get the declaration of funct()
to work with and the linker would get just one definition of funct()
from fun.cpp
and will use it with confidence.
To add to the other answers, I think the acronyms were derived to show a scale between the two terms to distinguish how reliable transactions or requests where between RDMS versus Big Data.
From this article acid vs base
In Chemistry, pH measures the relative basicity and acidity of an aqueous (solvent in water) solution. The pH scale extends from 0 (highly acidic substances such as battery acid) to 14 (highly alkaline substances like lie); pure water at 77° F (25° C) has a pH of 7 and is neutral.
Data engineers have cleverly borrowed acid vs base from chemists and created acronyms that while not exact in their meanings, are still apt representations of what is happening within a given database system when discussing the reliability of transaction processing.
One other point, since I work with Big Data using Elasticsearch. To clarify, an instance of Elasticsearch is a node and a group of nodes form a cluster.
To me from a practical standpoint, BA (Basically Available), in this context, has the idea of multiple master nodes to handle the Elasticsearch cluster and it's operations.
If you have 3 master nodes and the currently directing master node goes down, the system stays up, albeit in a less efficient state, and another master node takes its place as the main directing master node. If two master nodes go down, the system still stays up and the last master node takes over.
More on schemas:
In SQL 2005 a schema is a way to group objects. It is a container you can put objects into. People can own this object. You can grant rights on the schema.
In 2000 a schema was equivalent to a user. Now it has broken free and is quite useful. You could throw all your user procs in a certain schema and your admin procs in another. Grant EXECUTE to the appropriate user/role and you're through with granting EXECUTE on specific procedures. Nice.
The dot notation would go like this:
Server.Database.Schema.Object
or
myserver01.Adventureworks.Accounting.Beans
There are valid differences between types of architects:
Enterprise architects look at solutions for the enterprise aligining tightly with the enterprise strategy. Eg in a bank, they'll look at the complete IT landscape.
Solution architects focus on a particular solution, for example a new credit card acquiring system in a bank.
Domain architects focus on specific areas, for example an application architect or network architect.
Technical architects generally play the role of solution architects with less focus on the business aspect and more on the techology aspect.
There is, alas, another use of "upstream" that the other answers here are not getting at, namely to refer to the parent-child relationship of commits within a repo. Scott Chacon in the Pro Git book is particularly prone to this, and the results are unfortunate. Do not imitate this way of speaking.
For example, he says of a merge resulting a fast-forward that this happens because
the commit pointed to by the branch you merged in was directly upstream of the commit you’re on
He wants to say that commit B is the only child of the only child of ... of the only child of commit A, so to merge B into A it is sufficient to move the ref A to point to commit B. Why this direction should be called "upstream" rather than "downstream", or why the geometry of such a pure straight-line graph should be described "directly upstream", is completely unclear and probably arbitrary. (The man page for git-merge
does a far better job of explaining this relationship when it says that "the current branch head is an ancestor of the named commit." That is the sort of thing Chacon should have said.)
Indeed, Chacon himself appears to use "downstream" later to mean exactly the same thing, when he speaks of rewriting all child commits of a deleted commit:
You must rewrite all the commits downstream from 6df76 to fully remove this file from your Git history
Basically he seems not to have any clear idea what he means by "upstream" and "downstream" when referring to the history of commits over time. This use is informal, then, and not to be encouraged, as it is just confusing.
It is perfectly clear that every commit (except one) has at least one parent, and that parents of parents are thus ancestors; and in the other direction, commits have children and descendants. That's accepted terminology, and describes the directionality of the graph unambiguously, so that's the way to talk when you want to describe how commits relate to one another within the graph geometry of a repo. Do not use "upstream" or "downstream" loosely in this situation.
[Additional note: I've been thinking about the relationship between the first Chacon sentence I cite above and the git-merge
man page, and it occurs to me that the former may be based on a misunderstanding of the latter. The man page does go on to describe a situation where the use of "upstream" is legitimate: fast-forwarding often happens when "you are tracking an upstream repository, you have committed no local changes, and now you want to update to a newer upstream revision." So perhaps Chacon used "upstream" because he saw it here in the man page. But in the man page there is a remote repository; there is no remote repository in Chacon's cited example of fast-forwarding, just a couple of locally created branches.]
Boilerplate definition is becoming more global in many other programming languages nowadays. It comes from OOP and hybrid languages that have become OOP and were before procedual have now the same goal to keep repeating the code you build with a model/template/class/object hence why they adapt this term. You make a template and the only things you do for each instance of a template are the parameters to individualize an object this part is what we call boilerplate. You simply re-use the code you made a template of, just with different parameters.
Synonyms
a blueprint is a boilerplate
a stencil is a boilerplate
a footer is a boilerplate
a design pattern for multiple use is a boilerplate
a signature of a mail is a boilerplate
Tuple is used to refer to a row in a relational database model. But tuple has little bit difference with row.
Another way to do this, for integer types anyway, is to define constants as enums in the class:
class test
{
public:
enum { N = 10 };
};
What is API Testing?
API testing utilizes programming to send calls to the API and get the yield. It testing regards the segment under test as a black box. The objective of API testing is to confirm right execution and blunder treatment of the part preceding its coordination into an application.
REST API
REST: Representational State Transfer.
4 Commonly Used API Methods:-
Steps to Test API Manually:-
To use API manually, we can use browser based REST API plugins.
Currying is one of the higher-order functions of Java Script.
Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.
Confused?
Let see an example,
function add(a,b)
{
return a+b;
}
add(5,6);
This is similar to the following currying function,
function add(a)
{
return function(b){
return a+b;
}
}
var curryAdd = add(5);
curryAdd(6);
So what does this code means?
Now read the definition again,
Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.
Still, Confused? Let me explain in deep!
When you call this function,
var curryAdd = add(5);
It will return you a function like this,
curryAdd=function(y){return 5+y;}
So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script. So come back to the currying,
This line will pass the second argument to the curryAdd function.
curryAdd(6);
which in turns results,
curryAdd=function(6){return 5+6;}
// Which results in 11
Hope you understand the usage of currying here. So, Coming to the advantages,
Why Currying?
It makes use of code reusability. Less code, Less Error. You may ask how it is less code?
I can prove it with ECMA script 6 new feature arrow functions.
Yes! ECMA 6, provide us with the wonderful feature called arrow functions,
function add(a)
{
return function(b){
return a+b;
}
}
With the help of the arrow function, we can write the above function as follows,
x=>y=>x+y
Cool right?
So, Less Code and Fewer bugs!!
With the help of these higher-order function one can easily develop a bug-free code.
I challenge you!
Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.
Thanks, Have a nice day!
In past projects I worked on, the endpoint was a relative property. That is to say it may or may not have been appended to, but it always contained the protocol://host:port/partOfThePath
.
If the service being called had a dynamic part to it, for example a ?param=dynamicValue
, then that part would get added to the endpoint. But many times the endpoint could be used as is without having to be amended.
Whats important to understand is what an endpoint is not and how it helps. For example an alternative way to pass the information stored in an endpoint would be to store the different parts of the endpoint in separate properties. For example:
hostForServiceA=someIp
portForServiceA=8080
pathForServiceA=/some/service/path
hostForServiceB=someIp
portForServiceB=8080
pathForServiceB=/some/service/path
Or if the same host and port across multiple services:
host=someIp
port=8080
pathForServiceA=/some/service/path
pathForServiceB=/some/service/path
In those cases the full URL would need to be constructed in your code as such:
String url = "http://" + host + ":" + port + pathForServiceA + "?" + dynamicParam + "=" + dynamicValue;
In contract this can be stored as an endpoint as such
serviceAEndpoint=http://host:port/some/service/path?dynamicParam=
And yes many times we stored the endpoint up to and including the '='. This lead to code like this:
String url = serviceAEndpoint + dynamicValue;
Hope that sheds some light.
Here it is:
s = "123"
try:
i = int(s)
except ValueError as verr:
pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
pass # do job to handle: Exception occurred while converting to int
I you send passwords to users in an email, you might as well have no passwords at all.
You cannot reverse the MD5 function, so your only option is to generate a new password and send that to the user (preferably over some secure channel).
import types
import yourmodule
print([getattr(yourmodule, a) for a in dir(yourmodule)
if isinstance(getattr(yourmodule, a), types.FunctionType)])
Location is a struct. If there aren't any convenience members, you'll need to reassign the entire Location:
this.balancePanel.Location = new Point(
this.optionsPanel.Location.X,
this.balancePanel.Location.Y);
Most structs are also immutable, but in the rare (and confusing) case that it is mutable, you can also copy-out, edit, copy-in;
var loc = this.balancePanel.Location;
loc.X = this.optionsPanel.Location.X;
this.balancePanel.Location = loc;
Although I don't recommend the above, since structs should ideally be immutable.
Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.
Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.
In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.
Option Explicit
Sub test()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A1:IV65536"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Code goes here for whatever it is you want to do.
End If
Next iCol
Next iRow
End Sub
To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:
Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need
This is another option to write a pandas dataframe directly into a matplotlib table:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')
df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
ax.table(cellText=df.values, colLabels=df.columns, loc='center')
fig.tight_layout()
plt.show()
I had a similar problem, in my case the solution was a one liner which works even if the keys aren't symbols, but you need to have the criteria keys in an array
criteria_array = [:choice1, :choice2]
params.select { |k,v| criteria_array.include?(k) } #=> { :choice1 => "Oh look another one",
:choice2 => "Even more strings" }
Another example
criteria_array = [1, 2, 3]
params = { 1 => "A String",
17 => "Oh look, another one",
25 => "Even more strings",
49 => "But wait",
105 => "The last string" }
params.select { |k,v| criteria_array.include?(k) } #=> { 1 => "A String"}
First you have to click on the report, Then View -> Report Data
If you don't give an aspect
argument to imshow
, it will use the value for image.aspect
in your matplotlibrc
. The default for this value in a new matplotlibrc
is equal
.
So imshow
will plot your array with equal aspect ratio.
If you don't need an equal aspect you can set aspect
to auto
imshow(random.rand(8, 90), interpolation='nearest', aspect='auto')
which gives the following figure
If you want an equal aspect ratio you have to adapt your figsize
according to the aspect
fig, ax = subplots(figsize=(18, 2))
ax.imshow(random.rand(8, 90), interpolation='nearest')
tight_layout()
which gives you:
The below code gives you the simple extrapolation module. k is the value to which the data set y has to be extrapolated based on the data set x. The numpy
module is required.
def extrapol(k,x,y):
xm=np.mean(x);
ym=np.mean(y);
sumnr=0;
sumdr=0;
length=len(x);
for i in range(0,length):
sumnr=sumnr+((x[i]-xm)*(y[i]-ym));
sumdr=sumdr+((x[i]-xm)*(x[i]-xm));
m=sumnr/sumdr;
c=ym-(m*xm);
return((m*k)+c)
I agree with using the ?? operator.
If you're dealing with strings use if(String.IsNullOrEmpty(myStr))
This is now IsEnabled
takePicturebutton.IsEnabled = false; // true
You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.
Turn the EXISTS clause into a subquery instead within an IF function
SELECT IF( EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?), 1, 0)
In fact, booleans are returned as 1 or 0
SELECT EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?)
Create the macro as here:
On the Tools menu in Microsoft Excel, point to Macro, and then click Visual Basic Editor. On the Insert menu, click Module. Copy and paste this code into the code window of the module. It will automatically name itself HyperAdd.
Sub HyperAdd()
'Converts each text hyperlink selected into a working hyperlink
For Each xCell In Selection
ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=xCell.Formula
Next xCell
End Sub
When you're finished pasting your macro, click Close and Return to Microsoft Excel on the File menu.
Then select the required cells and click macro and click run.
NOTE Do NOT select the whole column! Select ONLY the cells you wish to be changed to clickable links else you will end up in a neverending loop and have to restart Excel! Done!
When you
import App from './App.jsx';
That means it will import whatever you export default
. You can rename App
class inside App.jsx
to whatever you want as long as you export default
it will work but you can only have one export default.
So you only need to export default App
and you don't need to export the rest.
If you still want to export the rest of the components, you will need named export.
https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export
JavaScript Pure:
<script type="text/javascript">
document.getElementById("modal").click();
</script>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#modal").trigger('click');
});
</script>
or
<script type="text/javascript">
$(document).ready(function(){
$("#modal").click();
});
</script>
If you have proportioned elements, you could use:
.valid {
background-position: 98% center;
}
.half .valid {
background-position: 96% center;
}
In this example, .valid
would be the class with the picture and .half
would be a row with half the size of the standard one.
Dirty, but works as a charm and it's reasonably manageable.
Below code works for me:
<input id="myDatePicker" class="readonlyjm"/>
$('#myDatePicker').datepicker({
/* options */
});
$('.readonlyjm').on('focus',function(){
$(this).trigger('blur');
});
Apparently YouTube constantly polls for Google Cast scripts even if the extension isn't installed.
From one commenter:
... it appears that Chrome attempts to get cast_sender.js on pages that have YouTube content. I'm guessing when Chrome sees media that it can stream it attempts to access the Chromecast extension. When the extension isn't present, the error is thrown.
The only solution I've come across is to install the Google Cast extension, whether you need it or not. You may then hide the toolbar button.
For more information and updates, see this SO question. Here's the official issue.
this worked for me , in this way we setting the default value to empty string
@Html.TextBoxFor(m => m.Id, new { @Value = "" })
With Bootstrap 4, there is a css class specifically for this. The below will center row content:
<div class="row justify-content-center">
...inner divs and content...
</div>
See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.
I am looking for a way to create a select without repeating the conditional query.
I'm assuming that you don't want to repeat Foo-stuff+bar
. You could put your calculation into a derived table:
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a
A common table expression would work just as well:
WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM a
Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.
I am generally using the way posted by Barry Wark and Rahul Gupta.
Although, I do not like repeating the same words in both .h and .m file. Note, that in the following example the line is almost identical in both files:
// file.h
extern NSString* const MyConst;
//file.m
NSString* const MyConst = @"Lorem ipsum";
Therefore, what I like to do is to use some C preprocessor machinery. Let me explain through the example.
I have a header file which defines the macro STR_CONST(name, value)
:
// StringConsts.h
#ifdef SYNTHESIZE_CONSTS
# define STR_CONST(name, value) NSString* const name = @ value
#else
# define STR_CONST(name, value) extern NSString* const name
#endif
The in my .h/.m pair where I want to define the constant I do the following:
// myfile.h
#import <StringConsts.h>
STR_CONST(MyConst, "Lorem Ipsum");
STR_CONST(MyOtherConst, "Hello world");
// myfile.m
#define SYNTHESIZE_CONSTS
#import "myfile.h"
et voila, I have all the information about the constants in .h file only.
Typically, you'd use a built-in layout control appropriate for your scenario (e.g. use a grid as a parent if you want scaling relative to the parent). If you want to do it with an arbitrary parent element, you can create a ValueConverter do it, but it probably won't be quite as clean as you'd like. However, if you absolutely need it, you could do something like this:
public class PercentageConverter : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
return System.Convert.ToDouble(value) *
System.Convert.ToDouble(parameter);
}
public object ConvertBack(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Which can be used like this, to get a child textbox 10% of the width of its parent canvas:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<local:PercentageConverter x:Key="PercentageConverter"/>
</Window.Resources>
<Canvas x:Name="canvas">
<TextBlock Text="Hello"
Background="Red"
Width="{Binding
Converter={StaticResource PercentageConverter},
ElementName=canvas,
Path=ActualWidth,
ConverterParameter=0.1}"/>
</Canvas>
</Window>
To add a little to @Bakuriu's answer:
If you already know where the warning is likely to occur then it's often cleaner to use the numpy.errstate
context manager, rather than numpy.seterr
which treats all subsequent warnings of the same type the same regardless of where they occur within your code:
import numpy as np
a = np.r_[1.]
with np.errstate(divide='raise'):
try:
a / 0 # this gets caught and handled as an exception
except FloatingPointError:
print('oh no!')
a / 0 # this prints a RuntimeWarning as usual
In my original example I had a = np.r_[0]
, but apparently there was a change in numpy's behaviour such that division-by-zero is handled differently in cases where the numerator is all-zeros. For example, in numpy 1.16.4:
all_zeros = np.array([0., 0.])
not_all_zeros = np.array([1., 0.])
with np.errstate(divide='raise'):
not_all_zeros / 0. # Raises FloatingPointError
with np.errstate(divide='raise'):
all_zeros / 0. # No exception raised
with np.errstate(invalid='raise'):
all_zeros / 0. # Raises FloatingPointError
The corresponding warning messages are also different: 1. / 0.
is logged as RuntimeWarning: divide by zero encountered in true_divide
, whereas 0. / 0.
is logged as RuntimeWarning: invalid value encountered in true_divide
. I'm not sure why exactly this change was made, but I suspect it has to do with the fact that the result of 0. / 0.
is not representable as a number (numpy returns a NaN in this case) whereas 1. / 0.
and -1. / 0.
return +Inf and -Inf respectively, per the IEE 754 standard.
If you want to catch both types of error you can always pass np.errstate(divide='raise', invalid='raise')
, or all='raise'
if you want to raise an exception on any kind of floating point error.
I also don't like using a function to handle a property which has been resolved again and again in every controller and service. Seem I'm not alone :D
Don't tried to get result with a promise as a variable, of course no way. But I found and use a solution below to access to the result as a property.
Firstly, write result to a property of your service:
app.factory('your_factory',function(){
var theParentIdResult = null;
var factoryReturn = {
theParentId: theParentIdResult,
addSiteParentId : addSiteParentId
};
return factoryReturn;
function addSiteParentId(nodeId) {
var theParentId = 'a';
var parentId = relationsManagerResource.GetParentId(nodeId)
.then(function(response){
factoryReturn.theParentIdResult = response.data;
console.log(theParentId); // #1
});
}
})
Now, we just need to ensure that method addSiteParentId
always be resolved before we accessed to property theParentId
. We can achieve this by using some ways.
Use resolve in router method:
resolve: {
parentId: function (your_factory) {
your_factory.addSiteParentId();
}
}
then in controller and other services used in your router, just call your_factory.theParentId to get your property. Referce here for more information: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx
Use run
method of app to resolve your service.
app.run(function (your_factory) { your_factory.addSiteParentId(); })
Inject it in the first controller or services of the controller. In the controller we can call all required init services. Then all remain controllers as children of main controller can be accessed to this property normally as you want.
Chose your ways depend on your context depend on scope of your variable and reading frequency of your variable.
How was the database exported?
If it was exported using exp
and a full schema was exported, then
Create the user:
create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
Grant the rights:
grant connect, create session, imp_full_database to <username>;
Start the import with imp
:
imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
If it was exported using expdp
, then start the import with impdp
:
impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp
file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\
).
Either move the export file to the above path or create a directory object to pointing to the path where the dmp
file is present and pass the object name to the impdp
command above.
EDIT As jirassimok has mentioned below my function will change the data in place, after that it runs a lot faster in timeit. This causes the good results. It's some kind of cheating. Sorry for your inconvenience.
I found a faster method for ReLU with numpy. You can use the fancy index feature of numpy as well.
fancy index:
20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> x = np.random.random((5,5)) - 0.5
>>> x
array([[-0.21444316, -0.05676216, 0.43956365, -0.30788116, -0.19952038],
[-0.43062223, 0.12144647, -0.05698369, -0.32187085, 0.24901568],
[ 0.06785385, -0.43476031, -0.0735933 , 0.3736868 , 0.24832288],
[ 0.47085262, -0.06379623, 0.46904916, -0.29421609, -0.15091168],
[ 0.08381359, -0.25068492, -0.25733763, -0.1852205 , -0.42816953]])
>>> x[x<0]=0
>>> x
array([[ 0. , 0. , 0.43956365, 0. , 0. ],
[ 0. , 0.12144647, 0. , 0. , 0.24901568],
[ 0.06785385, 0. , 0. , 0.3736868 , 0.24832288],
[ 0.47085262, 0. , 0.46904916, 0. , 0. ],
[ 0.08381359, 0. , 0. , 0. , 0. ]])
Here is my benchmark:
import numpy as np
x = np.random.random((5000, 5000)) - 0.5
print("max method:")
%timeit -n10 np.maximum(x, 0)
print("max inplace method:")
%timeit -n10 np.maximum(x, 0,x)
print("multiplication method:")
%timeit -n10 x * (x > 0)
print("abs method:")
%timeit -n10 (abs(x) + x) / 2
print("fancy index:")
%timeit -n10 x[x<0] =0
max method:
241 ms ± 3.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
max inplace method:
38.5 ms ± 4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
multiplication method:
162 ms ± 3.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
abs method:
181 ms ± 4.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
fancy index:
20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Controller
public ActionResult Index()
{
//you don't need to include the category bc it does it by itself
//var model = db.Product.Include(c => c.Category).ToList()
ViewBag.Categories = db.Category.OrderBy(c => c.Name).ToList();
var model = db.Product.ToList()
return View(model);
}
View
you need to filter the model with the given category
like :=> Model.where(p=>p.CategoryID == category.CategoryID)
try this...
@foreach (var category in ViewBag.Categories)
{
<h3><u>@category.Name</u></h3>
<div>
@foreach (var product in Model.where(p=>p.CategoryID == category.CategoryID))
{
<table cellpadding="5" cellspacing"5" style="border:1px solid black; width:100%;background-color:White;">
<thead>
<tr>
<th style="background-color:black; color:white;">
@product.Title
@if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
{
@Html.Raw(" - ")
@Html.ActionLink("Edit", "Edit", new { id = product.ID }, new { style = "background-color:black; color:white !important;" })
}
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="background-color:White;">
@product.Description
</td>
</tr>
</tbody>
</table>
}
</div>
}
Update: Corrected map rendering algorithm, added more illustrations, changed formating.
Perhaps the advantage for the "zig-zag" technique for mapping the tiles to the screen can be said that the tile's x
and y
coordinates are on the vertical and horizontal axes.
"Drawing in a diamond" approach:
By drawing an isometric map using "drawing in a diamond", which I believe refers to just rendering the map by using a nested for
-loop over the two-dimensional array, such as this example:
tile_map[][] = [[...],...]
for (cellY = 0; cellY < tile_map.size; cellY++):
for (cellX = 0; cellX < tile_map[cellY].size cellX++):
draw(
tile_map[cellX][cellY],
screenX = (cellX * tile_width / 2) + (cellY * tile_width / 2)
screenY = (cellY * tile_height / 2) - (cellX * tile_height / 2)
)
Advantage:
The advantage to the approach is that it is a simple nested for
-loop with fairly straight forward logic that works consistently throughout all tiles.
Disadvantage:
One downside to that approach is that the x
and y
coordinates of the tiles on the map will increase in diagonal lines, which might make it more difficult to visually map the location on the screen to the map represented as an array:
However, there is going to be a pitfall to implementing the above example code -- the rendering order will cause tiles that are supposed to be behind certain tiles to be drawn on top of the tiles in front:
In order to amend this problem, the inner for
-loop's order must be reversed -- starting from the highest value, and rendering toward the lower value:
tile_map[][] = [[...],...]
for (i = 0; i < tile_map.size; i++):
for (j = tile_map[i].size; j >= 0; j--): // Changed loop condition here.
draw(
tile_map[i][j],
x = (j * tile_width / 2) + (i * tile_width / 2)
y = (i * tile_height / 2) - (j * tile_height / 2)
)
With the above fix, the rendering of the map should be corrected:
"Zig-zag" approach:
Advantage:
Perhaps the advantage of the "zig-zag" approach is that the rendered map may appear to be a little more vertically compact than the "diamond" approach:
Disadvantage:
From trying to implement the zig-zag technique, the disadvantage may be that it is a little bit harder to write the rendering code because it cannot be written as simple as a nested for
-loop over each element in an array:
tile_map[][] = [[...],...]
for (i = 0; i < tile_map.size; i++):
if i is odd:
offset_x = tile_width / 2
else:
offset_x = 0
for (j = 0; j < tile_map[i].size; j++):
draw(
tile_map[i][j],
x = (j * tile_width) + offset_x,
y = i * tile_height / 2
)
Also, it may be a little bit difficult to try to figure out the coordinate of a tile due to the staggered nature of the rendering order:
Note: The illustrations included in this answer were created with a Java implementation of the tile rendering code presented, with the following int
array as the map:
tileMap = new int[][] {
{0, 1, 2, 3},
{3, 2, 1, 0},
{0, 0, 1, 1},
{2, 2, 3, 3}
};
The tile images are:
tileImage[0] ->
A box with a box inside.tileImage[1] ->
A black box.tileImage[2] ->
A white box.tileImage[3] ->
A box with a tall gray object in it.A Note on Tile Widths and Heights
The variables tile_width
and tile_height
which are used in the above code examples refer to the width and height of the ground tile in the image representing the tile:
Using the dimensions of the image will work, as long as the image dimensions and the tile dimensions match. Otherwise, the tile map could be rendered with gaps between the tiles.
You can use property dangerouslySetInnerHTML
, like this
const Component = React.createClass({_x000D_
iframe: function () {_x000D_
return {_x000D_
__html: this.props.iframe_x000D_
}_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
<Component iframe={iframe} />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe>
tag and pass it to new <iframe>
tag, like that
/**_x000D_
* getAttrs_x000D_
* returns all attributes from TAG string_x000D_
* @return Object_x000D_
*/_x000D_
const getAttrs = (iframeTag) => {_x000D_
var doc = document.createElement('div');_x000D_
doc.innerHTML = iframeTag;_x000D_
_x000D_
const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
return [].slice_x000D_
.call(iframe.attributes)_x000D_
.reduce((attrs, element) => {_x000D_
attrs[element.name] = element.value;_x000D_
return attrs;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<iframe {...getAttrs(this.props.iframe) } />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
<Component iframe={iframe} />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
Note that in the above C++ solutions, there was some problems.
One solution was inefficient because it passed an std::string by copy, and because it iterated over all the chars, instead of comparing only half the chars. Then, even when discovering the string was not a palindrome, it continued the loop, waiting its end before reporting "false".
The other was better, with a very small function, whose problem was that it was not able to test anything else than std::string. In C++, it is easy to extend an algorithm to a whole bunch of similar objects. By templating its std::string into "T", it would have worked on both std::string, std::wstring, std::vector and std::deque. But without major modification because of the use of the operator <, the std::list was out of its scope.
My own solutions try to show that a C++ solution won't stop at working on the exact current type, but will strive to work an anything that behaves the same way, no matter the type. For example, I could apply my palindrome tests on std::string, on vector of int or on list of "Anything" as long as Anything was comparable through its operator = (build in types, as well as classes).
Note that the template can even be extended with an optional type that can be used to compare the data. For example, if you want to compare in a case insensitive way, or even compare similar characters (like è, é, ë, ê and e).
Like king Leonidas would have said: "Templates ? This is C++ !!!"
So, in C++, there are at least 3 major ways to do it, each one leading to the other:
The problem is that until C++0X, we can't consider the std::string array of chars as contiguous, so we must "cheat" and retrieve the c_str() property. As we are using it in a read-only fashion, it should be ok...
bool isPalindromeA(const std::string & p_strText)
{
if(p_strText.length() < 2) return true ;
const char * pStart = p_strText.c_str() ;
const char * pEnd = pStart + p_strText.length() - 1 ;
for(; pStart < pEnd; ++pStart, --pEnd)
{
if(*pStart != *pEnd)
{
return false ;
}
}
return true ;
}
Now, we'll try to apply the same solution, but to any C++ container with random access to its items through operator []. For example, any std::basic_string, std::vector, std::deque, etc. Operator [] is constant access for those containers, so we won't lose undue speed.
template <typename T>
bool isPalindromeB(const T & p_aText)
{
if(p_aText.empty()) return true ;
typename T::size_type iStart = 0 ;
typename T::size_type iEnd = p_aText.size() - 1 ;
for(; iStart < iEnd; ++iStart, --iEnd)
{
if(p_aText[iStart] != p_aText[iEnd])
{
return false ;
}
}
return true ;
}
It will work with almost any unordered STL-like container with bidirectional iterators For example, any std::basic_string, std::vector, std::deque, std::list, etc. So, this function can be applied on all STL-like containers with the following conditions: 1 - T is a container with bidirectional iterator 2 - T's iterator points to a comparable type (through operator =)
template <typename T>
bool isPalindromeC(const T & p_aText)
{
if(p_aText.empty()) return true ;
typename T::const_iterator pStart = p_aText.begin() ;
typename T::const_iterator pEnd = p_aText.end() ;
--pEnd ;
while(true)
{
if(*pStart != *pEnd)
{
return false ;
}
if((pStart == pEnd) || (++pStart == pEnd))
{
return true ;
}
--pEnd ;
}
}
Without using TextInfo
:
public static string TitleCase(this string text, char seperator = ' ') =>
string.Join(seperator, text.Split(seperator).Select(word => new string(
word.Select((letter, i) => i == 0 ? char.ToUpper(letter) : char.ToLower(letter)).ToArray())));
It loops through every letter in each word, converting it to uppercase if it's the first letter otherwise converting it to lowercase.
You need nunique
:
df = df.groupby('domain')['ID'].nunique()
print (df)
domain
'facebook.com' 1
'google.com' 1
'twitter.com' 2
'vk.com' 3
Name: ID, dtype: int64
If you need to strip
'
characters:
df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com 1
google.com 1
twitter.com 2
vk.com 3
Name: ID, dtype: int64
Or as Jon Clements commented:
df.groupby(df.domain.str.strip("'"))['ID'].nunique()
You can retain the column name like this:
df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
domain ID
0 fb 1
1 ggl 1
2 twitter 2
3 vk 3
The difference is that nunique()
returns a Series and agg()
returns a DataFrame.
Feb, 2016:
I needed to do this based on client entered database values and without a lat/long generator. Google really likes lat/long these days. Here is what I learned:
1 The beginning of the link looks like this: https://www.google.com/maps/place/
2 Then you put your address:
3 Put the address after the place/
4 Then put a slash at the end.
NOTE: The slash at the end was important. After the user clicks the link, Google goes ahead and appends more to the URL and they do it after this slash.
Working example for this question:
https://www.google.ca/maps/place/1200+Pennsylvania+Ave+SE,+Washington,+DC+20003/
I hope that helps.
Arrays are special objects in java, they have a simple attribute named length
which is final
.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
- The
public
final
fieldlength
, which contains the number of components of the array.length
may be positive or zero.The
public
methodclone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of theclone
method of an array typeT[]
isT[]
.A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
- All the members inherited from class
Object
; the only method ofObject
that is not inherited is itsclone
method.
Resources:
Since this is like a "wikipage of code" I want to add some code from the QNX Knowledge base (note: this is not my work, but I checked it and it works fine on my system):
How to get CPU usage in %: http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5
#include <atomic.h>
#include <libc.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/iofunc.h>
#include <sys/neutrino.h>
#include <sys/resmgr.h>
#include <sys/syspage.h>
#include <unistd.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/debug.h>
#include <sys/procfs.h>
#include <sys/syspage.h>
#include <sys/neutrino.h>
#include <sys/time.h>
#include <time.h>
#include <fcntl.h>
#include <devctl.h>
#include <errno.h>
#define MAX_CPUS 32
static float Loads[MAX_CPUS];
static _uint64 LastSutime[MAX_CPUS];
static _uint64 LastNsec[MAX_CPUS];
static int ProcFd = -1;
static int NumCpus = 0;
int find_ncpus(void) {
return NumCpus;
}
int get_cpu(int cpu) {
int ret;
ret = (int)Loads[ cpu % MAX_CPUS ];
ret = max(0,ret);
ret = min(100,ret);
return( ret );
}
static _uint64 nanoseconds( void ) {
_uint64 sec, usec;
struct timeval tval;
gettimeofday( &tval, NULL );
sec = tval.tv_sec;
usec = tval.tv_usec;
return( ( ( sec * 1000000 ) + usec ) * 1000 );
}
int sample_cpus( void ) {
int i;
debug_thread_t debug_data;
_uint64 current_nsec, sutime_delta, time_delta;
memset( &debug_data, 0, sizeof( debug_data ) );
for( i=0; i<NumCpus; i++ ) {
/* Get the sutime of the idle thread #i+1 */
debug_data.tid = i + 1;
devctl( ProcFd, DCMD_PROC_TIDSTATUS,
&debug_data, sizeof( debug_data ), NULL );
/* Get the current time */
current_nsec = nanoseconds();
/* Get the deltas between now and the last samples */
sutime_delta = debug_data.sutime - LastSutime[i];
time_delta = current_nsec - LastNsec[i];
/* Figure out the load */
Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );
/* Flat out strange rounding issues. */
if( Loads[i] < 0 ) {
Loads[i] = 0;
}
/* Keep these for reference in the next cycle */
LastNsec[i] = current_nsec;
LastSutime[i] = debug_data.sutime;
}
return EOK;
}
int init_cpu( void ) {
int i;
debug_thread_t debug_data;
memset( &debug_data, 0, sizeof( debug_data ) );
/* Open a connection to proc to talk over.*/
ProcFd = open( "/proc/1/as", O_RDONLY );
if( ProcFd == -1 ) {
fprintf( stderr, "pload: Unable to access procnto: %s\n",strerror( errno ) );
fflush( stderr );
return -1;
}
i = fcntl(ProcFd,F_GETFD);
if(i != -1){
i |= FD_CLOEXEC;
if(fcntl(ProcFd,F_SETFD,i) != -1){
/* Grab this value */
NumCpus = _syspage_ptr->num_cpu;
/* Get a starting point for the comparisons */
for( i=0; i<NumCpus; i++ ) {
/*
* the sutime of idle thread is how much
* time that thread has been using, we can compare this
* against how much time has passed to get an idea of the
* load on the system.
*/
debug_data.tid = i + 1;
devctl( ProcFd, DCMD_PROC_TIDSTATUS, &debug_data, sizeof( debug_data ), NULL );
LastSutime[i] = debug_data.sutime;
LastNsec[i] = nanoseconds();
}
return(EOK);
}
}
close(ProcFd);
return(-1);
}
void close_cpu(void){
if(ProcFd != -1){
close(ProcFd);
ProcFd = -1;
}
}
int main(int argc, char* argv[]){
int i,j;
init_cpu();
printf("System has: %d CPUs\n", NumCpus);
for(i=0; i<20; i++) {
sample_cpus();
for(j=0; j<NumCpus;j++)
printf("CPU #%d: %f\n", j, Loads[j]);
sleep(1);
}
close_cpu();
}
How to get the free (!) memory: http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <err.h>
#include <sys/stat.h>
#include <sys/types.h>
int main( int argc, char *argv[] ){
struct stat statbuf;
paddr_t freemem;
stat( "/proc", &statbuf );
freemem = (paddr_t)statbuf.st_size;
printf( "Free memory: %d bytes\n", freemem );
printf( "Free memory: %d KB\n", freemem / 1024 );
printf( "Free memory: %d MB\n", freemem / ( 1024 * 1024 ) );
return 0;
}
<div style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" onclick="document.getElementsByClassName('answer_list')[0].style.display = 'auto';">
As I did not find a proper way I wrote a script to do it and I'm sharing it here for those who need it. The script runs through all user tables and collects the columns. If the column type is any char type then it tries to convert it to the given collation.
Columns has to be index and constraint free for this to work.
If someone still has a better solution to this please post it!
DECLARE @collate nvarchar(100);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);
SET @collate = 'Latin1_General_CI_AS';
DECLARE local_table_cursor CURSOR FOR
SELECT [name]
FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1
OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @table
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE local_change_cursor CURSOR FOR
SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
, c.name column_name
, t.Name data_type
, c.max_length
, c.column_id
FROM sys.columns c
JOIN sys.types t ON c.system_type_id = t.system_type_id
LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE c.object_id = OBJECT_ID(@table)
ORDER BY c.column_id
OPEN local_change_cursor
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@max_length = -1) OR (@max_length > 4000) SET @max_length = 4000;
IF (@data_type LIKE '%char%')
BEGIN TRY
SET @sql = 'ALTER TABLE ' + @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
PRINT @sql
EXEC sp_executesql @sql
END TRY
BEGIN CATCH
PRINT 'ERROR: Some index or constraint rely on the column' + @column_name + '. No conversion possible.'
PRINT @sql
END CATCH
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id
END
CLOSE local_change_cursor
DEALLOCATE local_change_cursor
FETCH NEXT FROM local_table_cursor
INTO @table
END
CLOSE local_table_cursor
DEALLOCATE local_table_cursor
GO
Not sure if this is any "cleaner", but:
List keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++) {
Object obj = keys.get(i);
// do stuff here
}
Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:
-Xmx512m -ea -Djava.awt.headless=true
Here are two other software packages which can be used for DNS caching on Linux:
After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.
If your system is using NetworkManager you can either try using the dns=dnsmasq
option in /etc/NetworkManager/NetworkManager.conf
or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d
directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.
In Visual Studio Professional 2017 Version 15.9.13:
First, either:
or
Then, wait for it while it is "getting things ready..." and being "almost there..."
Switch to the "Individual components" tab
Scroll down to the "Compilers, build tools, and runtimes" section
Check "VC++ 2017 version 15.9 v14.16 latest v141 tools"
like this:
After doing this, you will be blessed with not just one, but a whopping four instances of DUMPBIN:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x86\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x86\dumpbin.exe
Already quite a few solutions here, but yet another way of doing that would be -
anims = []
images = [f for f in files if (lambda t: True if f[2].lower() in IMAGE_TYPES else anims.append(t) and False)(f)]
Iterates over the list only once, and looks a bit more pythonic and hence readable to me.
>>> files = [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ('file1.bmp', 33L, '.bmp')]
>>> IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
>>> anims = []
>>> images = [f for f in files if (lambda t: True if f[2].lower() in IMAGE_TYPES else anims.append(t) and False)(f)]
>>> print '\n'.join([str(anims), str(images)])
[('file2.avi', 999L, '.avi')]
[('file1.jpg', 33L, '.jpg'), ('file1.bmp', 33L, '.bmp')]
>>>
Using make_axes
is even easier and gives a better result. It also provides possibilities to customise the positioning of the colorbar.
Also note the option of subplots
to share x and y axes.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
for ax in axes.flat:
im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)
cax,kw = mpl.colorbar.make_axes([ax for ax in axes.flat])
plt.colorbar(im, cax=cax, **kw)
plt.show()
I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.
String[] output = originalString.split(" (");
String result = output[0];
Another way if you must use cut command
ps axu | grep [j]boss |awk '$1=$1'|cut -d' ' -f5
In Solaris, replace awk with nawk
or /usr/xpg4/bin/awk
After installing it http://meldmerge.org/ I had to tell git where it was:
git config --global merge.tool meld
git config --global diff.tool meld
git config --global mergetool.meld.path “C:\Program Files (x86)\Meld\meld.exe”
And that seems to work. Both merging and diffing with “git difftool” or “git mergetool”
If someone facing issue such as Meld crash after starting (problem indication with python) then you need to set up Meld/lib to your system environment variable as bellow
C:\Program Files (x86)\Meld\lib
static int binaryToInt (String binary){
char []cA = binary.toCharArray();
int result = 0;
for (int i = cA.length-1;i>=0;i--){
//111 , length = 3, i = 2, 2^(3-3) + 2^(3-2)
// 0 1
if(cA[i]=='1') result+=Math.pow(2, cA.length-i-1);
}
return result;
}
Update: 19 -11-2019
The below answer is no more relevant to present day.
So for any one looking for answers you should look at the documentation linked below
https://developer.android.com/training/articles/user-data-ids
Old Answer - Not relevant now. You check this blog in the link below
http://android-developers.blogspot.in/2011/03/identifying-app-installations.html
ANDROID_ID
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
The above is from the link @ Is there a unique Android device ID?
More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.
ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.
The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.
You get the imei number of the device using the below
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29
Add this is manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
try this:
select salesid,count (salesid) from AXDelNotesNoTracking group by salesid having count (salesid) >1
and
tests whether both expressions are logically True
while &
(when used with True
/False
values) tests if both are True
.
In Python, empty built-in objects are typically treated as logically False
while non-empty built-ins are logically True
. This facilitates the common use case where you want to do something if a list is empty and something else if the list is not. Note that this means that the list [False] is logically True
:
>>> if [False]:
... print 'True'
...
True
So in Example 1, the first list is non-empty and therefore logically True
, so the truth value of the and
is the same as that of the second list. (In our case, the second list is non-empty and therefore logically True
, but identifying that would require an unnecessary step of calculation.)
For example 2, lists cannot meaningfully be combined in a bitwise fashion because they can contain arbitrary unlike elements. Things that can be combined bitwise include: Trues and Falses, integers.
NumPy objects, by contrast, support vectorized calculations. That is, they let you perform the same operations on multiple pieces of data.
Example 3 fails because NumPy arrays (of length > 1) have no truth value as this prevents vector-based logic confusion.
Example 4 is simply a vectorized bit and
operation.
Bottom Line
If you are not dealing with arrays and are not performing math manipulations of integers, you probably want and
.
If you have vectors of truth values that you wish to combine, use numpy
with &
.
The goal was to write code to call start() and join() in one place.
Parameter anonymous class is an anonymous function. new Thread(() ->{})
new Thread(() ->{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
}){{start();}}.join();
In the body of an anonymous class has instance-block that calls start(). The result is a new instance of class Thread, which is called join().
Once you have markers on the map, you can retrieve the Lat/Long coordinates through the API and use this to set the map's center. You'll first just need to determine which marker you wish to center on - I'll leave that up to you.
// "marker" refers to the Marker object you wish to center on
var latLng = marker.getPosition(); // returns LatLng object
map.setCenter(latLng); // setCenter takes a LatLng object
Info windows are separate objects which are typically bound to a marker, so to open the info window you might do something like this (however it will depend on your code):
var infoWindow = marker.infoWindow; // retrieve the InfoWindow object
infoWindow.open(map); // Trigger the "open()" method
Hope this helps.
Here is a simplified function that returns a boolean and has no output pushed to stdout:
import subprocess, platform
def pingOk(sHost):
try:
output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)
except Exception, e:
return False
return True
A 2-tuple
is a pair. You can access the first and second elements like this:
x = ('a', 1) # make a pair
x[0] # access 'a'
x[1] # access 1
The DataView object itself is used to loop through DataView rows.
DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.
C#
foreach (DataRowView rowView in dataView)
{
DataRow row = rowView.Row;
// Do something //
}
VB.NET
For Each rowView As DataRowView in dataView
Dim row As DataRow = rowView.Row
' Do something '
Next
As cardern has said list will do the job.
Here is how you can use a named range.
Select your range and enter a new name:
Select your cell that you want a drop down to be in and goto data tab -> data validation.
Select 'List' from the 'Allow' Drop down menu.
Enter your named range like this:
Now you have a drop down linked to your range. If you insert new rows in your range everything will update automatically.
I'd say it depends on what you need it for:
If you need it just to get 3 columns layout, I'd suggest to do it with float
.
If you need it for menu, you can use inline-block
. For the whitespace problem, you can use few tricks as described by Chris Coyier here http://css-tricks.com/fighting-the-space-between-inline-block-elements/.
If you need to make a multiple choice option, which the width needs to spread evenly inside a specified box, then I'd prefer display: table
. This will not work correctly in some browsers, so it depends on your browser support.
Lastly, what might be the best method is using flexbox
. The spec for this has changed few times, so it's not stable just yet. But once it has been finalized, this will be the best method I reckon.
Please do the import like below:
import { Router } from '@angular/Router';
The mistake that was being done was -> import { Router } from '@angular/router';
You need to rename your main class to Main
, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main
.
That's all.
Preamble
below may work or may not, this is all given as-is, you and only you are responsible person in case of some damage, data loss and so on. But I hope things go smooth!
To undo make install
I would do (and I did) this:
Idea: check whatever script installs and undo this with simple bash script.
--prefix=$PWD/install
. For CMake, you can go to your build dir, open CMakeCache.txt, and fix CMAKE_INSTALL_PREFIX value.make install
again).make install
script installs into custom dir just same contents you want to remove from somewhere else (usually /usr/local
). So, we need a script.
3.1. Script should compare custom dir, with dir you want clean. I use this:anti-install.sh
RM_DIR=$1
PRESENT_DIR=$2
echo "Remove files from $RM_DIR, which are present in $PRESENT_DIR"
pushd $RM_DIR
for fn in `find . -iname '*'`; do
# echo "Checking $PRESENT_DIR/$fn..."
if test -f "$PRESENT_DIR/$fn"; then
# First try this, and check whether things go plain
echo "rm $RM_DIR/$fn"
# Then uncomment this, (but, check twice it works good to you).
# rm $RM_DIR/$fn
fi
done
popd
3.2. Now just run this script (it will go dry-run)
bash anti-install.sh <dir you want to clean> <custom installation dir>
E.g. You wan't to clean /usr/local, and your custom installation dir is /user/me/llvm.build/install, then it would be
bash anti-install.sh /usr/local /user/me/llvm.build/install
3.3. Check log carefully, if commands are good to you, uncomment rm $RM_DIR/$fn
and run it again. But stop! Did you really check carefully? May be check again?
Source to instructions: https://dyatkovskiy.com/2019/11/26/anti-make-install/
Good luck!
The KeyDown event only triggered at the standard TextBox or MaskedTextBox by "normal" input keys, not ENTER or TAB and so on.
One can get special keys like ENTER by overriding the IsInputKey method:
public class CustomTextBox : System.Windows.Forms.TextBox
{
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Return)
return true;
return base.IsInputKey(keyData);
}
}
Then one can use the KeyDown event in the following way:
CustomTextBox ctb = new CustomTextBox();
ctb.KeyDown += new KeyEventHandler(tb_KeyDown);
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Enter key is down
//Capture the text
if (sender is TextBox)
{
TextBox txb = (TextBox)sender;
MessageBox.Show(txb.Text);
}
}
}
You can try this. Override the OnPaint event of the TextBox.
protected override void OnPaint(PaintEventArgs e)
{
SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
// Draw string to screen.
e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}
set the ControlStyles to "UserPaint"
public MyTextBox()//constructor
{
// This call is required by the Windows.Forms Form Designer.
this.SetStyle(ControlStyles.UserPaint,true);
InitializeComponent();
// TODO: Add any initialization after the InitForm call
}
Or you can try this hack
In Enter event set the focus
int index=this.Controls.IndexOf(this.textBox1);
this.Controls[index-1].Focus();
So your control will not focussed and behave like disabled.
Based on Michaels answer this is the actual CSS code to use
.parent:hover .child
{
display: block;
-webkit-animation: fadeInFromNone 0.5s ease-out;
-moz-animation: fadeInFromNone 0.5s ease-out;
-o-animation: fadeInFromNone 0.5s ease-out;
animation: fadeInFromNone 0.5s ease-out;
}
@-webkit-keyframes fadeInFromNone {
0% {
display: none;
opacity: 0;
}
1% {
display: block;
opacity: 0;
}
100% {
display: block;
opacity: 1;
}
}
@-moz-keyframes fadeInFromNone {
0% {
display: none;
opacity: 0;
}
1% {
display: block;
opacity: 0;
}
100% {
display: block;
opacity: 1;
}
}
@-o-keyframes fadeInFromNone {
0% {
display: none;
opacity: 0;
}
1% {
display: block;
opacity: 0;
}
100% {
display: block;
opacity: 1;
}
}
@keyframes fadeInFromNone {
0% {
display: none;
opacity: 0;
}
1% {
display: block;
opacity: 0;
}
100% {
display: block;
opacity: 1;
}
}
I did it using below steps:
git reset --hard <commit key of the pull request>
git add
git commit --amend
git push -f origin <name of the remote branch of pull request>
The argument is of length zero takes places when you get an output as an integer of length 0 and not a NULL output.i.e., integer(0).
You can further verify my point by finding the class of your output-
>class(output)
"integer"
The best way I just found to address this is to temporarily set that project (most likely a class library) to the startup project. This forces the package manager console to use that project as it's config source. part of the reason it is set up this way is because of the top down model that th econfig files usually follow. The rule of thumb is that the project that is closest to the client (MVC application for instance) is the web.config or app.config that will be used.
Every service that is bound in activity must be unbind on app close.
So try using
onPause(){
unbindService(YOUR_SERVICE);
super.onPause();
}
For those of you editing the ./.git/config
[remote "external"]
url = ssh://[email protected]:11720/aaa/bbb/ccc
fetch = +refs/heads/*:refs/remotes/external/*
Very easy, this is how I did it.
.directive('blockOnRender', function ($blockUI) {_x000D_
return {_x000D_
restrict: 'A',_x000D_
link: function (scope, element, attrs) {_x000D_
_x000D_
if (scope.$first) {_x000D_
$blockUI.blockElement($(element).parent());_x000D_
}_x000D_
if (scope.$last) {_x000D_
$blockUI.unblockElement($(element).parent());_x000D_
}_x000D_
}_x000D_
};_x000D_
})
_x000D_
You should do it this way ideally
t = TemperatureData.objects.get(id=1)
t.value = 999
t.save(['value'])
This allow you to specify which column should be saved and rest are left as they currently are in database. (https://code.djangoproject.com/ticket/4102)!
my example:
companyNamesFirst = this.model.CustomerDisplayList.Where(a => a.CompanyFirst != null ? a.CompanyFirst.StartsWith(typedChars.ToLower())) : false).Select(b => b.CompanyFirst).Distinct().ToList();
You can use show innodb status
(or show engine innodb status
for newer versions of mysql) to get a list of all the actions currently pending inside the InnoDB engine. Buried in the wall of output will be the transactions, and what internal process ID they're running under.
You won't be able to force a commit or rollback of those transactions, but you CAN kill the MySQL process running them, which does essentially boil down to a rollback. It kills the processes' connection and causes MySQL to clean up the mess its left.
Here's what you'd want to look for:
------------
TRANSACTIONS
------------
Trx id counter 0 140151
Purge done for trx's n:o < 0 134992 undo n:o < 0 0
History list length 10
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 17004, OS thread id 140621902116624
MySQL thread id 10594, query id 10269885 localhost marc
show innodb status
In this case, there's just one connection to the InnoDB engine right now (my login, running the show
query). If that line were an actual connection/stuck transaction you'd want to terminate, you'd then do a kill 10594
.
git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
It was tested with three different URL styles:
echo "Fetch URL: http://user@pass:gitservice.org:20080/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: Fetch URL: [email protected]:home1-oss/oss-build.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: https://github.com/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0
first, then cd %~dp0
. This will change the directory to the batch file's drive, then change to its folder.
For #oneLinerLovers, cd /d %~dp0
will change both the drive and directory :)
Hope this helps someone.
If the file input name
indicates an array and flags multiple
, and you parse the entire form
with FormData
, it is not necessary to iteratively append()
the input files. FormData
will automatically handle multiple files.
$('#submit_1').on('click', function() {_x000D_
let data = new FormData($("#my_form")[0]);_x000D_
_x000D_
$.ajax({_x000D_
url: '/path/to/php_file',_x000D_
type: 'POST',_x000D_
data: data,_x000D_
processData: false,_x000D_
contentType: false,_x000D_
success: function(r) {_x000D_
console.log('success', r);_x000D_
},_x000D_
error: function(r) {_x000D_
console.log('error', r);_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="my_form">_x000D_
<input type="file" name="multi_img_file[]" id="multi_img_file" accept=".gif,.jpg,.jpeg,.png,.svg" multiple="multiple" />_x000D_
<button type="button" name="submit_1" id="submit_1">Not type='submit'</button>_x000D_
</form>
_x000D_
Note that a regular button type="button"
is used, not type="submit"
. This shows there is no dependency on using submit
to get this functionality.
The resulting $_FILES
entry is like this in Chrome dev tools:
multi_img_file:
error: (2) [0, 0]
name: (2) ["pic1.jpg", "pic2.jpg"]
size: (2) [1978036, 2446180]
tmp_name: (2) ["/tmp/phphnrdPz", "/tmp/phpBrGSZN"]
type: (2) ["image/jpeg", "image/jpeg"]
Note: There are cases where some images will upload just fine when uploaded as a single file, but they will fail when uploaded in a set of multiple files. The symptom is that PHP reports empty $_POST
and $_FILES
without AJAX throwing any errors. Issue occurs with Chrome 75.0.3770.100 and PHP 7.0. Only seems to happen with 1 out of several dozen images in my test set.
I know it's a old quetion but i got the same problem and fix it like this:
First, Add Fragment1 to BackStack with a name (e.g "Frag1"):
frag = new Fragment1();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detailFragment, frag);
transaction.addToBackStack("Frag1");
transaction.commit();
And then, Whenever you want to go back to Fragment1 (even after adding 10 fragments above it), just call popBackStackImmediate with the name:
getSupportFragmentManager().popBackStackImmediate("Frag1", 0);
Hope it will help someone :)
If you are trying to change this setting in the Blazor (ASP.NET Core Hosted) template, you need to pass the following to the AddNewtonsoftJson
call in Startup.cs
in the Server
project:
services.AddMvc().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
);
Place all your layouts inside a ScrollView with width and height set to fill_parent.
I used this:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
MyEclipse has a pretty decent one, it costs money however. One of the reasons I went over to Netbeans is because of their JSP editor, which is still far from perfect but better then vanilla Eclipse.
Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.
The value will get reflected when using in the blocks of parent class
if the variable is static then change the value during initialization itself with static block,
class Son extends Dad {
static {
me = "son";
}
}
or else change in constructor.
You can also change the value later in any blocks. It will get reflected in super class
Well, I think you can assign it to a new object. Something like:
var v = new object();
For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:
var arguments = uri.Query
.Substring(1) // Remove '?'
.Split('&')
.Select(q => q.Split('='))
.ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());
Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
jww is right — you're referencing the wrong intermediate certificate.
As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt
Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):
The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file
So I'd go for that one.
This rings a bell. I came across a similar problem in the past,
You can generate an assemblyInfo.cs by right clicking the project and chosing properties. In the application tab fill in the details and press save, this will generate the assemblyInfo.cs file for you. If you build your project after that, it should work.
Cheers, Tarun
Update 2016-07-08:
For Visual Studio 2010 through the most recent version (2015 at time of writing), LandedGently's comment still applies:
After you select project Properties and the Application tab as @Tarun mentioned, there is a button "Assembly Information..." which opens another dialog. You need to at least fill in the Title here. VS will add the GUID and versions, but if the title is empty, it will not create the AssemblyInfo.cs file.
Check your input parameters, and make sure you don't have one named type
. If so then you will have a clash and get this error.
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
You could achieve that simply by wrapping the image by a <div>
and adding overflow: hidden
to that element:
<div class="img-wrapper">
<img src="..." />
</div>
.img-wrapper {
display: inline-block; /* change the default display type to inline-block */
overflow: hidden; /* hide the overflow */
}
Also it's worth noting that <img>
element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px
gap at the bottom of the image.
That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align
property to the image with a value other than baseline
.
Additionally for a better user experience, you could add transition
to the images.
Thus we'll end up with the following:
.img-wrapper img {
transition: all .2s ease;
vertical-align: middle;
}
I fixed this issue on my debian GNU/Linux system by overiding system rules that way :
mv /etc/udev/rules.d/51-android.rules /etc/udev/rules.d/99-android.rules
I used contents from files linked at : http://rootzwiki.com/topic/258-udev-rules-for-any-device-no-more-starting-adb-with-sudo/
You need two things to precisely define the scroll position of a listView:
To get the current listView Scroll position:
int firstVisiblePosition = listView.getFirstVisiblePosition();
int topEdge=listView.getChildAt(0).getTop(); //This gives how much the top view has been scrolled.
To set the listView Scroll position:
listView.setSelectionFromTop(firstVisiblePosition,0);
// Note the '-' sign for scrollTo..
listView.scrollTo(0,-topEdge);
I am going to answer my own question.
I added the following lines of code to my Makefile and it fixed the "clock skew" problem:
clean:
find . -type f | xargs touch
rm -rf $(OBJS)
Those who are using python 3 and reload from importlib.
If you have problems like it seems that module doesn't reload... That is because it needs some time to recompile pyc (up to 60 sec).I writing this hint just that you know if you have experienced this kind of problem.
you can use getline from a file using this code. this code will take a whole line from the file. and then you can use a while loop to go all lines while (ins);
ifstream ins(filename);
string s;
std::getline (ins,s);
One issue with REPLACE
will be where city names contain the district name. You can use something like.
SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
FROM dbo.tblOrtsteileGeo O
JOIN dbo.Cities C
ON C.foo = O.foo
WHERE O.GKZ = '06440004'
Since no one else has mentioned this…
It is not safe to compare the results of System.nanoTime()
calls between different threads. Even if the events of the threads happen in a predictable order, the difference in nanoseconds can be positive or negative.
System.currentTimeMillis()
is safe for use between threads.
here is the code to print only the headers or columns of the csv file.
import csv
HEADERS = next(csv.reader(open('filepath.csv')))
print (HEADERS)
Another method with pandas
import pandas as pd
HEADERS = list(pd.read_csv('filepath.csv').head(0))
print (HEADERS)
i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:
RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
to your .htaccess file
You convert type np.dot(X, T)
to float32 like this:
z=np.array(np.dot(X, T),dtype=np.float32)
def sigmoid(X, T):
return (1.0 / (1.0 + np.exp(-z)))
Hopefully it will finally work!
DDL = Data Definition Language, any commands that provides structure and other information about your data
DML = Data Manipulation Language, there's only 3 of them, INSERT, UPDATE, DELETE. 4, if you will count SELECT * INTO x_tbl from tbl
of MSSQL (ANSI SQL: CREATE TABLE x_tbl AS SELECT * FROM tbl
)
You can use range with count to check how many times a number appears in the string by checking it against the range:
def count_digit(a):
sum = 0
for i in range(10):
sum += a.count(str(i))
return sum
ans = count_digit("apple3rh5")
print(ans)
#This print 2
Don't post the data as an array. To bind to a list, the key/value pairs should be submitted with the same value for each key.
You should not need a form to do this. You just need a list of key/value pairs, which you can include in the call to $.post.
All have highlighted almost all major differences between numpy array and python list, I will just brief them out here:
Numpy arrays have a fixed size at creation, unlike python lists (which can grow dynamically). Changing the size of ndarray will create a new array and delete the original.
The elements in a Numpy array are all required to be of the same data type (we can have the heterogeneous type as well but that will not gonna permit you mathematical operations) and thus will be the same size in memory
Numpy arrays are facilitated advances mathematical and other types of operations on large numbers of data. Typically such operations are executed more efficiently and with less code than is possible using pythons build in sequences
Here is My Code
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
if (gvDetail.Rows.Count > 0)
{
System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
gvDetail.RenderControl(htmlWrite1);
gvDetail.AllowPaging = false;
Search();
sh.ExportToExcel(gvDetail, "Report");
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
puts 'abcdefg'.start_with?('abc') #=> true
[edit] This is something I didn't know before this question: start_with
takes multiple arguments.
'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
Use val()
to change to the value (not the text) and trigger()
to manually fire the event.
The change event handler must be declared before the trigger.
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
$('.check')
.val('two')
.trigger('change');
Another solution that uses jQuery and JSON, so you can access the parameter values through an object.
var loc = window.location.href;
var param = {};
if(loc.indexOf('?') > -1)
{
var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");
var stringJson = "{";
for(var i=0;i<params.length;i++)
{
var propVal = params[i].split("=");
var paramName = propVal[0];
var value = propVal[1];
stringJson += "\""+paramName+"\": \""+value+"\"";
if(i != params.length-1) stringJson += ",";
}
stringJson += "}";
// parse string with jQuery parseJSON
param = $.parseJSON(stringJson);
}
Assuming your URL is http://example.com/?search=hello+world&language=en&page=3
After that it's only a matter of using the parameters like this:
param.language
to return
en
The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.
If your parameter contains numeric values then just parse the value.
parseInt(param.page)
If there are no parameters param
will just be an empty object.
I do a mix of edem's answer and your second code. This way, I have the benefits of common getter/setters (code completion in your IDE), ease of coding if I want, exceptions due to inexistent properties (great for discovering typos: $foo->naem
instead of $foo->name
), read only properties and compound properties.
class Foo
{
private $_bar;
private $_baz;
public function getBar()
{
return $this->_bar;
}
public function setBar($value)
{
$this->_bar = $value;
}
public function getBaz()
{
return $this->_baz;
}
public function getBarBaz()
{
return $this->_bar . ' ' . $this->_baz;
}
public function __get($var)
{
$func = 'get'.$var;
if (method_exists($this, $func))
{
return $this->$func();
} else {
throw new InexistentPropertyException("Inexistent property: $var");
}
}
public function __set($var, $value)
{
$func = 'set'.$var;
if (method_exists($this, $func))
{
$this->$func($value);
} else {
if (method_exists($this, 'get'.$var))
{
throw new ReadOnlyException("property $var is read-only");
} else {
throw new InexistentPropertyException("Inexistent property: $var");
}
}
}
}
Cache-Control: private
Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache, such as a proxy server.
If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe
container anytime the height of the framed content changes.
Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).
window.addEventListener("load", function(){
if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe
send_height_to_parent_function = function(){
var height = document.getElementsByTagName("html")[0].clientHeight;
//console.log("Sending height as " + height + "px");
parent.postMessage({"height" : height }, "*");
}
// send message to parent about height updates
send_height_to_parent_function(); //whenever the page is loaded
window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
var observer = new MutationObserver(send_height_to_parent_function); // whenever DOM changes PT1
var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
observer.observe(window.document, config); // PT3
});
Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.
<script>
window.addEventListener("message", function(e){
var this_frame = document.getElementById("healthy_behavior_iframe");
if (this_frame.contentWindow === e.source) {
this_frame.height = e.data.height + "px";
this_frame.style.height = e.data.height + "px";
}
})
</script>
try this
.div
{
text-decoration:none;
font-size:16;
display:block;
padding:14px;
}
.div a:hover
{
background-color:#080808;
color:white;
}
lets say we have a anchor tag used in our code and class"div" is called in the main program. the a:hover will do the thing, it will give a vampire black color to the background and white color to the text when the mouse is moved over it that's what hover means.
You can make it with timeout
:
This will be visible: timeout 5
This will not be visible timeout 5 >nul
Turns out you can't use the root
user in 5.7 anymore without becoming a sudoer. That means you can't just run mysql -u root
anymore and have to do sudo mysql -u root
instead.
That also means that it will no longer work if you're using the root
user in a GUI (or supposedly any non-command line application). To make it work you'll have to create a new user with the required privileges and use that instead.
See this answer for more details.
A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.
For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.
Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.
However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.
Read the Security section of the PHP manual as a starting point to keeping your code safe.
You can use:
$("#tagscloud span").text("Your text here");
The same code will also work for the second case. You could also use:
$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");
you can use toggleClass()
to toggle class it is really handy.
case:1
<div id='mydiv' class="class1"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class2"></div>
case:2
<div id='mydiv' class="class2"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class1"></div>
case:3
<div id='mydiv' class="class1 class2 class3"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class3"></div>
Regarding Fred the Fantastic's answer:
Not every JPEG marker between C0
-CF
are SOF
markers; I excluded DHT (C4
), DNL (C8
) and DAC (CC
). Note that I haven't looked into whether it is even possible to parse any frames other than C0
and C2
in this manner. However, the other ones seem to be fairly rare (I personally haven't encountered any other than C0
and C2
).
Either way, this solves the problem mentioned in comments by Malandy with Bangles.jpg
(DHT erroneously parsed as SOF).
The other problem mentioned with 1431588037-WgsI3vK.jpg
is due to imghdr
only being able detect the APP0 (EXIF) and APP1 (JFIF) headers.
This can be fixed by adding a more lax test to imghdr (e.g. simply FFD8
or maybe FFD8FF
?) or something much more complex (possibly even data validation). With a more complex approach I've only found issues with: APP14 (FFEE
) (Adobe); the first marker being DQT (FFDB
); and APP2 and issues with embedded ICC_PROFILEs.
Revised code below, also altered the call to imghdr.what()
slightly:
import struct
import imghdr
def test_jpeg(h, f):
# SOI APP2 + ICC_PROFILE
if h[0:4] == '\xff\xd8\xff\xe2' and h[6:17] == b'ICC_PROFILE':
print "A"
return 'jpeg'
# SOI APP14 + Adobe
if h[0:4] == '\xff\xd8\xff\xee' and h[6:11] == b'Adobe':
return 'jpeg'
# SOI DQT
if h[0:4] == '\xff\xd8\xff\xdb':
return 'jpeg'
imghdr.tests.append(test_jpeg)
def get_image_size(fname):
'''Determine the image type of fhandle and return its size.
from draco'''
with open(fname, 'rb') as fhandle:
head = fhandle.read(24)
if len(head) != 24:
return
what = imghdr.what(None, head)
if what == 'png':
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
return
width, height = struct.unpack('>ii', head[16:24])
elif what == 'gif':
width, height = struct.unpack('<HH', head[6:10])
elif what == 'jpeg':
try:
fhandle.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf or ftype in (0xc4, 0xc8, 0xcc):
fhandle.seek(size, 1)
byte = fhandle.read(1)
while ord(byte) == 0xff:
byte = fhandle.read(1)
ftype = ord(byte)
size = struct.unpack('>H', fhandle.read(2))[0] - 2
# We are at a SOFn block
fhandle.seek(1, 1) # Skip `precision' byte.
height, width = struct.unpack('>HH', fhandle.read(4))
except Exception: #IGNORE:W0703
return
else:
return
return width, height
Note: Created a full answer instead of a comment, since I'm not yet allowed to.
FCM implementation Class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
if(data != null) {
// Do something with Token
}
}
}
// FirebaseInstanceId.getInstance().getToken();
@Override
public void onNewToken(String token) {
super.onNewToken(token);
if (!token.isEmpty()) {
Log.e("NEW_TOKEN",token);
}
}
}
And call its initialize in Activity or APP :
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
instanceIdResult -> {
String newToken = instanceIdResult.getToken();
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.i("FireBaseToken", "onFailure : " + e.toString());
}
});
AndroidManifest.xml :
<service android:name="ir.hamplus.MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
**If you added "INSTANCE_ID_EVENT" don't forget to disable it.
<span style="line-height:40px;"><br></span>
You'd have to do this inline and on each
element but it should work on most browsers
Fiddle with the line height to get the desired effect. If you make it inline on each element, it should work across most browsers and e-mail(but this is too complex to discuss here).
"By default, when an application calls DriverManager.getConnection(url, ...)
and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.
Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("create table customer(id integer, name varchar(10))");
st.execute("insert into customer values (1, 'Thomas')");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select name from customer");
while (rset.next()) {
String name = rset.getString(1);
System.out.println(name);
}
}
}
Converting java.util.Data
to java.sql.Data
will loose hour, minute and second. So if it is possible, I suggest you use java.sql.Timestamp
like this:
prepareStatement.setTimestamp(1, new Timestamp(utilDate.getTime()));
For more info, you can check this question.
I also faced this due to Tomcat version mismatching! According to the documentation, the default tomcat version of Grails 4.0.x is tomcat 8 but in the server that I was using had the tomcat version of 9.0.31!
in the build.gradle file I changed compile "org.springframework.boot:spring-boot-starter-tomcat" to provided "org.springframework.boot:spring-boot-starter-tomcat" and added/modified the cache plugin to compile "org.grails.plugins:cache", { exclude group: "org.codehaus.groovy", module: "groovy-all" } under dependencies block! [Cache plugin comes with groovy-all 2.1]
It worked like a charm! Strangely, this did not cause any problems when running the app with command grails run-app
a one-liner that will give you the rough equivalent of "viewing source" to see array contents:
assumes php 4.3.0+:
echo nl2br(str_replace(' ', ' ', print_r($_SERVER, true)));
<xsl:value-of select="name(.)" /> : <xsl:value-of select="."/>
The tibble
package now has a dedicated function that converts row names to an explicit variable.
library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head
Gives:
das_Auto mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
6 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
You can use groupBy of angular.filter module.
so you can do something like this:
JS:
$scope.players = [
{name: 'Gene', team: 'alpha'},
{name: 'George', team: 'beta'},
{name: 'Steve', team: 'gamma'},
{name: 'Paula', team: 'beta'},
{name: 'Scruath', team: 'gamma'}
];
HTML:
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
RESULT:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath
UPDATE: jsbin Remember the basic requirements to use angular.filter
, specifically note you must add it to your module's dependencies:
(1) You can install angular-filter using 4 different methods:
- clone & build this repository
- via Bower: by running $ bower install angular-filter from your terminal
- via npm: by running $ npm install angular-filter from your terminal
- via cdnjs http://www.cdnjs.com/libraries/angular-filter
(2) Include angular-filter.js (or angular-filter.min.js) in your index.html, after including Angular itself.
(3) Add 'angular.filter' to your main module's list of dependencies.
UNION
removes duplicates, whereas UNION ALL
does not.
In order to remove duplicates the result set must be sorted, and this may have an impact on the performance of the UNION, depending on the volume of data being sorted, and the settings of various RDBMS parameters ( For Oracle PGA_AGGREGATE_TARGET
with WORKAREA_SIZE_POLICY=AUTO
or SORT_AREA_SIZE
and SOR_AREA_RETAINED_SIZE
if WORKAREA_SIZE_POLICY=MANUAL
).
Basically, the sort is faster if it can be carried out in memory, but the same caveat about the volume of data applies.
Of course, if you need data returned without duplicates then you must use UNION, depending on the source of your data.
I would have commented on the first post to qualify the "is much less performant" comment, but have insufficient reputation (points) to do so.
USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up
sudo systemctl enable postgresql
DISABLE exists as well ofc
Some DOC: freedesktop man systemctl
There should be no difference, but your tuple method is wrong, try:
a_list.append(tuple([3, 4]))
On Mac OS X, neither of these regex syntaxes work inside sed for matching whole words
\bmyWord\b
\<myWord\>
Hear me now and believe me later, this ugly syntax is what you need to use:
/[[:<:]]myWord[[:>:]]/
So, for example, to replace mint with minty for whole words only:
sed "s/[[:<:]]mint[[:>:]]/minty/g"
Source: re_format man page
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
'Create Excel
Set objExcel = Wscript.CreateObject("Excel.Application")
objExcel.visible = True
Set objWb = objExcel.Workbooks.Add
objWb.Saveas("D:\Example.xlsx")
objExcel.Quit
As far as i had gone it is mostly depend on compiler but in general most cases the value is pre assumed as 0 by the compliers.
I got garbage value in case of VC++ while TC gave value as 0.
I Print it like below
int i;
printf('%d',i);
Please Try This for Getting column Index
Private Sub lvDetail_MouseMove(sender As Object, e As MouseEventArgs) Handles lvDetail.MouseClick
Dim info As ListViewHitTestInfo = lvDetail.HitTest(e.X, e.Y)
Dim rowIndex As Integer = lvDetail.FocusedItem.Index
lvDetail.Items(rowIndex).Selected = True
Dim xTxt = info.SubItem.Text
For i = 0 To lvDetail.Columns.Count - 1
If lvDetail.SelectedItems(0).SubItems(i).Text = xTxt Then
MsgBox(i)
End If
Next
End Sub
When you register for a new website, often you are sent an email to activate your account. That email typically contains a link to click on. Part of that link, contains a token, the server knows about this token and can associate it with your account. The token would usually have an expiry date associated with it, so you may only have an hour to click on the link and activate your account. None of this would be possible with cookies or session variables, since its unknown what device or browser the customer is using to check emails.
enter code hereif you are using linux you have to edit the
`/etc/apache2/sites-available/000-default.conf`
under the Documentroot . add the following code
`<Directory /var/www/>
AllowOverride all
Require all granted
</Directory>`
then ,
`sudo service apache2 restart`
and you have to enable the apache mod rewrite
`sudo a2enmod rewrite`
I had to downgrade OpenSSL in this way:
brew uninstall --ignore-dependencies openssl
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/30fd2b68feb458656c2da2b91e577960b11c42f4/Formula/openssl.rb
It was the only solution that worked for me.
From Oracle 12c R2 you could use COLLATE operator
:
The COLLATE operator determines the collation for an expression. This operator enables you to override the collation that the database would have derived for the expression using standard collation derivation rules.
The COLLATE operator takes one argument, collation_name, for which you can specify a named collation or pseudo-collation. If the collation name contains a space, then you must enclose the name in double quotation marks.
Demo:
CREATE TABLE tab1(i INT PRIMARY KEY, name VARCHAR2(100));
INSERT INTO tab1(i, name) VALUES (1, 'John');
INSERT INTO tab1(i, name) VALUES (2, 'Joe');
INSERT INTO tab1(i, name) VALUES (3, 'Billy');
--========================================================================--
SELECT /*csv*/ *
FROM tab1
WHERE name = 'jOHN' ;
-- no rows selected
SELECT /*csv*/ *
FROM tab1
WHERE name COLLATE BINARY_CI = 'jOHN' ;
/*
"I","NAME"
1,"John"
*/
SELECT /*csv*/ *
FROM tab1
WHERE name LIKE 'j%';
-- no rows selected
SELECT /*csv*/ *
FROM tab1
WHERE name COLLATE BINARY_CI LIKE 'j%';
/*
"I","NAME"
1,"John"
2,"Joe"
*/
I would say store them as an big integer, as a phone number itself is just a number. This also gives you more flexibility in how you present your phone numbers later, depending on what situation you are in.
I have written a C# method that url-encodes ALL symbols:
/// <summary>
/// !#$345Hf} ? %21%23%24%33%34%35%48%66%7D
/// </summary>
public static string UrlEncodeExtended( string value )
{
char[] chars = value.ToCharArray();
StringBuilder encodedValue = new StringBuilder();
foreach (char c in chars)
{
encodedValue.Append( "%" + ( (int)c ).ToString( "X2" ) );
}
return encodedValue.ToString();
}
DECLARE @a int=1000, @b int=1050
SELECT @a-1+ROW_NUMBER() OVER(ORDER BY y.z.value('(/n)[1]', 'int') ) rw
FROM (
SELECT CAST('<m>'+REPLICATE('<n>1</n>', @b-@a+1)+'</m>' AS XML ) x ) t
CROSS APPLY t.x.nodes('//m/n') y(z)
I had been working on this, and I was facing a problem using the responses provided here by different users. Problem was a white box behind my NavigationBar transparent image on iOS 13+
My solution is this one
if #available(iOS 13, *) {
navBar?.standardAppearance.backgroundColor = UIColor.clear
navBar?.standardAppearance.backgroundEffect = nil
navBar?.standardAppearance.shadowImage = UIImage()
navBar?.standardAppearance.shadowColor = .clear
navBar?.standardAppearance.backgroundImage = UIImage()
}
Hope this helps anyone with same problem
Double escaping is required when presented as a string.
Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html
That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.
my friend this the will fix ur problem ;)
in root of folder ( xampp ) just run this file ( setup_xampp.bat ) then press enter
and try to start the apache server
every things will work like charm ;)
in case your Latitude and Longitude lists are large and lazily loaded:
from itertools import izip
for lat, lon in izip(latitudes, longitudes):
process(lat, lon)
or if you want to avoid the for-loop
from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))
It depends on the shell (and its configuration) in standard bash only the command is stored without the date and time (check .bash_history
if there is any timestamp there).
To have bash store the timestamp you need to set HISTTIMEFORMAT
before executing the commands, e.g. in .bashrc
or .bash_profile
. This will cause bash to store the timestamps in .bash_history
(see the entries starting with #
).
#include<stdio.h>
int main(){
char ch='"';
printf("%c",ch);
return 0;
}
Output: "
import
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
You could compare String representations so:
array1.toString() == array2.toString()
array1.toString() !== array3.toString()
but that would also make
array4 = ['1',2,3,4,5]
equal to array1 if that matters to you
Another alternative, even though the OP did not ask for it:
There exist usb-to-serial adapters. Depending on the type of adapter, you may also need a nullmodem cable, too.
They are extremely easy to use under linux, work under windows, too, if you have got working drivers installed.
That way you can work directly with the sensors, and you do not have to try and emulate data. That way you are maybe even save from building an anemic system. (Due to your emulated data inputs not covering all cases, leading you to a brittle system.)
Its often better to work with the real stuff.
You can use WebClient.
Or (if you need more fine-grained control over the request) HttpWebRequest
Or, HttpClient in System.Net.Http.dll.
Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):
HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
http.Referer = referrer;
HttpWebResponse response = (HttpWebResponse )http.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string responseJson = sr.ReadToEnd();
// more stuff
}
Ubuntu comes with a version of PIP from precambrian and that's how you have to upgrade it if you do not want to spend hours and hours debugging pip related issues.
apt-get remove python-pip python3-pip
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
python3 get-pip.py
As you observed I included information for both Python 2.x and 3.x
In the last answer, you don't need to make a list from numbers; it is already a list:
numbers = [1, 2, 3]
numsum = sum(numbers)
print(numsum)
If you're open to using a third-party library, you can use the Collectors2
class in Eclipse Collections to convert the List
to a Bag
using a Stream
. A Bag
is a data structure that is built for counting.
Bag<String> counted =
list.stream().collect(Collectors2.countBy(each -> each));
Assert.assertEquals(1, counted.occurrencesOf("World"));
Assert.assertEquals(2, counted.occurrencesOf("Hello"));
System.out.println(counted.toStringOfItemToCount());
Output:
{World=1, Hello=2}
In this particular case, you can simply collect
the List
directly into a Bag
.
Bag<String> counted =
list.stream().collect(Collectors2.toBag());
You can also create the Bag
without using a Stream
by adapting the List
with the Eclipse Collections protocols.
Bag<String> counted = Lists.adapt(list).countBy(each -> each);
or in this particular case:
Bag<String> counted = Lists.adapt(list).toBag();
You could also just create the Bag directly.
Bag<String> counted = Bags.mutable.with("Hello", "Hello", "World");
A Bag<String>
is like a Map<String, Integer>
in that it internally keeps track of keys and their counts. But, if you ask a Map
for a key it doesn't contain, it will return null
. If you ask a Bag
for a key it doesn't contain using occurrencesOf
, it will return 0.
Note: I am a committer for Eclipse Collections.
You can try this out when you want to mass-assign properties of an Object from another Object using Property names:
public static void Assign(this object destination, object source)
{
if (destination is IEnumerable && source is IEnumerable)
{
var dest_enumerator = (destination as IEnumerable).GetEnumerator();
var src_enumerator = (source as IEnumerable).GetEnumerator();
while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
dest_enumerator.Current.Assign(src_enumerator.Current);
}
else
{
var destProperties = destination.GetType().GetProperties();
foreach (var sourceProperty in source.GetType().GetProperties())
{
foreach (var destProperty in destProperties)
{
if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
destProperty.SetValue(destination, sourceProperty.GetValue(source, new object[] { }), new object[] { });
break;
}
}
}
}
I found there is a library for this. See example here:
https://editor.datatables.net/examples/extensions/exportButtons.html
In addition to the above code, the following Javascript library files are loaded for use in this example:
In HTML, include following scripts:
jquery.dataTables.min.js
dataTables.editor.min.js
dataTables.select.min.js
dataTables.buttons.min.js
jszip.min.js
pdfmake.min.js
vfs_fonts.js
buttons.html5.min.js
buttons.print.min.js
Enable buttons by adding scripts like:
<script>
$(document).ready( function () {
$('#table-arrays').DataTable({
dom: '<"top"Blf>rt<"bottom"ip>',
buttons: ['copy', 'excel', 'csv', 'pdf', 'print'],
select: true,
});
} );
</script>
For some reason, the excel export results in corrupted file, but can be repaired. Alternatively, disable excel and use csv export.
using recursion
let myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
let size = 4; //Math.sqrt(myArr.length); --> For a n x n matrix
let tempArr = [];
function createMatrix(arr, i) {
if (arr.length !== 0) {
if(i % size == 0) {
tempArr.push(arr.splice(0,size))
}
createMatrix(arr, i - 1)
}
}
createMatrix(myArr, myArr.length);
console.log(tempArr);
Note: The existing array i.e. myArr will be modified.
If you can only think of one way to do it, don't do it.
Whether it's an interface layout, a task flow, or a block of code, just stop. Do something to collect more ideas, like asking other people how they would do it, and don't go back to implementing until you have at least three completely different ideas and at least one crisis of confidence.
Generally, when I think something can only be done one way, or think only one method has any merit, it's because I haven't thought through the factors which ought to be influencing the design thoroughly enough. If I had, some of them would clearly be in conflict, leading to a mess and thus an actual decision rather than a rote default.
Being a solid programmer does not make you a solid interface designer
And following all of the interface guidelines in the world will only begin to help. If it's even humanly possible... There seems to be a peculiar addiction to making things 'cute' and 'clever'.
Integers are only 32 bits. This means that its max value is 2^31 -1
. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow
uses double
.
If you want arbitrary integer precision, use BigInteger.pow
. But it's of course less efficient.
export https_proxy=http://127.0.0.1:1087 http_proxy=http://127.0.0.1:1087 all_proxy=socks5://127.0.0.1:1080
works for me
and I think it can solve all the problems like
Failed to connect to raw.githubusercontent.com port 443: Connection refused
Caution, member enumeration only works if the collection itself has no member of the same name. So if you had an array of FileInfo objects, you couldn't get an array of file lengths by using
$files.length # evaluates to array length
And before you say "well obviously", consider this. If you had an array of objects with a capacity property then
$objarr.capacity
would work fine UNLESS $objarr were actually not an [Array] but, for example, an [ArrayList]. So before using member enumeration you might have to look inside the black box containing your collection.
(Note to moderators: this should be a comment on rageandqq's answer but I don't yet have enough reputation.)
Swift 4, Xcode 9.4.1
The solution that worked for me: I had a label within a collection view cell, and the label text was getting trimmed. Set the attributes as below on Storyboard
Lines = 0
LineBreak = Word Wrap
Set yourlabel's leading and trailing constraint = 0 (using Autolayout)
SELECT * FROM news WHERE date > DATE_SUB(NOW(), INTERVAL 24 HOUR)
I guess you should differentiate the target (before and after Oreo)
int LAYOUT_FLAG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
}
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
LAYOUT_FLAG,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html
to achieve what you want .
Look at the code below :
HTML:
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>
JS :
createFormElement("Nickname","nickname")
function createFormElement(labelText, id) {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}
This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .
Moreover, when you use the process you mentioned in your post you get only [object Object]
. That is because when you call createProviderFormFields
, it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object
, then construct the html from it.
It's much easier to construct just the html and change the id
s of the label and input according to your needs.
That's fine. To understand the above, you have to understand the nature of abstract classes first. They are similar to interfaces in that respect. This is what Oracle say about this here.
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.
So you have to think about what happens when an interface extends another interface. For example ...
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
... as you can see, this also compiles perfectly fine. Simply because, just like an abstract class, an interface can NOT be instantiated. So, it is not required to explicitly mention the methods from its "parent". However, ALL the parent method signatures DO implicitly become a part of the extending interface or implementing abstract class. So, once a proper class (one that can be instantiated) extends the above, it WILL be required to ensure that every single abstract method is implemented.
Hope that helps... and Allahu 'alam !
Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,
or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.
i download the same custom-demo from Android.com and get the same complie problem.
at frist ,i change
xmlns:custom="http://schemas.android.com/apk/res/com.example.android.customviews"
to
xmlns:custom="http://schemas.android.com/apk/lib/com.example.android.customviews"
it work . then i get another solution
xmlns:custom="http://schemas.android.com/apk/res-auto"
it also work, but there are some differencies. The second solution has prefect function . i am finding the reason , may be you can have a hand in. thanks
After each command, the exit code can be found in the $?
variable so you would have something like:
ls -al file.ext
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi
You need to be careful of piped commands since the $?
only gives you the return code of the last element in the pipe so, in the code:
ls -al file.ext | sed 's/^/xx: /"
will not return an error code if the file doesn't exist (since the sed
part of the pipeline actually works, returning 0).
The bash
shell actually provides an array which can assist in that case, that being PIPESTATUS
. This array has one element for each of the pipeline components, that you can access individually like ${PIPESTATUS[0]}
:
pax> false | true ; echo ${PIPESTATUS[0]}
1
Note that this is getting you the result of the false
command, not the entire pipeline. You can also get the entire list to process as you see fit:
pax> false | true | false; echo ${PIPESTATUS[*]}
1 0 1
If you wanted to get the largest error code from a pipeline, you could use something like:
true | true | false | true | false
rcs=${PIPESTATUS[*]}; rc=0; for i in ${rcs}; do rc=$(($i > $rc ? $i : $rc)); done
echo $rc
This goes through each of the PIPESTATUS
elements in turn, storing it in rc
if it was greater than the previous rc
value.
Aggregated List of Libraries
As @Eiríkr Útlendi noted, the accepted solution only considers two white space characters: the horizontal tab (U+0009), and a breaking space (U+0020). It does not consider other whitespace characters such as non-breaking spaces (which happen to be in the text I am trying to deal with). A more complete whitespace character listing is included on Wikipedia and also referenced in the linked Perl answer. A simple C# solution that accounts for these other characters can be built using character class subtraction
[\s-[\r\n]]
or, including Eiríkr Útlendi's solution, you get
[\s\u3000-[\r\n]]
For IIS 7+, as well as adding the httpRuntime maxRequestLength setting you also need to add:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="52428800" /> <!--50MB-->
</requestFiltering>
</security>
</system.webServer>
Or in IIS (7):
- Select the website you want enable to accept large file uploads.
- In the main window double click 'Request filtering'
- Select "Edit Feature Settings"
- Modify the "Maximum allowed content length (bytes)"
['class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost:3306;dbname=testdb',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',]
It's simple:
Just provide the port number along with the host name
and set default sock path to your mysql.sock
file path in php.ini
which the server is running on.
I am surprised that none of the answers mentioned the insertAdjacentHTML()
method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.
Basic usage:
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');
Just as Oded has answered. You need to have this sort of detection functionality in javascript.
I've struggled with this myself and realized that the offset is not enough. It does not give you any information about daylight saving for example. I ended up writing some code to map to zoneinfo database keys.
By checking several dates around a year you can more accurately determine a timezone.
Try the script here: http://jsfiddle.net/pellepim/CsNcf/
Simply change your system timezone and click run to test it. If you are running chrome you need to do each test in a new tab though (and safar needs to be restarted to pick up timezone changes).
If you want more details of the code check out: https://bitbucket.org/pellepim/jstimezonedetect/
to truncate a decimal I've used the follow code:
<th><%#= sprintf("%0.01f",prom/total) %><!--1dec,aprox-->
<% if prom == 0 or total == 0 %>
N.E.
<% else %>
<%= Integer((prom/total).to_d*10)*0.1 %><!--1decimal,truncado-->
<% end %>
<%#= prom/total %>
</th>
If you want to truncate to 2 decimals, you should use Integr(a*100)*0.01
You can also use df.icol(n)
to access a column by integer.
Update: icol
is deprecated and the same functionality can be achieved by:
df.iloc[:, n] # to access the column at the nth position
There are a many ways to create your objects in JavaScript. Using a constructer function to create an object or object literal notation is using alot in JavaScript. Also creating an instance of Object and then adding properties and methods to it, there are three common ways to do create objects in JavaScript.
Constructer functions
There are built-in constructer functions that we all may use them time to time, like Date(), Number(), Boolean() etc, all constructer functions start with Capital letter, in the meantime we can create custom constructor function in JavaScript like this:
function Box (Width, Height, fill) {
this.width = Width; // The width of the box
this.height = Height; // The height of the box
this.fill = true; // Is it filled or not?
}
and you can invoke it, simply using new(), to create a new instance of the constructor, create something like below and call the constructor function with filled parameters:
var newBox = new Box(8, 12, true);
Object literals
Using object literals are very used case creating object in JavaScript, this an example of creating a simple object, you can assign anything to your object properties as long as they are defined:
var person = {
name: "Alireza",
surname: "Dezfoolian"
nose: 1,
feet: 2,
hands: 2,
cash: null
};
Prototyping
After creating an Object, you can prototype more members to that, for example adding colour to our Box, we can do this:
Box.prototype.colour = 'red';
In Android Studio 3.0 and later do this:
View > Tool Windows > Device File Explorer
The problem with some previous approaches is that they require an exact match of every word. But, What if you want to provide results for partial matches?
function search(arrayToSearch, wordsToSearch) {
arrayToSearch.filter(v =>
wordsToSearch.every(w =>
v.toLowerCase().split(" ").
reduce((isIn, h) => isIn || String(h).indexOf(w) >= 0, false)
)
)
}
//Usage
var myArray = ["Attach tag", "Attaching tags", "Blah blah blah"];
var searchText = "Tag attach";
var searchArr = searchText.toLowerCase().split(" "); //["tag", "attach"]
var matches = search(myArray, searchArr);
//Will return
//["Attach tag", "Attaching tags"]
This is useful when you want to provide a search box where users type words and the results can have those words in any order, position and case.
It is possible in VSS by three ways.
Active sync
icon on Solution Explorer.Ctrl
+ [
+ S
), you can able to navigate to active Item.Note: Either 1 or 2 only works in a mean time.. So You have to use either 1st or 2nd.
The str
function has a bug. Please try the following. You will see '0,196553' but the right output is '0,196554'. Because the str
function's default value is ROUND_HALF_UP.
>>> value=0.196553500000
>>> str("%f" % value).replace(".", ",")
df$colname <- as.numeric(df$colname)
I tried this way for changing one column type and I think it is better than many other versions, if you are not going to change all column types
df$colname <- as.character(df$colname)
for the vice versa.
You must use std namespace. If this code in main.cpp you should write
using namespace std;
If this declaration is in header, then you shouldn't include namespace and just write
std::string level;
In case of big projects, many files to change and also if the previous project version of PHP was 5.6 and the new one is 7.1, you can create a new file sql.php and include it in the header or somewhere you use it all the time and needs sql connection. For example:
//local
$sql_host = "localhost";
$sql_username = "root";
$sql_password = "";
$sql_database = "db";
$mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// /* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
} else {
// printf("Current character set: %s\n", $mysqli->character_set_name());
}
if (!function_exists('mysql_real_escape_string')) {
function mysql_real_escape_string($string){
global $mysqli;
if($string){
// $mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );
$newString = $mysqli->real_escape_string($string);
return $newString;
}
}
}
// $mysqli->close();
$conn = null;
if (!function_exists('mysql_query')) {
function mysql_query($query) {
global $mysqli;
// echo "DAAAAA";
if($query) {
$result = $mysqli->query($query);
return $result;
}
}
}
else {
$conn=mysql_connect($sql_host,$sql_username, $sql_password);
mysql_set_charset("utf8", $conn);
mysql_select_db($sql_database);
}
if (!function_exists('mysql_fetch_array')) {
function mysql_fetch_array($result){
if($result){
$row = $result->fetch_assoc();
return $row;
}
}
}
if (!function_exists('mysql_num_rows')) {
function mysql_num_rows($result){
if($result){
$row_cnt = $result->num_rows;;
return $row_cnt;
}
}
}
if (!function_exists('mysql_free_result')) {
function mysql_free_result($result){
if($result){
global $mysqli;
$result->free();
}
}
}
if (!function_exists('mysql_data_seek')) {
function mysql_data_seek($result, $offset){
if($result){
global $mysqli;
return $result->data_seek($offset);
}
}
}
if (!function_exists('mysql_close')) {
function mysql_close(){
global $mysqli;
return $mysqli->close();
}
}
if (!function_exists('mysql_insert_id')) {
function mysql_insert_id(){
global $mysqli;
$lastInsertId = $mysqli->insert_id;
return $lastInsertId;
}
}
if (!function_exists('mysql_error')) {
function mysql_error(){
global $mysqli;
$error = $mysqli->error;
return $error;
}
}
You can setup _JAVA_OPTIONS
instead of JAVA_OPTS
. This should work without $_JAVA_OPTIONS
.
If you are looking for non-jQuery solution that gives correct values in virtual pixels on mobile, and you think that plain window.innerHeight
or document.documentElement.clientHeight
can solve your problem, please study this link first: https://tripleodeon.com/assets/2011/12/table.html
The developer has done good testing that reveals the problem: you can get unexpected values for Android/iOS, landscape/portrait, normal/high density displays.
My current answer is not silver bullet yet (//todo), but rather a warning to those who are going to quickly copy-paste any given solution from this thread into production code.
I was looking for page width in virtual pixels on mobile, and I've found the only working code is (unexpectedly!) window.outerWidth
. I will later examine this table for correct solution giving height excluding navigation bar, when I have time.
If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON.
Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as .JSON file, you have to just select the location of the file.
Thanks, -Sam
There is a built in method which would be the fastest method also, calling tolist
on the .values
np array:
df.values.tolist()
[[0.0, 3.61, 380.0, 3.0],
[1.0, 3.67, 660.0, 3.0],
[1.0, 3.19, 640.0, 4.0],
[0.0, 2.93, 520.0, 4.0]]
For pfx files from SSL for Free I find this https://decoder.link/converter easiest.
Simply make sure PEM
-> PKCS#12
is selected, then upload the certificate, ca_bundle and key files and convert.
Remember the password, then upload with the password you used and add bindings.
Just a few other random ideas for completeness's sake. If they work for you, use them. Otherwise, you're probably better off trying something else.
You could also do this with a dictionary:
>>> x = {'cond1' : 'val1', 'cond2' : 'val2'}
>>> y = {'cond1' : 'val1', 'cond2' : 'val2'}
>>> x == y
True
This option is more complicated, but you may also find it useful:
class Klass(object):
def __init__(self, some_vars):
#initialize conditions here
def __nonzero__(self):
return (self.cond1 == 'val1' and self.cond2 == 'val2' and
self.cond3 == 'val3' and self.cond4 == 'val4')
foo = Klass()
if foo:
print "foo is true!"
else:
print "foo is false!"
Dunno if that works for you, but it's another option to consider. Here's one more way:
class Klass(object):
def __init__(self):
#initialize conditions here
def __eq__(self):
return (self.cond1 == 'val1' and self.cond2 == 'val2' and
self.cond3 == 'val3' and self.cond4 == 'val4')
x = Klass(some_values)
y = Klass(some_other_values)
if x == y:
print 'x == y'
else:
print 'x!=y'
The last two I haven't tested, but the concepts should be enough to get you going if that's what you want to go with.
(And for the record, if this is just a one time thing, you're probably just better off using the method you presented at first. If you're doing the comparison in lots of places, these methods may enhance readability enough to make you not feel so bad about the fact that they are kind of hacky.)
I solved it downgrading in gradle from
compile 'com.android.support:design:23.1.0'
to
compile 'com.android.support:design:23.0.1'
It seems like I always get problems when I update any component of Android Studio. Getting tired of it.
I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!
Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:
input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"
where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!
Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.
Comments please??
In JavaScript, primitive types such as integers and strings are passed by value whereas objects are passed by reference. So in order to achieve this you need to use an object:
// declare an object with property x
var obj = { x: 1 };
var aliasToObj = obj;
aliasToObj.x ++;
alert( obj.x ); // displays 2