It's declaring the string as nvarchar
data type, rather than varchar
You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.
To quote from Microsoft:
Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.
If you want to know the difference between these two data types, see this SO post:
For me I got NumberFormatException when trying to deal with the negative numbers. I used the following for the negative and positive numbers.
System.out.println(Integer.parseUnsignedInt("11111111111111111111111111110111", 2));
Output : -9
Based on the answers and comments given by Klass and Kevin Ballard above, I would go with:
println(_stdlib_getDemangledTypeName(now).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(soon).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(soon?).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(soon!).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(myvar0).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(myvar1).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(myvar2).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(myvar3).componentsSeparatedByString(".").last!)
which will print out:
"NSDate"
"ImplicitlyUnwrappedOptional"
"Optional"
"NSDate"
"NSString"
"PureSwiftClass"
"Int"
"Double"
You can import database afterwards:
docker exec -i mysql-container mysql -uuser -ppassword name_db < data.sql
You could use Directory.GetCurrentDirectory
:
var path = Path.Combine(Directory.GetCurrentDirectory(), "\\fileName.txt");
Which will look for the file fileName.txt
in the current directory of the application.
-- IN arguments : you get them. You can modify them locally but caller won't see it
-- IN OUT arguments: initialized by caller, already have a value, you can modify them and the caller will see it
-- OUT arguments: they're reinitialized by the procedure, the caller will see the final value.
CREATE PROCEDURE f (p IN NUMBER, x IN OUT NUMBER, y OUT NUMBER)
IS
BEGIN
x:=x * p;
y:=4 * p;
END;
/
SET SERVEROUTPUT ON
declare
foo number := 30;
bar number := 0;
begin
f(5,foo,bar);
dbms_output.put_line(foo || ' ' || bar);
end;
/
-- Procedure output can be collected from variables x and y (ans1:= x and ans2:=y) will be: 150 and 20 respectively.
-- Answer borrowed from: https://stackoverflow.com/a/9484228/1661078
You can't do this because the table variables are out of scope.
You would have to declare the table variable inside the dynamic SQL statement or create temporary tables.
I would suggest you read this excellent article on dynamic SQL.
super
is used to call the constructor
, methods
and properties
of parent class.
Use a Linux Live cd/usb and boot an that to be able to directly connect to your wifi hardware or use linux as the main OS with direct access to the wifi card and then use windows as a guest os, I know that this maybe not the ideal way but it will work.
In this case it is just coding style.
Use of var
is only necessary when dealing with anonymous types.
In other situations it's a matter of taste.
You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
You can use below code to get the batch of list.
Iterable<List<T>> batchIds = Iterables.partition(list, batchSize);
You need to import Google Guava library to use above code.
Greg Hewgill's answer is great but if you need more nodes per level you can use a list|dictionary to create them: And then use method to access them either by name or order (like id)
class node(object):
def __init__(self):
self.name=None
self.node=[]
self.otherInfo = None
self.prev=None
def nex(self,child):
"Gets a node by number"
return self.node[child]
def prev(self):
return self.prev
def goto(self,data):
"Gets the node by name"
for child in range(0,len(self.node)):
if(self.node[child].name==data):
return self.node[child]
def add(self):
node1=node()
self.node.append(node1)
node1.prev=self
return node1
Now just create a root and build it up: ex:
tree=node() #create a node
tree.name="root" #name it root
tree.otherInfo="blue" #or what ever
tree=tree.add() #add a node to the root
tree.name="node1" #name it
root
/
child1
tree=tree.add()
tree.name="grandchild1"
root
/
child1
/
grandchild1
tree=tree.prev()
tree=tree.add()
tree.name="gchild2"
root
/
child1
/ \
grandchild1 gchild2
tree=tree.prev()
tree=tree.prev()
tree=tree.add()
tree=tree.name="child2"
root
/ \
child1 child2
/ \
grandchild1 gchild2
tree=tree.prev()
tree=tree.goto("child1") or tree=tree.nex(0)
tree.name="changed"
root
/ \
changed child2
/ \
grandchild1 gchild2
That should be enough for you to start figuring out how to make this work
Be careful, characters like ’ or » are considered as alpha by MySQL. It better to use something like :
IF c BETWEEN 'a' AND 'z' OR c BETWEEN 'A' AND 'Z' OR c BETWEEN '0' AND '9' OR c = '-' THEN
For security reason mysql -u root wont work untill you pass -p in command so try with below way
mysql -u root -p[Enter]
//enter your localhost password
This is not about the difference between Window.ContentRendered
and Window.Loaded
but about what how the Window.Loaded
event can be used:
I use it to avoid splash screens in all applications which need a long time to come up.
// initializing my main window
public MyAppMainWindow()
{
InitializeComponent();
// Set the event
this.ContentRendered += MyAppMainWindow_ContentRendered;
}
private void MyAppMainWindow_ContentRendered(object sender, EventArgs e)
{
// ... comes up quick when the controls are loaded and rendered
// unset the event
this.ContentRendered -= MyAppMainWindow_ContentRendered;
// ... make the time comsuming init stuff here
}
A char
variable is actually an 8-bit integral value. It will have values from 0
to 255
. These are ASCII codes. 0
stands for the C-null character, and 255
stands for an empty symbol.
So, when you write the following assignment:
char a = 'a';
It is the same thing as:
char a = 97;
So, you can compare two char
variables using the >
, <
, ==
, <=
, >=
operators:
char a = 'a';
char b = 'b';
if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);
Use the command svn status on your working copy to show the status of files, files that are not yet under version control (and not ignored) will have a question mark next to them.
As for ignoring files you need to edit the svn:ignore property, read the chapter Ignoring Unversioned Items in the svnbook at http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.ignore.html. The book also describes more about using svn status.
Clyde's solution works, but it is a broadcast, which I am pretty sure will be less efficient than calling a method directly. I could be mistaken, but I think the broadcasts are meant more for inter-application communication.
I'm assuming you already know how to bind a service with an Activity. I do something sort of like the code below to handle this kind of problem:
class MyService extends Service {
MyFragment mMyFragment = null;
MyFragment mMyOtherFragment = null;
private void networkLoop() {
...
//received new data for list.
if(myFragment != null)
myFragment.updateList();
}
...
//received new data for textView
if(myFragment !=null)
myFragment.updateText();
...
//received new data for textView
if(myOtherFragment !=null)
myOtherFragment.updateSomething();
...
}
}
class MyFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=null;
}
public void updateList() {
runOnUiThread(new Runnable() {
public void run() {
//Update the list.
}
});
}
public void updateText() {
//as above
}
}
class MyOtherFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=null;
}
public void updateSomething() {//etc... }
}
I left out bits for thread safety, which is essential. Make sure to use locks or something like that when checking and using or changing the fragment references on the service.
If you are using Jackson do a lot of JsonNode
building in code, you may be interesting in the following set of utilities. The benefit of using them is that they support a more natural chaining style that better shows the structure of the JSON under construction.
Here is an example usage:
import static JsonNodeBuilders.array;
import static JsonNodeBuilders.object;
...
val request = object("x", "1").with("y", array(object("z", "2"))).end();
Which is equivalent to the following JSON:
{"x":"1", "y": [{"z": "2"}]}
Here are the classes:
import static lombok.AccessLevel.PRIVATE;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;
/**
* Convenience {@link JsonNode} builder.
*/
@NoArgsConstructor(access = PRIVATE)
public final class JsonNodeBuilders {
/**
* Factory methods for an {@link ObjectNode} builder.
*/
public static ObjectNodeBuilder object() {
return object(JsonNodeFactory.instance);
}
public static ObjectNodeBuilder object(@NonNull String k1, boolean v1) {
return object().with(k1, v1);
}
public static ObjectNodeBuilder object(@NonNull String k1, int v1) {
return object().with(k1, v1);
}
public static ObjectNodeBuilder object(@NonNull String k1, float v1) {
return object().with(k1, v1);
}
public static ObjectNodeBuilder object(@NonNull String k1, String v1) {
return object().with(k1, v1);
}
public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2) {
return object(k1, v1).with(k2, v2);
}
public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2,
@NonNull String k3, String v3) {
return object(k1, v1, k2, v2).with(k3, v3);
}
public static ObjectNodeBuilder object(@NonNull String k1, JsonNodeBuilder<?> builder) {
return object().with(k1, builder);
}
public static ObjectNodeBuilder object(JsonNodeFactory factory) {
return new ObjectNodeBuilder(factory);
}
/**
* Factory methods for an {@link ArrayNode} builder.
*/
public static ArrayNodeBuilder array() {
return array(JsonNodeFactory.instance);
}
public static ArrayNodeBuilder array(@NonNull boolean... values) {
return array().with(values);
}
public static ArrayNodeBuilder array(@NonNull int... values) {
return array().with(values);
}
public static ArrayNodeBuilder array(@NonNull String... values) {
return array().with(values);
}
public static ArrayNodeBuilder array(@NonNull JsonNodeBuilder<?>... builders) {
return array().with(builders);
}
public static ArrayNodeBuilder array(JsonNodeFactory factory) {
return new ArrayNodeBuilder(factory);
}
public interface JsonNodeBuilder<T extends JsonNode> {
/**
* Construct and return the {@link JsonNode} instance.
*/
T end();
}
@RequiredArgsConstructor
private static abstract class AbstractNodeBuilder<T extends JsonNode> implements JsonNodeBuilder<T> {
/**
* The source of values.
*/
@NonNull
protected final JsonNodeFactory factory;
/**
* The value under construction.
*/
@NonNull
protected final T node;
/**
* Returns a valid JSON string, so long as {@code POJONode}s not used.
*/
@Override
public String toString() {
return node.toString();
}
}
public final static class ObjectNodeBuilder extends AbstractNodeBuilder<ObjectNode> {
private ObjectNodeBuilder(JsonNodeFactory factory) {
super(factory, factory.objectNode());
}
public ObjectNodeBuilder withNull(@NonNull String field) {
return with(field, factory.nullNode());
}
public ObjectNodeBuilder with(@NonNull String field, int value) {
return with(field, factory.numberNode(value));
}
public ObjectNodeBuilder with(@NonNull String field, float value) {
return with(field, factory.numberNode(value));
}
public ObjectNodeBuilder with(@NonNull String field, boolean value) {
return with(field, factory.booleanNode(value));
}
public ObjectNodeBuilder with(@NonNull String field, String value) {
return with(field, factory.textNode(value));
}
public ObjectNodeBuilder with(@NonNull String field, JsonNode value) {
node.set(field, value);
return this;
}
public ObjectNodeBuilder with(@NonNull String field, @NonNull JsonNodeBuilder<?> builder) {
return with(field, builder.end());
}
public ObjectNodeBuilder withPOJO(@NonNull String field, @NonNull Object pojo) {
return with(field, factory.pojoNode(pojo));
}
@Override
public ObjectNode end() {
return node;
}
}
public final static class ArrayNodeBuilder extends AbstractNodeBuilder<ArrayNode> {
private ArrayNodeBuilder(JsonNodeFactory factory) {
super(factory, factory.arrayNode());
}
public ArrayNodeBuilder with(boolean value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(@NonNull boolean... values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(int value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(@NonNull int... values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(float value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(String value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(@NonNull String... values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(@NonNull Iterable<String> values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(JsonNode value) {
node.add(value);
return this;
}
public ArrayNodeBuilder with(@NonNull JsonNode... values) {
for (val value : values)
with(value);
return this;
}
public ArrayNodeBuilder with(JsonNodeBuilder<?> value) {
return with(value.end());
}
public ArrayNodeBuilder with(@NonNull JsonNodeBuilder<?>... builders) {
for (val builder : builders)
with(builder);
return this;
}
@Override
public ArrayNode end() {
return node;
}
}
}
Note that the implementation uses Lombok, but you can easily desugar it to fill in the Java boilerplate.
static void Main(string[] args)
{
Console.WriteLine("geef een leeftijd");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("geef een leeftijd");
int b = Convert.ToInt32(Console.ReadLine());
int einde = Sum(a, b);
Console.WriteLine(einde);
}
static int Sum(int x, int y)
{
int result = x + y;
return result;
This seems to be clean.
public enum Plane{
/**
* BOEING_747 plane.
*/
BOEING_747("BOEING_747"),
/**
* AIRBUS_A380 Plane.
*/
AIRBUS_A380("AIRBUS_A380"),
;
private final String plane;
private Plane(final String plane) {
this.plane= plane;
}
Plane(){
plane=null;
}
/**
* toString method.
*
* @return Value of this Enum as String.
*/
@Override
public String toString(){
return plane;
}
/**
* This method add support to compare Strings with the equalsIgnoreCase String method.
*
* Replicated functionality of the equalsIgnorecase of the java.lang.String.class
*
* @param value String to test.
* @return True if equal otherwise false.
*/
public boolean equalsIgnoreCase(final String value){
return plane.equalsIgnoreCase(value);
}
And then in main code:
String airplane="BOEING_747";
if(Plane.BOEING_747.equalsIgnoreCase(airplane)){
//code
}
If there is someone interested in achieve the @Pedro Silva solution in JS, I just ported this same solution for it:
const getBase64Size = (base64) => {
let padding = base64.length
? getBase64Padding(base64)
: 0
return ((Math.ceil(base64.length / 4) * 3 ) - padding) / 1000
}
const getBase64Padding = (base64) => {
return endsWith(base64, '==')
? 2
: 1
}
const endsWith = (str, end) => {
let charsFromEnd = end.length
let extractedEnd = str.slice(-charsFromEnd)
return extractedEnd === end
}
There should be a binary called "pip2.7" installed at some location included within your $PATH variable.
You can find that out by typing
which pip2.7
This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py
Now, you should be all set, and
which pip2.7
should return the correct output.
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Solution:
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
Model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}
df = df_try
for i in range(4):
df = df.append(df_try)
# Here, we have df_try times 5
df = df.append(df)
# Here, we have df_try times 10
I recommend not doing this...
What you are describing is not a comprehension.
PEP 8 Style Guide for Python Code, which I do recommend, has this to say on compound statements:
- Compound statements (multiple statements on the same line) are generally discouraged.
Yes:
if foo == 'blah': do_blah_thing() do_one() do_two() do_three()
Rather not:
if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three()
Here is a sample comprehension to make the distinction:
>>> [i for i in xrange(10) if i == 9]
[9]
Are you moving it using svn mv
, or just mv
? I think using just mv
may cause this issue.
Http 415 Media Unsupported
is responded back only when the content type header you are providing is not supported by the application.
With POSTMAN, the Content-type
header you are sending is Content type 'multipart/form-data
not application/json
. While in the ajax code you are setting it correctly to application/json
. Pass the correct Content-type header in POSTMAN and it will work.
foreach (GridViewRow gvr in gvMyGridView.Rows)
{
string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}
You can use this code while doing an iteration with foreach
or for any GridView event like OnRowDataBound
.
Here you can input multiple values for DataKeyNames
by separating with comma ,
. For example, DataKeyNames="ProductID,ItemID,OrderID"
.
You can now access each of DataKeys
by providing its index like below:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values[2].ToString();
You can also use Key Name instead of its index to get the values from DataKeyNames
collection like below:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ProductID"].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ItemID"].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values["OrderID"].ToString();
I use the following to successfully redirect all pages of my domain from http to https:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Note this will redirect using the 301 'permanently moved'
redirect, which will help transfer your SEO rankings.
To redirect using the 302 'temporarily moved'
change [R=302,L]
I had to run "rehash" and then it was able to find the jupyter command
For a pure Ruby solution combine URI.parse
with CGI.parse
(this can be used even if Rails/Rack etc. are not required):
CGI.parse(URI.parse(url).query)
# => {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }
You should use the ARG
directive in your Dockerfile which is meant for this purpose.
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.
So your Dockerfile will have this line:
ARG request_domain
or if you'd prefer a default value:
ARG request_domain=127.0.0.1
Now you can reference this variable inside your Dockerfile:
ENV request_domain=$request_domain
then you will build your container like so:
$ docker build --build-arg request_domain=mydomain Dockerfile
Note 1: Your image will not build if you have referenced an ARG
in your Dockerfile but excluded it in --build-arg
.
Note 2: If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:
[Warning] One or more build-args [foo] were not consumed.
as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:
First Solution
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
Second Solution: in this solution you can create an array of input values:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
If you use
ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"
instead of
ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'
your shell will interpolate the $BUILD_NUMBER
before sending the command string to the remote host.
None of these worked for me in Ubuntu 16.4.
Yet another answer, that uses stold
(though you could also use stof
/stod
if you don't require the precision).
bool isNumeric(const std::string& string)
{
std::size_t pos;
long double value = 0.0;
try
{
value = std::stold(string, &pos);
}
catch(std::invalid_argument&)
{
return false;
}
catch(std::out_of_range&)
{
return false;
}
return pos == string.size() && !std::isnan(value);
}
you can use hidden property of element:
document.getElementById("test").hidden=true;
document.getElementById("test").hidden=false
sklearn
estimators implement methods to make it easy for you to save relevant trained properties of an estimator. Some estimators implement __getstate__
methods themselves, but others, like the GMM
just use the base implementation which simply saves the objects inner dictionary:
def __getstate__(self):
try:
state = super(BaseEstimator, self).__getstate__()
except AttributeError:
state = self.__dict__.copy()
if type(self).__module__.startswith('sklearn.'):
return dict(state.items(), _sklearn_version=__version__)
else:
return state
The recommended method to save your model to disc is to use the pickle
module:
from sklearn import datasets
from sklearn.svm import SVC
iris = datasets.load_iris()
X = iris.data[:100, :2]
y = iris.target[:100]
model = SVC()
model.fit(X,y)
import pickle
with open('mymodel','wb') as f:
pickle.dump(model,f)
However, you should save additional data so you can retrain your model in the future, or suffer dire consequences (such as being locked into an old version of sklearn).
From the documentation:
In order to rebuild a similar model with future versions of scikit-learn, additional metadata should be saved along the pickled model:
The training data, e.g. a reference to a immutable snapshot
The python source code used to generate the model
The versions of scikit-learn and its dependencies
The cross validation score obtained on the training data
This is especially true for Ensemble estimators that rely on the tree.pyx
module written in Cython(such as IsolationForest
), since it creates a coupling to the implementation, which is not guaranteed to be stable between versions of sklearn. It has seen backwards incompatible changes in the past.
If your models become very large and loading becomes a nuisance, you can also use the more efficient joblib
. From the documentation:
In the specific case of the scikit, it may be more interesting to use joblib’s replacement of
pickle
(joblib.dump
&joblib.load
), which is more efficient on objects that carry large numpy arrays internally as is often the case for fitted scikit-learn estimators, but can only pickle to the disk and not to a string:
Adding padding to an inner div
, as in the currently accepted answer, won't work if for some reason you want to use box-model: border-box
.
What does work in both cases is increasing the width of the inner div
to 100% plus the scrollbar's width (assuming overflow: hidden
on the outer div).
For example, in CSS:
.container2 {
width: calc(100% + 19px);
}
In JavaScript, cross-browser:
var child = document.getElementById('container2');
var addWidth = child.offsetWidth - child.clientWidth + "px";
child.style.width = 'calc(100% + ' + addWidth + ')';
The "-r" option is invalid on my systems. I had to use a different syntax for the "From" field.
-a "From: Foo Bar <[email protected]>"
I can't find a scenario that cannot be solved using node-fibers. The example you provided using node-fibers behaves as expected. The key is to run all the relevant code inside a fiber, so you don't have to start a new fiber in random positions.
Lets see an example: Say you use some framework, which is the entry point of your application (you cannot modify this framework). This framework loads nodejs modules as plugins, and calls some methods on the plugins. Lets say this framework only accepts synchronous functions, and does not use fibers by itself.
There is a library that you want to use in one of your plugins, but this library is async, and you don't want to modify it either.
The main thread cannot be yielded when no fiber is running, but you still can create plugins using fibers! Just create a wrapper entry that starts the whole framework inside a fiber, so you can yield the execution from the plugins.
Downside: If the framework uses setTimeout
or Promise
s internally, then it will escape the fiber context. This can be worked around by mocking setTimeout
, Promise.then
, and all event handlers.
So this is how you can yield a fiber until a Promise
is resolved. This code takes an async (Promise returning) function and resumes the fiber when the promise is resolved:
framework-entry.js
console.log(require("./my-plugin").run());
async-lib.js
exports.getValueAsync = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve("Async Value");
}, 100);
});
};
my-plugin.js
const Fiber = require("fibers");
function fiberWaitFor(promiseOrValue) {
var fiber = Fiber.current, error, value;
Promise.resolve(promiseOrValue).then(v => {
error = false;
value = v;
fiber.run();
}, e => {
error = true;
value = e;
fiber.run();
});
Fiber.yield();
if (error) {
throw value;
} else {
return value;
}
}
const asyncLib = require("./async-lib");
exports.run = () => {
return fiberWaitFor(asyncLib.getValueAsync());
};
my-entry.js
require("fibers")(() => {
require("./framework-entry");
}).run();
When you run node framework-entry.js
it will throw an error: Error: yield() called with no fiber running
. If you run node my-entry.js
it works as expected.
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
If you're on Windows then it's a total no-brainer: Get Visual C++ Express.
render: function(){
return(
<div>
<input type="text" id="one" onKeyDown={this.add} />
</div>
);
}
onKeyDown
detects keyCode
events.
I've created library to traverse and edit deep nested JS objects. Check out API here: https://github.com/dominik791
You can also play with the library interactively using demo app: https://dominik791.github.io/obj-traverse-demo/
Examples of usage: You should always have root object which is the first parameter of each method:
var rootObj = {
name: 'rootObject',
children: [
{
'name': 'child1',
children: [ ... ]
},
{
'name': 'child2',
children: [ ... ]
}
]
};
The second parameter is always the name of property that holds nested objects. In above case it would be 'children'
.
The third parameter is an object that you use to find object/objects that you want to find/modify/delete. For example if you're looking for object with id equal to 1, then you will pass { id: 1}
as the third parameter.
And you can:
findFirst(rootObj, 'children', { id: 1 })
to find first object
with id === 1
findAll(rootObj, 'children', { id: 1 })
to find all objects
with id === 1
findAndDeleteFirst(rootObj, 'children', { id: 1 })
to delete first matching objectfindAndDeleteAll(rootObj, 'children', { id: 1 })
to delete all matching objectsreplacementObj
is used as the last parameter in two last methods:
findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change first found object with id === 1
to the { id: 2, name: 'newObj'}
findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change all objects with id === 1
to the { id: 2, name: 'newObj'}
function getRemote() {
return $.ajax({
type: "GET",
url: remote_url,
async: false,
success: function (result) {
/* if result is a JSon object */
if (result.valid)
return true;
else
return false;
}
});
}
I had same problem. it happen because javascript
expect json
data type in returning data. but if you use echo or print in your php this situation occur. if you use echo
function in php
to return data, Simply remove dataType : "json"
working pretty well.
The '\r'
character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.
From the old telnet specification (RFC 854) (page 11):
The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").
However, from the latest specification (RFC5198) (page 13):
...
In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.
LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).
So newline in Telnet should always be '\r\n'
but most implementations have either not been updated, or keeps the old '\n\r'
for backwards compatibility.
Since std::string
in C++ is mutable you can use that. It has a += operator
and an append
function.
If you need to append numerical data use the std::to_string
functions.
If you want even more flexibility in the form of being able to serialise any object to a string then use the std::stringstream
class. But you'll need to implement your own streaming operator functions for it to work with your own custom classes.
git reset --soft HEAD~1
git pull
Use any()
.
if any(t < 0 for t in x):
# do something
My solution is:
$maxs = array_keys($array, max($array))
Note:
this way you can retrieve every key related to a given max value.
If you are interested only in one key among all simply use $maxs[0]
You can use .ndim
for dimension and .shape
to know the exact dimension
var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]])
var.ndim
# displays 2
var.shape
# display 6, 2
You can change the dimension using .reshape
function
var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]]).reshape(3,4)
var.ndim
#display 2
var.shape
#display 3, 4
a very simple solution would be, and I see you have said that you would like to see the simplest solution possible. A prompt for the user to continue after halting a loop Etc.
raw_input("Press<enter> to continue")
.a
files are created with the ar
utility, and they are libraries. To use it with gcc
, collect all .a files
in a lib/
folder and then link with -L lib/
and -l<name of specific library>
.
Collection of all .a files into lib/
is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.
The margins vary depending on the printer. In Windows GDI, you call the following functions to get the built-in margins, the "no-print zone":
GetDeviceCaps(hdc, PHYSICALWIDTH);
GetDeviceCaps(hdc, PHYSICALHEIGHT);
GetDeviceCaps(hdc, PHYSICALOFFSETX);
GetDeviceCaps(hdc, PHYSICALOFFSETY);
Printing right to the edge is called a "bleed" in the printing industry. The only laser printer I ever knew to print right to the edge was the Xerox 9700: 120 ppm, $500K in 1980.
A void pointer is known as generic pointer, which can refer to variables of any data type.
Interestingly, http://maps.apple.com
links will open directly in Apple Maps on an iOS device, or redirect to Google Maps otherwise (which is then intercepted on an Android device), so you can craft a careful URL that will do the right thing in both cases using an "Apple Maps" URL like:
http://maps.apple.com/?daddr=1600+Amphitheatre+Pkwy,+Mountain+View+CA
Alternatively, you can use a Google Maps url directly (without the /maps
URL component) to open directly in Google Maps on an Android device, or open in Google Maps' Mobile Web on an iOS device:
http://maps.google.com/?daddr=1+Infinite+Loop,+Cupertino+CA
DateTime.Today
is DateTime.Now
with time set to zero.
It is important to note that there is a difference between a DateTime value, which represents the number of ticks that have elapsed since midnight of January 1, 0000, and the string representation of that DateTime value, which expresses a date and time value in a culture-specific-specific format: https://msdn.microsoft.com/en-us/library/system.datetime.now%28v=vs.110%29.aspx
DateTime.Now.Ticks
is the actual time stored by .net (essentially UTC time), the rest are just representations (which are important for display purposes).
If the Kind
property is DateTimeKind.Local
it implicitly includes the time zone information of the local computer. When sending over a .net web service, DateTime values are by default serialized with time zone information included, e.g. 2008-10-31T15:07:38.6875000-05:00, and a computer in another time zone can still exactly know what time is being referred to.
So, using DateTime.Now and DateTime.Today is perfectly OK.
You usually start running into trouble when you begin confusing the string representation with the actual value and try to "fix" the DateTime, when it isn't broken.
Using the AWS Management Console
If the newline is expected to be at the end of the string, then:
if (!s.empty() && s[s.length()-1] == '\n') {
s.erase(s.length()-1);
}
If the string can contain many newlines anywhere in the string:
std::string::size_type i = 0;
while (i < s.length()) {
i = s.find('\n', i);
if (i == std::string:npos) {
break;
}
s.erase(i);
}
If you are seeing an error something like
error on line -1 c:apacheconfopenssl.cnf
try changing from back slash to front slash in the -config.
Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort()
.
See the documentation:
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
UPDATE: As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See The jqXHR Object (jQuery API documentation).
UPDATE 2:
As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an xhr
any more. See the 3.0 blog here.
UPDATE 3: xhr.abort()
still works on jQuery 3.x. Don't assume the update 2 is correct. More info on jQuery Github repository.
.toString() is the built-in typecasting function, I'm no expert to that details but whenever we compare built-in type casting verse explicit methodologies, built-in workarounds always preferred.
I too have been through this pain - if the query is dynamically generated (e.g. Hibernate Criteria) then I couldn't find a practical way to do it.
The good news for me was that I was only investigating union to solve a performance problem when using an 'or' in an Oracle database.
The solution Patrick posted (combining the results programmatically using a set) while ugly (especially since I wanted to do results paging as well) was adequate for me.
You can use the Math.abs(number) function. It returns a positive number.
Given your Object:
var foo = { 'bar' : 'baz' }
To get bar
, use:
Object.keys(foo)[0]
To get baz
, use:
foo[Object.keys(foo)[0]]
Assuming a single object
I am giving one exapmle to undersand when do we use @Queryparam
and @pathparam
For example I am taking one resouce is carResource
class
If you want to make the inputs of your resouce method manadatory then use the param type as @pathaparam
, if the inputs of your resource method should be optional then keep that param type as @QueryParam
param
@Path("/car")
class CarResource
{
@Get
@produces("text/plain")
@Path("/search/{carmodel}")
public String getCarSearch(@PathParam("carmodel")String model,@QueryParam("carcolor")String color) {
//logic for getting cars based on carmodel and color
-----
return cars
}
}
For this resouce pass the request
req uri ://address:2020/carWeb/car/search/swift?carcolor=red
If you give req like this the resouce will gives the based car model and color
req uri://address:2020/carWeb/car/search/swift
If you give req like this the resoce method will display only swift model based car
req://address:2020/carWeb/car/search?carcolor=red
If you give like this we will get ResourceNotFound exception because in the car resouce class I declared carmodel as @pathPram
that is you must and should give the carmodel as reQ uri otherwise it will not pass the req to resouce but if you don't pass the color also it will pass the req to resource why because the color is @quetyParam
it is optional in req.
Simply floating both elements left achieves the same result.
div {
background:yellow;
vertical-align:middle;
margin:10px;
}
a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}
span {
background:red;
display:inline-block;
float:left;
}
You could try this:
#include <stdio.h>
int main()
{
int i,j;
int my_array[3][3] ={10, 23, 42, 1, 654, 0, 40652, 22, 0};
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d ", my_array[i][j]);
}
printf("\n");
}
return 0;
}
As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data
with participants
.
The alternative to the solution they provided would be to prevent render until participants exist, something like this:
render: function() {
if (!this.props.data.participants) {
return null;
}
return (
<ul className="PlayerList">
// I'm the Player List {this.props.data}
// <Player author="The Mini John" />
{
this.props.data.participants.map(function(player) {
return <li key={player}>{player}</li>
})
}
</ul>
);
}
To run the .bat, and have access to the last exit code, run it as:
& .\my-app\my-fle.bat
Assuming your separator is '...', but it can be any string.
text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')
>>> print head
some string
If the separator is not found, head
will contain all of the original string.
The partition function was added in Python 2.5.
partition(...) S.partition(sep) -> (head, sep, tail)
Searches for the separator sep in S, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns S and two empty strings.
It's in the python docs.
import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1),
datetime.time(10, 23))
returns
datetime.datetime(2011, 1, 1, 10, 23)
Two of the most common
First way :
let jsonData = require('./JsonFile.json')
let jsonData = require('./JsonFile')
// if we omitting .json also works
OR
import jsonData from ('./JsonFile.json')
Second way :
1) synchronously
const fs = require('fs')
let jsonData = JSON.parse(fs.readFileSync('JsonFile.json', 'utf-8'))
2) asynchronously
const fs = require('fs')
let jsonData = {}
fs.readFile('JsonFile.json', 'utf-8', (err, data) => {
if (err) throw err
jsonData = JSON.parse(data)
})
Note: 1) if we JsonFile.json is changed, we not get the new data, even if we re run require('./JsonFile.json')
2) The fs.readFile or fs.readFileSync will always re read the file, and get changes
Spaces are simply replaced by "%20" like :
There are a few things wrong here:
First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".
.unix()
returns Unix Time in whole seconds, but the default moment
constructor accepts a timestamp in milliseconds. You should instead use .valueOf()
to return milliseconds. Note that calling .unix()*1000
would also work, but it would result in a loss of precision.
You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:
moment("10/15/2014 9:00", "M/D/YYYY H:mm")
.calendar()
has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format()
function instead. Again, you may want to pass a format specifier.
To answer your questions in comments, No - you don't need to call .local()
or .utc()
.
Putting it all together:
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);
On my machine, in the US Pacific time zone, it results in:
Values are: ts = 1413388800000, s = 10/15/2014 9:00
Since the input value is interpreted in terms of local time, you will get a different value for ts
if you are in a different time zone.
Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix()
to return the timestamp in whole seconds, and moment.unix(ts)
to parse it back to a moment.
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);
That's pretty much all you need:
mysql> select * from t;
+------+-------+
| id | data |
+------+-------+
| 1 | max |
| 2 | linda |
| 3 | sam |
| 4 | henry |
+------+-------+
4 rows in set (0.02 sec)
mysql> update t set data=concat(data, 'a');
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4 Changed: 4 Warnings: 0
mysql> select * from t;
+------+--------+
| id | data |
+------+--------+
| 1 | maxa |
| 2 | lindaa |
| 3 | sama |
| 4 | henrya |
+------+--------+
4 rows in set (0.00 sec)
Not sure why you'd be having trouble, though I am testing this on 5.1.41
update 2019-09-29: Java version 11
The technique below does not now work with Java 11, and probably higher versions: there is no way of ignoring multiple "broken links" (i.e. to other classes, other APIs). Solution: keep your javadoc executable file (or javadoc.exe) from Java version 8
There are good reasons for making your own local javadocs, and it's not particularly difficult!
First you need the source. At the time of writing the Java 8 JDK comes with a zip file called src.zip
. Sometimes, for unexplained reasons, Oracle don't always include the source. So for some older versions (and who knows about the future) you have to get hold of the Java source in another way. It's worth also being aware that, in the past, Oracle have sometimes included the source with the Linux version of the JDK, but not with the Windows one.
I just unzipped this file... the top directories are "com", "java", "javax", "launcher" and "org". Directory launcher
contains no files to document.
You can generate the javadocs very very simply from any or all of these by CD'ing at the command prompt/terminal to the directory ...\src
. Then go
javadoc -d docs -Xmaxwarns 10 -Xmaxerrs 10 -Xdoclint:none -sourcepath . -subpackages java:javax:org:com
NB note that there is a "." after -sourcepath
Simple as that. Generating your own javadocs also has 2 huge advantages
NB Swing is semi-officially DEAD. We should all be switching to JavaFX, which is helpfully bundled with Java 8 JDK, but in its own source file, javafx-src.zip
.
Unzipped, this reveals 3 "root" packages: com
, javafx
and netscape
(wha'?). These should be manually moved over the to appropriate places under the unzipped src
directory (including the JavaFX com.sun
packages under the Java com.sun
strcture). Compiling all these Javadoc files took my machine a non-negligible time. I'd expect to see all the JavaFX source classes in with all the other source classes some time soon.
BTW, the same thinking applies to documenting any and all Java jars (with source) which you use. However, all versions of most jars will be found with their documentation available for download at Maven Central http://search.maven.org...
PS afterthought:
using Eclipse and the "Gradle STS" plugin: the "New Gradle STS Project" wizard will create a gradle.build
file containing the line
include plugin: 'eclipse'
This magically downloads the source jar with the executable jar (under GRADLE_HOME
) when you go
./gradlew build
[addendum 2020-01-13: if you have chosen not to include the Eclipse plugin in your build.gradle, it would appear that you can go (with the selection on your project in the Project Explorer) Right-click Gradle
--> Refresh Gradle Project
to get Eclipse to download the source files.]
... giving you an extra degree of certainty that you have got the right src
and therefore the right javadoc
for the dependency in question.
Isn't this the same:
if ((checkbox.checked || columnname != A2) &&
columnname != a && columnname != b && columnname != c)
{
"statement 1"
}
You don't need JavaScript for this. Just wanted to make that clear, since as of the time this answer was posted, all of the answers to this question involve the use of JavaScript in some way or another.
You can do this rather easily with pure HTML and CSS by creating a form with hidden fields containing the data you want to submit, then styling the submit button of the form to look like a link.
For example:
.inline {_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
.link-button {_x000D_
background: none;_x000D_
border: none;_x000D_
color: blue;_x000D_
text-decoration: underline;_x000D_
cursor: pointer;_x000D_
font-size: 1em;_x000D_
font-family: serif;_x000D_
}_x000D_
.link-button:focus {_x000D_
outline: none;_x000D_
}_x000D_
.link-button:active {_x000D_
color:red;_x000D_
}
_x000D_
<a href="some_page">This is a regular link</a>_x000D_
_x000D_
<form method="post" action="some_page" class="inline">_x000D_
<input type="hidden" name="extra_submit_param" value="extra_submit_value">_x000D_
<button type="submit" name="submit_param" value="submit_value" class="link-button">_x000D_
This is a link that sends a POST request_x000D_
</button>_x000D_
</form>
_x000D_
The exact CSS you use may vary depending on how regular links on your site are styled.
For me it was a mistake in the pom.xml
- I'd set <scope>provided<scope>
on my dependencies, and this was making them not get copied during the mvn package
stage.
My symptoms were the error message the OP posted, and that the jars were not included in the WEB-INF/lib path inside the .war after package was run. When I removed the scope, the jars appeared in the output, and all loads up fine now.
Check - LSNRCTL> stat I got result like -
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1522)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for 32-bit Windows: Version 11.2.0.1.0 - Production
Start Date 17-APR-2016 10:12:38
Uptime 0 days 10 hr. 6 min. 16 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File
C:\product\11.2.0\dbhome_1\network\admin\listener.ora
Listener Log File c:\app\admin\diag\tnslsnr\admin-PC\listener\alert\log.xml Listening
Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1522ipc)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1522)))
Services Summary... Service "CLRExtProc" has 1 instance(s). Instance
"CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
Service "orcl" has 1 instance(s). Instance "orcl", status READY, has 1 handler(s) for this service...
Service "orclXDB" has 1 instance(s).
Instance "orcl", status READY, has 1 handler(s) for this service...
The command completed successfully.
From above details - My port no is - 1522 and i am able to create connection using "orcl" instance - so i used port as 1522 and instance as "orcl" -- Now URL is -
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:orcl", "SYS as SYSDBA","password");
It worked for me So please check LSNRCTL> stat in command prompt and configure your connection url accordingly.
Hope it will help Someone.
Faced this issue of removing the labels in Chartjs now. Looks like the documentation is improved. http://www.chartjs.org/docs/#getting-started-global-chart-configuration
Chart.defaults.global.legend.display = false;
this global settings prevents legends from being shown in all Charts. Since this was enough for me, I used it. I am not sure to how to avoid legends for individual charts.
A simple, although awk-less solution in bash:
while IFS=, read -r a a a b; do echo "$a"; done <inputfile
It works faster for small files (<100 lines) then awk as it uses less resources (avoids calling the expensive fork
and execve
system calls).
EDIT from Ed Morton (sorry for hi-jacking the answer, I don't know if there's a better way to address this):
To put to rest the myth that shell will run faster than awk for small files:
$ wc -l file
99 file
$ time while IFS=, read -r a a a b; do echo "$a"; done <file >/dev/null
real 0m0.016s
user 0m0.000s
sys 0m0.015s
$ time awk -F, '{print $3}' file >/dev/null
real 0m0.016s
user 0m0.000s
sys 0m0.015s
I expect if you get a REALY small enough file then you will see the shell script run in a fraction of a blink of an eye faster than the awk script but who cares?
And if you don't believe that it's harder to write robust shell scripts than awk scripts, look at this bug in the shell script you posted:
$ cat file
a,b,-e,d
$ cut -d, -f3 file
-e
$ awk -F, '{print $3}' file
-e
$ while IFS=, read -r a a a b; do echo "$a"; done <file
$
I believe the part regarding how to span rows has been answered thoroughly (i.e. by nesting rows), but I also ran into the issue of my nested rows not filling their container. While flexbox and negative margins are an option, a much easier solution is to use the predefined h-50
class on the row
containing boxes 2, 3, 4, and 5.
Note: I am using
Bootstrap-4
, I just wanted to share because I ran into the same problem and found this to be a more elegant solution :)
To install and run any version of Python in the same system follow my guide below.
For example say you want to install Python 2.x and Python 3.x on the same Windows system.
Install both of their binary releases anywhere you want.
Running simply the command python
the executable that is first met in PATH will be chosen for launch. In other words, add the Python directories manually. The one you add first will be selected when you type python
. Consecutive python programs (increasing order that their directories are placed in PATH) will be chosen like so:
python
python
etc.. No matter the order of "pythons" you can:
In my example I have Python 2.7.14 installed first and Python 3.5.3. This is how my PATH variable starts with:
PATH=C:\Program Files\Microsoft MPI\Bin\;C:\Python27;C:\Program Files\Python_3.6\Scripts\;C:\Program Files\Python_3.6\;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Intel\Shared
...
Note that Python 2.7 is first and Python 3.5 second.
python
command will launch python 2.7 (if Python 3.5 the same command would launch Python 3.5). py -2
launches Python 2.7 (because it happens that the second Python is Python 3.5 which is incompatible with py -2
).
Running py -3
launches Python 3.5 (because it's Python 3.x) py -4
. This may change if/when Python version 4 is released. Now py -4
or py -5
etc. on my system outputs: Requested Python version (4) not installed
or Requested Python version (5) not installed
etc.
Hopefully this is clear enough.
For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:
# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
Model.where(attributes).first || Model.create(attributes)
end
Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.
For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.
For that need to add the 2021 partition into that table
ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS
As found in other answers, either new Uri()
or TryCreate()
can do the tick.
However, the base Uri has to end with /
and the relative has to NOT begin with /
; otherwise it will remove the trailing part of the base Url
I think this is best done as an extension method, i.e.
public static Uri Append(this Uri uri, string relativePath)
{
var baseUri = uri.AbsoluteUri.EndsWith('/') ? uri : new Uri(uri.AbsoluteUri + '/');
var relative = relativePath.StartsWith('/') ? relativePath.Substring(1) : relativePath;
return new Uri(baseUri, relative);
}
and to use it:
var baseUri = new Uri("http://test.com/test/");
var combinedUri = baseUri.Append("/Do/Something");
In terms of performance, this consumes more resources than it needs, because of the Uri class which does a lot of parsing and validation; a very rough profiling (Debug) did a million operations in about 2 seconds. This will work for most scenarios, however to be more efficient, it's better to manipulate everything as strings, this takes 125 milliseconds for 1 million operations. I.e.
public static string Append(this Uri uri, string relativePath)
{
//avoid the use of Uri as it's not needed, and adds a bit of overhead.
var absoluteUri = uri.AbsoluteUri; //a calculated property, better cache it
var baseUri = absoluteUri.EndsWith('/') ? absoluteUri : absoluteUri + '/';
var relative = relativePath.StartsWith('/') ? relativePath.Substring(1) : relativePath;
return baseUri + relative;
}
And if you still want to return a URI, it takes around 600 milliseconds for 1 million operations.
public static Uri AppendUri(this Uri uri, string relativePath)
{
//avoid the use of Uri as it's not needed, and adds a bit of overhead.
var absoluteUri = uri.AbsoluteUri; //a calculated property, better cache it
var baseUri = absoluteUri.EndsWith('/') ? absoluteUri : absoluteUri + '/';
var relative = relativePath.StartsWith('/') ? relativePath.Substring(1) : relativePath;
return new Uri(baseUri + relative);
}
I hope this helps.
A simple way is.....
#include <stdio.h>
#include <stdlib.h>
#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
"
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate
and send to the system(concatenated_string); */
int main()
{
puts("Will execute sh with the following script :");
puts(SHELLSCRIPT);
puts("Starting now:");
system(SHELLSCRIPT); //it will run the script inside the c code.
return 0;
}
Say thanks to
Yoda @http://www.unix.com/programming/216190-putting-bash-script-c-program.html
As of MongoDB 2.4, you can use $setOnInsert (http://docs.mongodb.org/manual/reference/operator/setOnInsert/)
Set 'insertion_date' using $setOnInsert and 'last_update_date' using $set in your upsert command.
To turn your pseudocode into a working example:
now = datetime.utcnow()
for document in update:
collection.update_one(
{"_id": document["_id"]},
{
"$setOnInsert": {"insertion_date": now},
"$set": {"last_update_date": now},
},
upsert=True,
)
The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.
private void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()
or
string.Concat(foo.ToArray().Select(a => a += ",").ToArray())
Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.
For more advanced and precise math consider using bc(1).
echo "3 * 2.19" | bc -l
6.57
<TextView
android:id="@+id/txt_banner"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_below="@+id/title"
android:background="@drawable/ripple_effect"
android:gravity="center|left"
android:paddingLeft="15dp"
android:text="@string/banner"
android:textSize="15sp" />
Add this into drawable
<?xml version="1.0" encoding="utf-8"?>
<!--this ripple animation only working for >= android version 21 -->
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/click_efect" />
This is little more explanation for pass by value and pass by reference (JavaScript). In this concept, they are talking about passing the variable by reference and passing the variable by reference.
Pass by value (primitive type)
var a = 3;
var b = a;
console.log(a); // a = 3
console.log(b); // b = 3
a=4;
console.log(a); // a = 4
console.log(b); // b = 3
Pass by reference (objects)
var c = { "name" : "john" };
var d = c;
console.log(c); // { "name" : "john" }
console.log(d); // { "name" : "john" }
c.name = "doe";
console.log(c); // { "name" : "doe" }
console.log(d); // { "name" : "doe" }
c
, and it points to some memory, say (0x012).d
points to the same location (0x012).Special case, pass by reference (objects)
c = {"name" : "jane"};
console.log(c); // { "name" : "jane" }
console.log(d); // { "name" : "doe" }
You can use the Ext.util.Format.ellipsis function if you are using Ext.js.
You can download the gradle you want from Gradle Service by reading the gradle-wrapper.properties.Download it ,unpack it where you like and then change your grandle configuration use local not the recommended.
This work out for me :
in javascript :
Axios({
method: 'post',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order
}).then(function (response) {
console.log(response.data);
});
and in the backend (.net core) : in startup:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
and in controller before action
[EnableCors("AllowOrigin")]
system("pause");
is wrong because it's part of Windows API and so it won't work in other operation systems.
You should try to use just objects from C++ standard library. A better solution will be to write:
cin.get();
return 0;
But it will also cause problems if you have other cin
s in your code. Because after each cin
, you'll tap an Enter
or \n
which is a white space character. cin
ignores this character and leaves it in the buffer zone but cin.get()
, gets this remained character. So the control of the program reaches the line return 0
and the console gets closed before letting you see the results.
To solve this, we write the code as follows:
cin.ignore();
cin.get();
return 0;
I found out that composer runs with the php-version /usr/bin/env finds first in $PATH, which is 7.1.33 in my case on MacOs. So shifting mamp's php to the beginning helped me here.
PHPVER=$(/usr/libexec/PlistBuddy -c "print phpVersion" ~/Library/Preferences/de.appsolute.mamppro.plist)
export PATH=/Applications/MAMP/bin/php/php${PHPVER}/bin:$PATH
Read this article on how to convert a silverlight theme to WPF... The have a look at the Silverlight toolkit, thy released loads of free silverlight themes!!!
It is ||
, for example:
select 'Mr ' || ename from emp;
The only "interesting" feature I can think of is that 'x' || null
returns 'x'
, not null
as you might perhaps expect.
I'm not sure of a way to do this in 3D, but in 2D you can use the compass
command.
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
Or you can use print_r
if you don't care about types. If you use print_r
, you can make the second argument TRUE
so it will return instead of echo, useful for...
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
Here's the working code. Works in desktop and mobile browsers. hope it helps. thanks for everyone responding.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Layout</title>
<style type="text/css">
body, html
{
margin: 0; padding: 0; height: 100%; overflow: hidden;
}
#content
{
position:absolute; left: 0; right: 0; bottom: 0; top: 0px;
}
</style>
</head>
<body>
<div id="content">
<iframe width="100%" height="100%" frameborder="0" src="http://cnn.com" />
</div>
</body>
</html>
The best way currently to do the same would be to install LESS command line compiler using
$ npm install -g less jshint recess uglify-js
Once you have done this, then go to the less folder in the directory and then edit the file variables.less and you can change a lot of variables according to what you need including the color of the navigation bar
@navbarCollapseWidth: 979px;
@navbarHeight: 40px;
@navbarBackgroundHighlight: #ffffff;
@navbarBackground: darken(@navbarBackgroundHighlight, 5%);
@navbarBorder: darken(@navbarBackground, 12%);
@navbarText: #777;
@navbarLinkColor: #777;
@navbarLinkColorHover: @grayDark;
@navbarLinkColorActive: @gray;
@navbarLinkBackgroundHover: transparent;
@navbarLinkBackgroundActive: darken(@navbarBackground, 5%);
Once you have done this, go to your bootstrap directory and run the command make.
the above code for chrome is working fine. i have tried like this in mozila but its not working. i found the solution for that
For mozila
input[type=number] {
-moz-appearance: textfield;
appearance: textfield;
margin: 0;
}
Thanks Sanjib
What do you mean exactly? Do you want to reuse the result of your query for an other query?
In that case, why don't you combine both queries, by making the second query search inside the results of the first one (SELECT xxx in (SELECT yyy...)
$("#Id").change(function(){
var selected = $('#Id option:selected').val();
alert(selected);
});
I think this is what you need.
powershell Set-Date -Da (Get-Date -Y 1980 -Mon 11 -Day 17)
Although it's not possible in general to do what's been asked, it's still often useful to have a count of how many items were iterated over after having iterated over them. For that, you can use jaraco.itertools.Counter or similar. Here's an example using Python 3 and rwt to load the package.
$ rwt -q jaraco.itertools -- -q
>>> import jaraco.itertools
>>> items = jaraco.itertools.Counter(range(100))
>>> _ = list(counted)
>>> items.count
100
>>> import random
>>> def gen(n):
... for i in range(n):
... if random.randint(0, 1) == 0:
... yield i
...
>>> items = jaraco.itertools.Counter(gen(100))
>>> _ = list(counted)
>>> items.count
48
If you want to pass data between two actions during a redirect without include any data in the query string, put the model in the TempData object.
ACTION
TempData["datacontainer"] = modelData;
VIEW
var modelData= TempData["datacontainer"] as ModelDataType;
TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only! Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this.
Therefore, the only scenario where using TempData will reliably work is when you are redirecting.
You cannot use VBA (Interior.ColorIndex
) in a formula which is why you receive the error.
It is not possible to do this without VBA.
Function YellowIt(rng As Range) As Boolean
If rng.Interior.ColorIndex = 6 Then
YellowIt = True
Else
YellowIt = False
End If
End Function
However, I do not recommend this: it is not how user-defined VBA functions (UDFs) are intended to be used. They should reflect the behaviour of Excel functions, which cannot read the colour-formatting of a cell. (This function may not work in a future version of Excel.)
It is far better that you base a formula on the original condition (decision) that makes the cell yellow in the first place. Or, alternatively, run a Sub procedure to fill in the True or False values (although, of course, these values will no longer be linked to the original cell's formatting).
Here is what I found for Google Sheets:
To get the current sheet name in Google sheets, the following simple script can help you without entering the name manually, please do as this:
Click Tools > Script editor
In the opened project window, copy and paste the below script code into the blank Code window, see screenshot:
......................
function sheetName() {
return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
}
Then save the code window, and go back to the sheet that you want to get its name, then enter this formula: =sheetName()
in a cell, and press Enter key, the sheet name will be displayed at once.
See this link with added screenshots: https://www.extendoffice.com/documents/excel/5222-google-sheets-get-list-of-sheets.html
Well, to be able to even get some information about why this happens, I did this:
You can update/install the node by reinstalling the installed package to the current version which may save us from lotta of errors, while doing the update.
This is done by nvm with the below command. Here, I have updated my node version to 8 and reinstalled all the available packages to v8 too!
nvm i v8 --reinstall-packages-from=default
It works on AWS Linux instance as well.
Just try this in razor
@{
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Google", Value = "Google"},
new SelectListItem {Text = "Other", Value = "Other"},
}, "Value", "Text");
}
and then
@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })
or
@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })
Convert an ArrayList to an object array
ArrayList has a constructor that takes a Collection, so the common idiom is:
List<T> list = new ArrayList<T>(Arrays.asList(array));
Which constructs a copy of the list created by the array.
now, Arrays.asList(array)
will wrap the array, so changes to the list
will affect the array, and visa versa. Although you can't add or remove
Find the Run button present on the top of the Eclipse, then select Run Configuration -> Arguments, in VM arguments section just mention the heap size you want to extend as below:
-Xmx1024m
Reflection e.g.:
public class PrivateObject {
private String privateString = null;
public PrivateObject(String privateString) {
this.privateString = privateString;
}
}
PrivateObject privateObject = new PrivateObject("The Private Value");
Field privateStringField = PrivateObject.class.
getDeclaredField("privateString");
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);
Use java -cp myjar.jar com.mypackage.myClass
.
If the class is not in a package then simply java -cp myjar.jar myClass
.
If you are not within the directory where myJar.jar
is located, then you can do:
On Unix or Linux platforms:
java -cp /location_of_jar/myjar.jar com.mypackage.myClass
On Windows:
java -cp c:\location_of_jar\myjar.jar com.mypackage.myClass
Its better to access the count with the laravels count method
$count = Model::where('status','=','1')->count();
or
$count = Model::count();
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
On production I prefer to redirect the requests to .php files under the directories where PHP processing should be disabled to a home page or to 404 page. This won't reveal any source code (why search engines should index uploaded malicious code?) and will look more friendly for visitors and even for evil hackers trying to exploit the stuff. Also it can be implemented in mostly in any context - vhost or .htaccess. Something like this:
<DirectoryMatch "^${docroot}/(image|cache|upload)/">
<FilesMatch "\.php$">
# use one of the redirections
#RedirectMatch temp "(.*)" "http://${servername}/404/"
RedirectMatch temp "(.*)" "http://${servername}"
</FilesMatch>
</DirectoryMatch>
Adjust the directives as you need.
Another problem can be that the python version you are using is not yet supported by opencv-python.
E.g. as of right now there is no opencv-python for python 3.8. You would need to downgrade your python to 3.7.5 for now.
Actually I wanted same alike thing, To get one year backward date, for a given date! :-)
With the hint of above answer from @mohammad mohsenipur I got to the following link, via his given link!
Luckily, there is a method same as date_add method, named date_sub method! :-) I do the following to get done what I wanted!
$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');
Hopes this answer will help somebody too! :-)
Good luck guys!
You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.
You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig
. It will give out some information and your local IP should look like 192.168.1.x.
go plain for SWIFT 3 and APACHE simple Auth:
func urlSession(_ session: URLSession, task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let credential = URLCredential(user: "test",
password: "test",
persistence: .none)
completionHandler(.useCredential, credential)
}
You could look into this: http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx It's not completely free, but it looks very nice.
Alex
-- My default settings (this is basically a single-session machine, so work_mem is pretty high)
SET effective_cache_size='2048MB';
SET work_mem='16MB';
\echo original
EXPLAIN ANALYZE
SELECT
COUNT (distinct val) as aantal
FROM one
;
\echo group by+count(*)
EXPLAIN ANALYZE
SELECT
distinct val
-- , COUNT(*)
FROM one
GROUP BY val;
\echo with CTE
EXPLAIN ANALYZE
WITH agg AS (
SELECT distinct val
FROM one
GROUP BY val
)
SELECT COUNT (*) as aantal
FROM agg
;
Results:
original QUERY PLAN
----------------------------------------------------------------------------------------------------------------------
Aggregate (cost=36448.06..36448.07 rows=1 width=4) (actual time=1766.472..1766.472 rows=1 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=31.371..185.914 rows=1499845 loops=1)
Total runtime: 1766.642 ms
(3 rows)
group by+count(*)
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------
HashAggregate (cost=36464.31..36477.31 rows=1300 width=4) (actual time=412.470..412.598 rows=1300 loops=1)
-> HashAggregate (cost=36448.06..36461.06 rows=1300 width=4) (actual time=412.066..412.203 rows=1300 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=26.134..166.846 rows=1499845 loops=1)
Total runtime: 412.686 ms
(4 rows)
with CTE
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=36506.56..36506.57 rows=1 width=0) (actual time=408.239..408.239 rows=1 loops=1)
CTE agg
-> HashAggregate (cost=36464.31..36477.31 rows=1300 width=4) (actual time=407.704..407.847 rows=1300 loops=1)
-> HashAggregate (cost=36448.06..36461.06 rows=1300 width=4) (actual time=407.320..407.467 rows=1300 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=24.321..165.256 rows=1499845 loops=1)
-> CTE Scan on agg (cost=0.00..26.00 rows=1300 width=0) (actual time=407.707..408.154 rows=1300 loops=1)
Total runtime: 408.300 ms
(7 rows)
The same plan as for the CTE could probably also be produced by other methods (window functions)
The simple way to use XMLHttpRequest
with pure JavaScript
. You can set custom header
but it's optional used based on requirement.
window.onload = function(){
var request = new XMLHttpRequest();
var params = "UID=CORS&name=CORS";
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
request.open('POST', 'https://www.example.com/api/createUser', true);
request.setRequestHeader('api-key', 'your-api-key');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
}
You can send params using POST method.
Please run below example and will get an JSON response.
window.onload = function(){_x000D_
var request = new XMLHttpRequest();_x000D_
_x000D_
request.onreadystatechange = function() {_x000D_
if (this.readyState == 4 && this.status == 200) {_x000D_
console.log(this.responseText);_x000D_
}_x000D_
};_x000D_
_x000D_
request.open('GET', 'https://jsonplaceholder.typicode.com/users/1');_x000D_
request.send();_x000D_
}
_x000D_
Kalle posted a link to a page that has this video on it, but it's done on XP. If you use Windows 7:
alt + n
alt + e
;
(that's a semicolon)C:\Python27
windows key + r
to bring up the run dialog. Type in python
and press enter.height:59.55%;//First specify your height then make overflow auto overflow:auto;
From your code, it looks like provider
is a variant or some other variable, and not an object.
Is Nothing
is for objects only, yet later you say it's a value that should either be NULL or NOT NULL, which would be handled by IsNull
.
Try using:
If Not IsNull(provider) Then
url = url & "&provider=" & provider
End if
Alternately, if that doesn't work, try:
If provider <> "" Then
url = url & "&provider=" & provider
End if
There's probably a another way or better. But this is how I do this in Spring Boot.
My property file contains the following lines. "," is the delimiter in each line.
mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;
My server config
@Configuration
public class ServerConfig {
@Inject
private Environment env;
@Bean
public MMLProperties mmlProperties() {
MMLProperties properties = new MMLProperties();
properties.setMmmlPots(env.getProperty("mml.pots"));
properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
return properties;
}
}
MMLProperties class.
public class MMLProperties {
private String mmlPots;
private String mmlIsdnGrunntengingar;
private String mmlIsdnStofntengingar;
public MMLProperties() {
super();
}
public void setMmmlPots(String mmlPots) {
this.mmlPots = mmlPots;
}
public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
}
public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
}
// These three public getXXX functions then take care of spliting the properties into List
public List<String> getMmmlCommandForPotsAsList() {
return getPropertieAsList(mmlPots);
}
public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
return getPropertieAsList(mmlIsdnGrunntengingar);
}
public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
return getPropertieAsList(mmlIsdnStofntengingar);
}
private List<String> getPropertieAsList(String propertie) {
return ((propertie != null) || (propertie.length() > 0))
? Arrays.asList(propertie.split("\\s*,\\s*"))
: Collections.emptyList();
}
}
Then in my Runner class I Autowire MMLProperties
@Component
public class Runner implements CommandLineRunner {
@Autowired
MMLProperties mmlProperties;
@Override
public void run(String... arg0) throws Exception {
// Now I can call my getXXX function to retrieve the properties as List
for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
System.out.println(command);
}
}
}
Hope this helps
A modern stdlib way is using sysconfig
module, available in version 2.7 and 3.2+. Unlike the current accepted answer, this method still works regardless of whether or not you have a virtual environment active.
Note: sysconfig
(source) is not to be confused with the distutils.sysconfig
submodule (source) mentioned in several other answers here. The latter is an entirely different module and it's lacking the get_paths
function discussed below.
Python currently uses eight paths (docs):
- stdlib: directory containing the standard Python library files that are not platform-specific.
- platstdlib: directory containing the standard Python library files that are platform-specific.
- platlib: directory for site-specific, platform-specific files.
- purelib: directory for site-specific, non-platform-specific files.
- include: directory for non-platform-specific header files.
- platinclude: directory for platform-specific header files.
- scripts: directory for script files.
- data: directory for data files.
In most cases, users finding this question would be interested in the 'purelib' path (in some cases, you might be interested in 'platlib' too). The purelib path is where ordinary Python packages will be installed by tools like pip
.
At system level, you'll see something like this:
# Linux
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/lib/python3.8/site-packages
# macOS (brew installed python3.8)
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/Cellar/[email protected]/3.8.3/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages
# Windows
C:\> py -c "import sysconfig; print(sysconfig.get_path('purelib'))"
C:\Users\wim\AppData\Local\Programs\Python\Python38\Lib\site-packages
With a venv, you'll get something like this
# Linux
/tmp/.venv/lib/python3.8/site-packages
# macOS
/private/tmp/.venv/lib/python3.8/site-packages
# Windows
C:\Users\wim\AppData\Local\Temp\.venv\Lib\site-packages
The function sysconfig.get_paths()
returns a dict of all of the relevant installation paths, example on Linux:
>>> import sysconfig
>>> sysconfig.get_paths()
{'stdlib': '/usr/local/lib/python3.8',
'platstdlib': '/usr/local/lib/python3.8',
'purelib': '/usr/local/lib/python3.8/site-packages',
'platlib': '/usr/local/lib/python3.8/site-packages',
'include': '/usr/local/include/python3.8',
'platinclude': '/usr/local/include/python3.8',
'scripts': '/usr/local/bin',
'data': '/usr/local'}
A shell script is also available to display these details, which you can invoke by executing sysconfig
as a module:
python -m sysconfig
Thanks RBarry. I'm putting together an IP block allocation system and storing as binary is the only way to go.
I'm storing the CIDR representation (ex: 192.168.1.0/24) of the IP block in a varchar field, and using 2 calculated fields to hold the binary form of the start and end of the block. From there, I can run fast queries to see if a given block as already been allocated or is free to assign.
I modified your function to calculate the ending IP Address like so:
CREATE FUNCTION dbo.fnDisplayIPv4End(@block AS VARCHAR(18)) RETURNS BINARY(4)
AS
BEGIN
DECLARE @bin AS BINARY(4)
DECLARE @ip AS VARCHAR(15)
DECLARE @size AS INT
SELECT @ip = Left(@block, Len(@block)-3)
SELECT @size = Right(@block, 2)
SELECT @bin = CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
+ CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
+ CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
+ CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))
SELECT @bin = CAST(@bin + POWER(2, 32-@size) AS BINARY(4))
RETURN @bin
END;
go
It may optionally have uses within the context of an application but far more often it is used for debugging purposes. For example, when you hit a breakpoint in an IDE, it's far easier to read a meaningful toString()
of objects than it is to inspect their members.
There is no set requirement for what a toString()
method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString()
methods are auto-generated in IDEs.
Relying on particular output from a toString()
method or parsing it within a program is a bad idea. Whatever you do, don't go down that route.
Callee vs caller saved is a convention for who is responsible for saving and restoring the value in a register across a call. ALL registers are "global" in that any code anywhere can see (or modify) a register and those modifications will be seen by any later code anywhere. The point of register saving conventions is that code is not supposed to modify certain registers, as other code assumes that the value is not modified.
In your example code, NONE of the registers are callee save, as it makes no attempt to save or restore the register values. However, it would seem to not be an entire procedure, as it contains a branch to an undefined label (l$loop
). So it might be a fragment of code from the middle of a procedure that treats some registers as callee save; you're just missing the save/restore instructions.
You would probably would have to set the child div to have position: absolute
.
Update your child style to
#parentDiv .childDiv
{
height:100px;
width:30px;
background-color:#999;
position:absolute;
top:207px;
}
My comments on Renaud Bompuis's answer messed up.
Actually, you can use late binding, and the reference to the 11.0 object library is not required.
The following code will work without any references:
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = True
f.Show
MsgBox "file choosen = " & f.SelectedItems.Count
Note that the above works well in the runtime also.
You could try adding an<hr>
and styling that. Its a minimal markup change but seems to need less css so that might do the trick.
fiddle:
In the $routeProvider URI patters, you can specify variable parameters, like so: $routeProvider.when('/page/:pageNumber' ...
, and access it in your controller via $routeParams.
There is a good example at the end of the $route page: http://docs.angularjs.org/api/ng.$route
EDIT (for the edited question):
The routing system is unfortunately very limited - there is a lot of discussion on this topic, and some solutions have been proposed, namely via creating multiple named views, etc.. But right now, the ngView directive serves only ONE view per route, on a one-to-one basis. You can go about this in multiple ways - the simpler one would be to use the view's template as a loader, with a <ng-include src="myTemplateUrl"></ng-include>
tag in it ($scope.myTemplateUrl would be created in the controller).
I use a more complex (but cleaner, for larger and more complicated problems) solution, basically skipping the $route service altogether, that is detailed here:
You can use a character class:
/[^\s\\]/
matches anything that is not a whitespace character nor a \
. Here's another example:
[abc]
means "match a
, b
or c
"; [^abc]
means "match any character except a
, b
or c
".
Try This.
Controller:
List<CountryModel> countryList = db.countryTable.ToList();
ViewBag.Country = new SelectList(countryList, "Country", "CountryName");
Yep, you can use border: 1px solid transparent
Another solution is to use outline
on hover (and set the border to 0) which doesn't affect the document flow:
li{
display:inline-block;
padding:5px;
border:0;
}
li:hover{
outline:1px solid #FC0;
}
NB. You can only set the outline as a sharthand property, not for individual sides. It's only meant to be used for debugging but it works nicely.
Allowed only characters & spaces. Ex : Jayant Lonari
if (!/^[a-zA-Z\s]+$/.test(NAME)) {
//Throw Error
}
You have two ways to do this:
In this type it automatically runs the reverse code of it, when rollback.
def change
rename_column :table_name, :old_column_name, :new_column_name
end
To this type, it runs the up method when rake db:migrate
and runs the down method when rake db:rollback
:
def self.up
rename_column :table_name, :old_column_name, :new_column_name
end
def self.down
rename_column :table_name,:new_column_name,:old_column_name
end
Maybe you are looking for Vector
. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList
instead.
Use subquery
SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]
I'm using nodejs client for access to private data
The solution was add the promp property with value consent to the settings object in oAuth2Client.generateAuthUrl function. Here is my code:
const getNewToken = (oAuth2Client, callback) => {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: SCOPES,
})
console.log('Authorize this app by visiting this url:', authUrl)
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
rl.question('Enter the code from that page here: ', (code) => {
rl.close()
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error while trying to retrieve access token', err)
oAuth2Client.setCredentials(token)
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err)
console.log('Token stored to', TOKEN_PATH)
})
callback(oAuth2Client)
})
})
}
You can use the online parameters extractor to get the code for generate your token:
Here is the complete code from google official docs:
https://developers.google.com/sheets/api/quickstart/nodejs
I hope the information is useful
Pure CSS:
.app-tooltip {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.app-tooltip:before {_x000D_
content: attr(data-title);_x000D_
background-color: rgba(97, 97, 97, 0.9);_x000D_
color: #fff;_x000D_
font-size: 12px;_x000D_
padding: 10px;_x000D_
position: absolute;_x000D_
bottom: -50px;_x000D_
opacity: 0;_x000D_
transition: all 0.4s ease;_x000D_
font-weight: 500;_x000D_
z-index: 2;_x000D_
}_x000D_
_x000D_
.app-tooltip:after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
left: 5px;_x000D_
bottom: -16px;_x000D_
border-style: solid;_x000D_
border-width: 0 10px 10px 10px;_x000D_
border-color: transparent transparent rgba(97, 97, 97, 0.9) transparent;_x000D_
transition: all 0.4s ease;_x000D_
}_x000D_
_x000D_
.app-tooltip:hover:after,_x000D_
.app-tooltip:hover:before {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div href="#" class="app-tooltip" data-title="Your message here"> Test here</div>
_x000D_
A Trie data structure would work the best, better than DP. Here is the code.
class TrieNode:
def __init__(self):
self.child = [None]*26
self.endWord = False
class Trie:
def __init__(self):
self.root = self.getNewNode()
def getNewNode(self):
return TrieNode()
def insert(self,value):
root = self.root
for i,character in enumerate(value):
index = ord(character) - ord('a')
if not root.child[index]:
root.child[index] = self.getNewNode()
root = root.child[index]
root.endWord = True
def search(self,value):
root = self.root
for i,character in enumerate(value):
index = ord(character) - ord('a')
if not root.child[index]:
return False
root = root.child[index]
return root.endWord
def main():
# Input keys (use only 'a' through 'z' and lower case)
keys = ["the","anaswe"]
output = ["Not present in trie",
"Present in trie"]
# Trie object
t = Trie()
# Construct trie
for key in keys:
t.insert(key)
# Search for different keys
print("{} ---- {}".format("the",output[t.search("the")]))
print("{} ---- {}".format("these",output[t.search("these")]))
print("{} ---- {}".format("their",output[t.search("their")]))
print("{} ---- {}".format("thaw",output[t.search("thaw")]))
if __name__ == '__main__':
main()
Let me know in case of doubts.
When making OUTER JOINs (ANSI-89 or ANSI-92), filtration location matters because criteria specified in the ON
clause is applied before the JOIN is made. Criteria against an OUTER JOINed table provided in the WHERE
clause is applied after the JOIN is made. This can produce very different result sets. In comparison, it doesn't matter for INNER JOINs if the criteria is provided in the ON
or WHERE
clauses -- the result will be the same.
SELECT s.*,
cs.`value`
FROM SETTINGS s
LEFT JOIN CHARACTER_SETTINGS cs ON cs.setting_id = s.id
AND cs.character_id = 1
First I would recommend you to store your timestamp as a NSNumber
in your Firebase Database, instead of storing it as a String
.
Another thing worth mentioning here, is that if you want to manipulate dates with Swift, you'd better use Date
instead of NSDate
, except if you're interacting with some Obj-C code in your app.
You can of course use both, but the Documentation states:
Date bridges to the NSDate class. You can use these interchangeably in code that interacts with Objective-C APIs.
Now to answer your question, I think the problem here is because of the timezone.
For example if you print(Date())
, as for now, you would get:
2017-09-23 06:59:34 +0000
This is the Greenwich Mean Time (GMT).
So depending on where you are located (or where your users are located) you need to adjust the timezone before (or after, when you try to access the data for example) storing your Date
:
let now = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm"
let dateString = formatter.string(from: now)
Then you have your properly formatted String
, reflecting the current time at your location, and you're free to do whatever you want with it :) (convert it to a Date
/ NSNumber
, or store it directly as a String
in the database..)
To check if one or more columns all exist, you can use set.issubset
, as in:
if set(['A','C']).issubset(df.columns):
df['sum'] = df['A'] + df['C']
As @brianpck points out in a comment, set([])
can alternatively be constructed with curly braces,
if {'A', 'C'}.issubset(df.columns):
See this question for a discussion of the curly-braces syntax.
Or, you can use a list comprehension, as in:
if all([item in df.columns for item in ['A','C']]):
If you've tried to change target to a previous GooglePlayServices or AppCompatv7 version and it doesn't work, check if you have any project-libraries dependency, this project will be targeting the latest version of any of these libraries. It happened to me with the Google Maps Utils Library project:
replace:
compile 'com.google.android.gms:play-services:+'
to
compile 'com.google.android.gms:play-services:8.3.0'
Then you can continue full targeting API 22
If it still doesn't compile, sometimes is useful to set compileSdkVersion API to 23 and targetSdkVersion to 22.
If you initialize both the parameters as float
, you will sure get actual divided value.
For example:
float RoomWidth, TileWidth, NumTiles;
RoomWidth = 142;
TileWidth = 8;
NumTiles = RoomWidth/TileWidth;
Ans:17.75.
Based on something found on Code Project
Once the data table is declared based on the grid's data source, lookup the column index by column name from the columns collection. At this point, use the index as needed to obtain information from or to format the cell.
protected void gridMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (DataTable)((GridView)sender).DataSource;
int colIndex = dt.Columns["MyColumnName"].Ordinal;
e.Row.Cells[colIndex].BackColor = Color.FromName("#ffeb9c");
}
}
It depends on the use case. Can you, please, describe it more?
If you want to be able to add both at one time, than you can do the which is nicely described by @Sanket Parikh. Put Integer and String into a new class and use that.
If you want to add the list either a String or an int, but only one of these at a time, then sure it is the List<Object>
which looks good but only for first sight! This is not a good pattern. You'll have to check what type of object you have each time you get an object from your list. Also This type of list can contain any other types as well.. So no, not a nice solution. Although maybe for a beginner it can be used. If you choose this, i would recommend to check what is "instanceof" in Java.
I would strongly advise to reconsider your needs and think about maybe your real nead is to encapsulate Integers to a List<Integer>
and Strings to a separate List<String>
Can i tell you a metaphor for what you want to do now? I would say you want to make a List wich can contain coffee beans and coffee shops. These to type of objects are totally different! Why are these put onto the same shelf? :)
Or do you have maybe data which can be a word or a number? Yepp! This would make sense, both of them is data! Then try to use one object for that which contains the data as String and if needed, can be translated to integer value.
public class MyDataObj {
String info;
boolean isNumeric;
public MyDataObj(String info){
setInfo(info);
}
public MyDataObj(Integer info){
setInfo(info);
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
this.isNumeric = false;
}
public void setInfo(Integer info) {
this.info = Integer.toString(info);
this.isNumeric = true;
}
public boolean isNumeric() {
return isNumeric;
}
}
This way you can use List<MyDataObj>
for your needs. Again, this depends on your needs! :)
Some edition: What about using inharitance? This is better then then List<Object>
solution, because you can not have other types in the list then Strings or Integers:
Interface:
public interface IMyDataObj {
public String getInfo();
}
For String:
public class MyStringDataObj implements IMyDataObj {
final String info;
public MyStringDataObj(String info){
this.info = info;
}
@Override
public String getInfo() {
return info;
}
}
For Integer:
public class MyIntegerDataObj implements IMyDataObj {
final Integer info;
public MyIntegerDataObj(Integer info) {
this.info = info;
}
@Override
public String getInfo() {
return Integer.toString(info);
}
}
Finally the list will be: List<IMyDataObj>
Taking a column is easy with the map function.
// a two-dimensional array
var two_d = [[1,2,3],[4,5,6],[7,8,9]];
// take the third column
var col3 = two_d.map(function(value,index) { return value[2]; });
Why bother with the slice at all? Just filter the matrix to find the rows of interest.
var interesting = two_d.filter(function(value,index) {return value[1]==5;});
// interesting is now [[4,5,6]]
Sadly, filter and map are not natively available on IE9 and lower. The MDN documentation provides implementations for browsers without native support.
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
To work with version 2 of log4j aka "log4j2"
-Dlog4j.configuration=
should read
-Dlog4j.configurationFile=
log4j:WARN ....
In your project, uninclude the log4j-1.2 jar and instead, include the log4j-1.2-api-2.1.jar. I wasn't sure how exactly to exclude the log4j 1.2. I knew that what dependency of my project was requiring it. So, with some reading, I excluded a bunch of stuff.
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.10</artifactId>
<version>0.8.2.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.log4j</groupId>
<artifactId>log4j-core</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
I am not sure which of the exclusions did the trick. Separately, I included a dependency to the 1.2 api which bridges to 2.x.
<!--
http://logging.apache.org/log4j/2.0/manual/migration.html
http://logging.apache.org/log4j/2.0/maven-artifacts.html
Log4j 1.x API Bridge
If existing components use Log4j 1.x and you want to have this logging
routed to Log4j 2, then remove any log4j 1.x dependencies and add the
following.
-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-1.2-api</artifactId>
<version>2.2</version>
</dependency>
Now, the 1.2 logs which were only going to the console actually flow to our 2.x appenders.
Pasting RedFilter code in two parts ,so as to avoid link rot
References:
https://github.com/mb16/geocoderNet/blob/master/build/sql/doubleMetaphone.sql
Part1:
--WEB LISTING 1: Double Metaphone Script
-------------------------------------
IF OBJECT_ID('fnIsVowel') IS NOT NULL BEGIN DROP FUNCTION fnIsVowel END
GO;
CREATE FUNCTION fnIsVowel( @c char(1) )
RETURNS bit
AS
BEGIN
IF (@c = 'A') OR (@c = 'E') OR (@c = 'I') OR (@c = 'O') OR (@c = 'U') OR (@c = 'Y')
BEGIN
RETURN 1
END
--'ELSE' would worry SQL Server, it wants RETURN last in a scalar function
RETURN 0
END
GO;
-----------------------------------------------
IF OBJECT_ID('fnSlavoGermanic') IS NOT NULL BEGIN DROP FUNCTION fnSlavoGermanic
END
GO;
CREATE FUNCTION fnSlavoGermanic( @Word char(50) )
RETURNS bit
AS
BEGIN
--Catch NULL also...
IF (CHARINDEX('W',@Word) > 0) OR (CHARINDEX('K',@Word) > 0) OR
(CHARINDEX('CZ',@Word) > 0)
--'WITZ' test is in original Lawrence Philips C++ code, but appears to be a subset of the first test for 'W'
-- OR (CHARINDEX('WITZ',@Word) > 0)
BEGIN
RETURN 1
END
--ELSE
RETURN 0
END
GO;
---------------------------------------------------------------------------------------------------------------------------------
----------------------
--Lawrence Philips calls for a length argument, but this has two drawbacks:
--1. All target strings must be of the same length
--2. It presents an opportunity for subtle bugs, ie fnStringAt( 1, 7, 'Search me please', 'Search' ) returns 0 (no matter what is in the searched string)
--So I've eliminated the argument and fnStringAt checks the length of each target as it executes
--DEFAULTS suck with UDFs. Have to specify DEFAULT in caller - why bother?
IF OBJECT_ID('fnStringAtDef') IS NOT NULL BEGIN DROP FUNCTION fnStringAtDef END
GO;
CREATE FUNCTION fnStringAtDef( @Start int, @StringToSearch varchar(50),
@Target1 varchar(50),
@Target2 varchar(50) = NULL,
@Target3 varchar(50) = NULL,
@Target4 varchar(50) = NULL,
@Target5 varchar(50) = NULL,
@Target6 varchar(50) = NULL )
RETURNS bit
AS
BEGIN
IF CHARINDEX(@Target1,@StringToSearch,@Start) > 0 RETURN 1
--2 Styles, test each optional argument for NULL, nesting further tests
--or just take advantage of CHARINDEX behavior with a NULL arg (unless 65 compatibility - code check before CREATE FUNCTION?
--Style 1:
--IF @Target2 IS NOT NULL
--BEGIN
-- IF CHARINDEX(@Target2,@StringToSearch,@Start) > 0 RETURN 1
-- (etc.)
--END
--Style 2:
IF CHARINDEX(@Target2,@StringToSearch,@Start) > 0 RETURN 1
IF CHARINDEX(@Target3,@StringToSearch,@Start) > 0 RETURN 1
IF CHARINDEX(@Target4,@StringToSearch,@Start) > 0 RETURN 1
IF CHARINDEX(@Target5,@StringToSearch,@Start) > 0 RETURN 1
IF CHARINDEX(@Target6,@StringToSearch,@Start) > 0 RETURN 1
RETURN 0
END
GO;
-------------------------------------------------------------------------------------------------
IF OBJECT_ID('fnStringAt') IS NOT NULL BEGIN DROP FUNCTION fnStringAt END
GO;
CREATE FUNCTION fnStringAt( @Start int, @StringToSearch varchar(50), @TargetStrings
varchar(2000) )
RETURNS bit
AS
BEGIN
DECLARE @SingleTarget varchar(50)
DECLARE @CurrentStart int
DECLARE @CurrentLength int
--Eliminate special cases
--Trailing space is needed to check for end of word in some cases, so always append comma
--loop tests should fairly quickly ignore ',,' termination
SET @TargetStrings = @TargetStrings + ','
SET @CurrentStart = 1
--Include terminating comma so spaces don't get truncated
SET @CurrentLength = (CHARINDEX(',',@TargetStrings,@CurrentStart) -
@CurrentStart) + 1
SET @SingleTarget = SUBSTRING(@TargetStrings,@CurrentStart,@CurrentLength)
WHILE LEN(@SingleTarget) > 1
BEGIN
IF SUBSTRING(@StringToSearch,@Start,LEN(@SingleTarget)-1) =
LEFT(@SingleTarget,LEN(@SingleTarget)-1)
BEGIN
RETURN 1
END
SET @CurrentStart = (@CurrentStart + @CurrentLength)
SET @CurrentLength = (CHARINDEX(',',@TargetStrings,@CurrentStart) -
@CurrentStart) + 1
IF NOT @CurrentLength > 1 --getting trailing comma
BEGIN
BREAK
END
SET @SingleTarget =
SUBSTRING(@TargetStrings,@CurrentStart,@CurrentLength)
END
RETURN 0
END
GO;
------------------------------------------------------------------------
IF OBJECT_ID('fnDoubleMetaphoneTable') IS NOT NULL BEGIN DROP FUNCTION
fnDoubleMetaphoneTable END
GO;
CREATE FUNCTION fnDoubleMetaphoneTable( @Word varchar(50) )
RETURNS @DMP TABLE ( Metaphone1 char(4), Metaphone2 char(4) )
AS
BEGIN
DECLARE @MP1 varchar(4), @MP2 varchar(4)
SET @MP1 = ''
SET @MP2 = ''
DECLARE @CurrentPosition int, @WordLength int, @CurrentChar char(1)
SET @CurrentPosition = 1
SET @WordLength = LEN(@Word)
IF @WordLength < 1
BEGIN
RETURN
END
--ensure case insensitivity
SET @Word = UPPER(@Word)
IF dbo.fnStringAt(1, @Word, 'GN,KN,PN,WR,PS') = 1
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
IF 'X' = LEFT(@Word,1)
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'S'
SET @CurrentPosition = @CurrentPosition + 1
END
WHILE (4 > LEN(RTRIM(@MP1))) OR (4 > LEN(RTRIM(@MP2)))
BEGIN
IF @CurrentPosition > @WordLength
BEGIN
BREAK
END
SET @CurrentChar = SUBSTRING(@Word,@CurrentPosition,1)
IF @CurrentChar IN('A','E','I','O','U','Y')
BEGIN
IF @CurrentPosition = 1
BEGIN
SET @MP1 = @MP1 + 'A'
SET @MP2 = @MP2 + 'A'
END
SET @CurrentPosition = @CurrentPosition + 1
END
ELSE IF @CurrentChar = 'B'
BEGIN
SET @MP1 = @MP1 + 'P'
SET @MP2 = @MP2 + 'P'
IF 'B' = SUBSTRING(@Word,@CurrentPosition + 1,1)
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
ELSE IF @CurrentChar = 'Ç'
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'S'
SET @CurrentPosition = @CurrentPosition + 1
END
ELSE IF @CurrentChar = 'C'
BEGIN
--various germanic
IF (@CurrentPosition > 2)
AND (dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition-2,1))=0)
AND (dbo.fnStringAt(@CurrentPosition-1,@Word,'ACH') = 1)
AND ((SUBSTRING(@Word,@CurrentPosition+2,1) <> 'I')
AND ((SUBSTRING(@Word,@CurrentPosition+2,1) <> 'E') OR
(dbo.fnStringAt(@CurrentPosition-2,@Word,'BACHER,MACHER')=1)))
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
SET @CurrentPosition = @CurrentPosition + 2
END
-- 'caesar'
ELSE IF (@CurrentPosition = 1) AND
(dbo.fnStringAt(@CurrentPosition,@Word,'CAESAR') = 1)
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'S'
SET @CurrentPosition = @CurrentPosition + 2
END
-- 'chianti'
ELSE IF dbo.fnStringAt(@CurrentPosition,@Word,'CHIA') = 1
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE IF dbo.fnStringAt(@CurrentPosition,@Word,'CH') = 1
BEGIN
-- Find 'michael'
IF (@CurrentPosition > 1) AND
(dbo.fnStringAt(@CurrentPosition,@Word,'CHAE') = 1)
BEGIN
--First instance of alternate encoding
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'X'
SET @CurrentPosition = @CurrentPosition + 2
END
--greek roots e.g. 'chemistry', 'chorus'
ELSE IF (@CurrentPosition = 1) AND (dbo.fnStringAt(2, @Word,
'HARAC,HARIS,HOR,HYM,HIA,HEM') = 1) AND (dbo.fnStringAt(1,@Word,'CHORE') = 0)
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
SET @CurrentPosition = @CurrentPosition + 2
END
--germanic, greek, or otherwise 'ch' for 'kh' sound
ELSE IF ((dbo.fnStringAt(1,@Word,'VAN ,VON ,SCH')=1) OR
(dbo.fnStringAt(@CurrentPosition-
2,@Word,'ORCHES,ARCHIT,ORCHID')=1) OR
(dbo.fnStringAt(@CurrentPosition+2,@Word,'T,S')=1) OR
(((dbo.fnStringAt(@CurrentPosition-1,@Word,'A,O,U,E')=1)
OR
(@CurrentPosition = 1))
AND
(dbo.fnStringAt(@CurrentPosition+2,@Word,'L,R,N,M,B,H,F,V,W, ')=1)))
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
--is this a given?
IF (@CurrentPosition > 1)
BEGIN
IF (dbo.fnStringAt(1,@Word,'MC') = 1)
BEGIN
--eg McHugh
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
END
ELSE
BEGIN
--Alternate encoding
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'K'
END
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'X'
END
SET @CurrentPosition = @CurrentPosition + 2
END
END
--e.g, 'czerny'
ELSE IF (dbo.fnStringAt(@CurrentPosition,@Word,'CZ')=1) AND
(dbo.fnStringAt((@CurrentPosition - 2),@Word,'WICZ')=0)
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'X'
SET @CurrentPosition = @CurrentPosition + 2
END
--e.g., 'focaccia'
ELSE IF(dbo.fnStringAt((@CurrentPosition + 1),@Word,'CIA')=1)
BEGIN
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'X'
SET @CurrentPosition = @CurrentPosition + 3
END
--double 'C', but not if e.g. 'McClellan'
ELSE IF(dbo.fnStringAt(@CurrentPosition,@Word,'CC')=1) AND NOT
((@CurrentPosition = 2) AND (LEFT(@Word,1) = 'M'))
--'bellocchio' but not 'bacchus'
IF (dbo.fnStringAt((@CurrentPosition + 2),@Word,'I,E,H')=1) AND
(dbo.fnStringAt((@CurrentPosition + 2),@Word,'HU')=0)
BEGIN
--'accident', 'accede' 'succeed'
IF (((@CurrentPosition = 2) AND
(SUBSTRING(@Word,@CurrentPosition - 1,1) = 'A'))
OR (dbo.fnStringAt((@CurrentPosition -
1),@Word,'UCCEE,UCCES')=1))
BEGIN
SET @MP1 = @MP1 + 'KS'
SET @MP2 = @MP2 + 'KS'
END
--'bacci', 'bertucci', other italian
ELSE
BEGIN
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'X'
END
SET @CurrentPosition = @CurrentPosition + 3
END
--Pierce's rule
ELSE
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE IF (dbo.fnStringAt(@CurrentPosition,@Word,'CK,CG,CQ')=1)
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE IF (dbo.fnStringAt(@CurrentPosition,@Word,'CI,CE,CY')=1)
BEGIN
--italian vs. english
IF (dbo.fnStringAt(@CurrentPosition,@Word,'CIO,CIE,CIA')=1)
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'X'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'S'
END
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
--name sent in 'mac caffrey', 'mac gregor
IF (dbo.fnStringAt((@CurrentPosition + 1),@Word,' C, Q, G')=1)
BEGIN
SET @CurrentPosition = @CurrentPosition + 3
END
ELSE
BEGIN
IF (dbo.fnStringAt((@CurrentPosition + 1),@Word,'C,K,Q')=1)
AND (dbo.fnStringAt((@CurrentPosition + 1), 2, 'CE,CI')=0)
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
END
END
ELSE IF @CurrentChar = 'D'
BEGIN
IF (dbo.fnStringAt(@CurrentPosition, @Word, 'DG')=1)
BEGIN
IF (dbo.fnStringAt((@CurrentPosition + 2),@Word,'I,E,Y')=1)
BEGIN
--e.g. 'edge'
SET @MP1 = @MP1 + 'J'
SET @MP2 = @MP2 + 'J'
SET @CurrentPosition = @CurrentPosition + 3
END
ELSE
BEGIN
--e.g. 'edgar'
SET @MP1 = @MP1 + 'TK'
SET @MP2 = @MP2 + 'TK'
SET @CurrentPosition = @CurrentPosition + 2
END
END
ELSE IF (dbo.fnStringAt(@CurrentPosition,@Word,'DT,DD')=1)
BEGIN
SET @MP1 = @MP1 + 'T'
SET @MP2 = @MP2 + 'T'
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'T'
SET @MP2 = @MP2 + 'T'
SET @CurrentPosition = @CurrentPosition + 1
END
END
ELSE IF @CurrentChar = 'F'
BEGIN
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'F')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
SET @MP1 = @MP1 + 'F'
SET @MP2 = @MP2 + 'F'
END
ELSE IF @CurrentChar = 'G'
BEGIN
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'H')
BEGIN
IF (@CurrentPosition > 1) AND
(dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition - 1,1)) = 0)
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
SET @CurrentPosition = @CurrentPosition + 2
END
--'ghislane', ghiradelli
ELSE IF (@CurrentPosition = 1)
BEGIN
IF (SUBSTRING(@Word,@CurrentPosition + 2,1) = 'I')
BEGIN
SET @MP1 = @MP1 + 'J'
SET @MP2 = @MP2 + 'J'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
END
SET @CurrentPosition = @CurrentPosition + 2
END
--Parker's rule (with some further refinements) - e.g., 'hugh'
ELSE IF (((@CurrentPosition > 2) AND (dbo.fnStringAt((@CurrentPosition
- 2),@Word,'B,H,D')=1) )
--e.g., 'bough'
OR ((@CurrentPosition > 3) AND (dbo.fnStringAt((@CurrentPosition
- 3),@Word,'B,H,D')=1) )
--e.g., 'broughton'
OR ((@CurrentPosition > 4) AND (dbo.fnStringAt((@CurrentPosition
- 4),@Word,'B,H')=1) ) )
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
--e.g., 'laugh', 'McLaughlin', 'cough', 'gough', 'rough', 'tough'
IF ((@CurrentPosition > 3)
AND (SUBSTRING(@Word,@CurrentPosition - 1,1) = 'U')
AND (dbo.fnStringAt((@CurrentPosition -
3),@Word,'C,G,L,R,T')=1) )
BEGIN
SET @MP1 = @MP1 + 'F'
SET @MP2 = @MP2 + 'F'
END
ELSE
BEGIN
IF ((@CurrentPosition > 1) AND
SUBSTRING(@Word,@CurrentPosition - 1,1) <> 'I')
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
END
END
SET @CurrentPosition = @CurrentPosition + 2
END
END
ELSE IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'N')
BEGIN
IF ((@CurrentPosition = 2) AND (dbo.fnIsVowel(LEFT(@Word,1))=1) AND
(dbo.fnSlavoGermanic(@Word)=0))
BEGIN
SET @MP1 = @MP1 + 'KN'
SET @MP2 = @MP2 + 'N'
END
ELSE
BEGIN
--not e.g. 'cagney'
IF ((dbo.fnStringAt((@CurrentPosition + 2),@Word,'EY')=0)
AND (SUBSTRING(@Word,@CurrentPosition + 1,1) <>
'Y') AND (dbo.fnSlavoGermanic(@Word)=0))
After read a lot of subjetcs on StakOverflow and other forums, I found the working solution for me. This solution is for working without Express.
here are the prerequisites.
SERVER SIDE
// DEPENDENCIES
var fs = require('fs'),
winston = require('winston'),
path = require('path');
// LOGS
const logger = winston.createLogger({
level : 'info',
format : winston.format.json(),
transports: [
new winston.transports.Console({ level: 'debug' }),
new winston.transports.File({ filename: 'err.log', level: 'err' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// CONSTANTS
const Port = 9000,
certsPath = '/etc/letsencrypt/live/my.domain.com/';
// STARTING HTTPS SERVER
var server = require('https').createServer({
key: fs.readFileSync(certsPath + 'privkey.pem'),
cert: fs.readFileSync(certsPath + 'cert.pem'),
ca: fs.readFileSync(certsPath + 'chain.pem'),
requestCert: false,
rejectUnauthorized: false
},
(req, res) => {
var filePath = '.' + req.url;
logger.info('FILE ASKED : ' + filePath);
// Default page for visitor calling directly URL
if (filePath == './')
filePath = './index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.wav':
contentType = 'audio/wav';
break;
}
var headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000, // 30 days
'Content-Type': contentType
};
fs.readFile(filePath, function(err, content) {
if (err) {
if(err.code == 'ENOENT'){
fs.readFile('./errpages/404.html', function(err, content) {
res.writeHead(404, headers);
res.end(content, 'utf-8');
});
}
else {
fs.readFile('./errpages/500.html', function(err, content) {
res.writeHead(500, headers);
res.end(content, 'utf-8');
});
}
}
else {
res.writeHead(200, headers);
res.end(content, 'utf-8');
}
});
if (req.method === 'OPTIONS') {
res.writeHead(204, headers);
res.end();
}
}).listen(port);
//OPENING SOCKET
var io = require('socket.io')(server).on('connection', function(s) {
logger.info("SERVER > Socket opened from client");
//... your code here
});
CLIENT SIDE
<script src="https://my.domain.com:port/js/socket.io.js"></script>
<script>
$(document).ready(function() {
$.socket = io.connect('https://my.domain.com:port', {
secure: true // for SSL
});
//... your code here
});
</script>
code {_x000D_
background: black;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
Tested and works in Safari 5 and IE6+.
I ended up figuring this out on my own.
In searching for my logs I went into
cd /usr/local/mysql/var
In there I found the file named [MyNAS].pid (replace [MyNAS] with the name of your NAS.
I then ran the following to remove the file
rm -rf /usr/local/mysql/var/[MyNAS].pid
I then restarted mysql
[/usr/local/mysql/var] # /etc/init.d/mysqld.sh restart
/mnt/ext/opt/mysql
/mnt/ext/opt/mysql
Try to shutting down MySQL
ERROR! MySQL manager or server PID file could not be found!
/mnt/ext/opt/mysql
Starting MySQL. SUCCESS!
I tested everything and it all works like a charm again!
You could easily use display:table to vertical-align content and text-align:center to horizontal align your iframe. http://jsfiddle.net/EnmD6/7/
html {
display:table;
height:100%;
width:100%;
}
body {
display:table-cell;
vertical-align:middle;
}
#top-element {
position:absolute;
top:0;
left:0;
background:orange;
width:100%;
}
#iframe-wrapper {
text-align:center;
}
version with table-row http://jsfiddle.net/EnmD6/9/
html {
height:100%;
width:100%;
}
body {
display:table;
height:100%;
width:100%;
margin:0;
}
#top-element {
display:table-row;
background:orange;
width:100%;
}
#iframe-wrapper {
display:table-cell;
height:100%;
vertical-align:middle;
text-align:center;
}
Use -n
or --line-number
.
Check out man grep
for lots more options.
I was in need of a similar kind of solution, wanted to add data on a wall like facebook, when posted,use prepend()
to add the latest post on top, thought might be useful for others..
$("#statusupdate").submit( function () {
$.post(
'ajax.php',
$(this).serialize(),
function(data){
$("#box").prepend($(data).fadeIn('slow'));
$("#status").val('');
}
);
event.preventDefault();
});
the code in ajax.php is
if (isset($_POST))
{
$feed = $_POST['feed'];
echo "<p id=\"result\" style=\"width:200px;height:50px;background-color:lightgray;display:none;\">$feed</p>";
}
Your interior <div>
elements should likely both be float:left
. Divs size to 100% the size of their container width automatically. Try using display:inline-block
instead of width:auto
on the container div. Or possibly float:left
the container and also apply overflow:auto
. Depends on what you're after exactly.
The reason is old rubygems. You need to update system part using non ssl source first:
gem update --system --source http://rubygems.org/
(temporarily updating system part using non-ssl connection).
Now you're ready to use gem update
.
I was able to fix this!
Had the same problems as stated above, made sure nothing was using port 80 and still not working and getting the message that Apache and Mysql were detected with the wrong path.
I did install XAMPP once before, uninstalled and reinstalled. I even manually uninstalled but still had issues.
The fix. Make sure you backup your system first!
Start Services via Control Panel>Admin Tools (also with Ctrl+R and services.msc
)
Look for Apache and MySQL services. Look at the patch indicated in the description (right click on service then click on properties). Chances are that you have Apache listed twice, one from your correct install and one from a previous install. Even if you only see one, look at the path, chances are it's from a previous install and causing your install not to work. In either case, you need to delete those incorrect services.
a. Got to command prompt (run as administrator): Start > all programs > Accessories > right click on Command Prompt > Select 'run as administrator'
b. on command prompt type sc delete service
, where service is the service you're wanting to delete, such as apache2.1 (or sc delete Apache2.4
). It should be exactly as it appears in your services. If the service has spaces such as Apache 2.1 then enter it in quotes, i.e. sc delete "Apache 2.1"
c. press enter. Now refresh or close/open your services window and you'll see it`s gone.
DO THIS for all services that XAMPP finds as running with an incorrect path.
Once you do this, go ahead and restart the XAMPP control panel (as administrator) and voila! all works. No conflicts
Unfortunately you cannot.
I tried using the CSS max
function in padding
to attempt this functionality, but I got a parse error in my css. Below is what I tried:
padding: 5px max(50vw - 350px, 10vw);
I then tried to separate the operations into variables, and that didn't work either
--padding: calc(50vw - 350px);
--max-padding: max(1vw, var(--padding));
padding: 5px var(--max-padding);
What eventually worked was just nesting what I wanted padded in a div with class "centered" and using max width and width like so
.centered {
width: 98vw;
max-width: 700px;
height: 100%;
margin: 0 auto;
}
Unfortunately, this appears to be the best way to mimic a "max-padding" and "min-padding". I imagine the technique would be similar for "min-margin" and "max-margin". Hopefully this gets added at some point!
The following is acceptable as well:
@GetMapping(path = { "/{pathVariable1}/{pathVariable1}/somePath",
"/fixedPath/{some-name}/{some-id}/fixed" },
produces = "application/json")
Same can be applied to @RequestMapping
as well
Why are you writing the code for calculating the distance by yourself?
Check the api's in Location class
The preceding answers don't insist enough on the main problem: even in very simple queries like
(SELECT t2.* FROM t1, t2 WHERE t2.id = t1.id ORDER BY t1.id)
a temporary table can be required, and if a VARCHAR
field is involved, it is converted to a CHAR
field in the temporary table. So if you have in your table say 500 000 lines with a VARCHAR(65000)
field, this column alone will use 6.5*5*10^9 byte. Such temp tables can't be handled in memory and are written to disk. The impact can be expected to be catastrophic.
Source (with metrics): https://nicj.net/mysql-text-vs-varchar-performance/
(This refers to the handling of TEXT
vs VARCHAR
in "standard"(?) MyISAM storage engine. It may be different in others, e.g., InnoDB.)
I'd advise against mix-ins in new Python code, if you can find any other way around it (such as composition-instead-of-inheritance, or just monkey-patching methods into your own classes) that isn't much more effort.
In old-style classes you could use mix-ins as a way of grabbing a few methods from another class. But in the new-style world everything, even the mix-in, inherits from object
. That means that any use of multiple inheritance naturally introduces MRO issues.
There are ways to make multiple-inheritance MRO work in Python, most notably the super() function, but it means you have to do your whole class hierarchy using super(), and it's considerably more difficult to understand the flow of control.
I was pretty sure that you need to specify the NOLOCK
for each JOIN
in the query. But my experience was limited to SQL Server 2005.
When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:
[SQL Server 2008 R2]
All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
[SQL Server 2005]
In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
Additionally, point to note - and this applies to both 2005 and 2008:
The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the
OPTION (EXPAND VIEWS)
query hint.
Replace disabled
with readonly="readonly"
. I think it is the same function.
<input type="text" class="details-dialog" readonly="readonly" style="color: ur color;">
Use the Node.js console.time()
and console.timeEnd()
:
var i;
console.time("dbsave");
for(i = 1; i < LIMIT; i++){
db.users.save({id : i, name : "MongoUser [" + i + "]"}, end);
}
end = function(err, saved) {
console.log(( err || !saved )?"Error":"Saved");
if(--i === 1){console.timeEnd("dbsave");}
};
This is a simple way of doing something.
@Override
public void onBackPressed() {
// do what you want to do when the "back" button is pressed.
startActivity(new Intent(Activity.this, MainActivity.class));
finish();
}
I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.
Try this. Works fine in ICS. If You want to stop service simply click the notification generated in statusbar.
public class HUD extends Service
{
protected boolean foreground = false;
protected boolean cancelNotification = false;
private Notification notification;
private View myView;
protected int id = 0;
private WindowManager wm;
private WindowManager.LayoutParams params;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
// System.exit(0);
Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_SHORT).show();
params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
params.gravity=Gravity.TOP|Gravity.LEFT;
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
inflateview();
foregroundNotification(1);
//moveToForeground(1,n,true);
}
@Override
public void onDestroy() {
super.onDestroy();
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(0);
Toast.makeText(getBaseContext(),"onDestroy", Toast.LENGTH_SHORT).show();
if(myView != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(myView);
myView = null;
}
}
protected Notification foregroundNotification(int notificationId)
{
notification = new Notification(R.drawable.ic_launcher, "my Notification", System.currentTimeMillis());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE;
notification.setLatestEventInfo(this, "my Notification", "my Notification", notificationIntent());
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(id, notification);
return notification;
}
private PendingIntent notificationIntent() {
Intent intent = new Intent(this, stopservice.class);
PendingIntent pending = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pending;
}
public void inflateview()
{
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.activity_button, null);
myView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(getBaseContext(),"onToasttt", Toast.LENGTH_SHORT).show();
return false;
}
});
// Add layout to window manager
wm.addView(myView, params);
}
}
UPDATE
Sample here
To create an overlay view, when setting up the LayoutParams DON'T set the type to TYPE_SYSTEM_OVERLAY.
Instead set it to TYPE_PHONE.
Use the following flags:
FLAG_NOT_TOUCH_MODAL
FLAG_WATCH_OUTSIDE_TOUCH
Pass the object:
doSomething(this)
You can get all data from object:
function(obj){
var value = obj.value;
var id = obj.id;
}
Or pass the id
only:
doSomething(this.id)
Get the object and after that value:
function(id){
var value = document.getElementById(id).value;
}
"objectForKey will return nil if it doesn't exist." It will also return nil if it does exist and it is either an integer or a boolean with a value of zero (i.e. FALSE or NO for the boolean).
I've tested this in the simulator for both 5.1 and 6.1. This means that you cannot really test for either integers or booleans having been set by asking for "the object". You can get away with this for integers if you don't mind treating "not set" as if it were "set to zero".
The people who already tested this appear to have been fooled by the false negative aspect, i.e. testing this by seeing if objectForKey returns nil when you know the key hasn't been set but failing to notice that it also returns nil if the key has been set but has been set to NO.
For my own problem, that sent me here, I just ended up changing the semantics of my boolean so that my desired default was in congruence with the value being set to NO. If that's not an option, you'll need to store as something other than a boolean and make sure that you can tell the difference between YES, NO, and "not set."
For Jersey 2.* (Tested on 2.7) and java 8:
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public static Client ignoreSSLClient() throws Exception {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}}, new java.security.SecureRandom());
return ClientBuilder.newBuilder()
.sslContext(sslcontext)
.hostnameVerifier((s1, s2) -> true)
.build();
}
The solution was as simple as adding plt.show()
at the end of the code snippet:
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
You can have code in the class definition in both Ruby and Python. However, in Ruby you have a reference to the class (self). In Python you don't have a reference to the class, as the class isn't defined yet.
An example:
class Kaka
puts self
end
self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python.
it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.
the thing you have to do is to change your insertion query as below
INSERT INTO `abuses` ( `user_id` , `abuser_username` , `comment` , `reg_date` , `auction_id` )
VALUES ( 100020, 'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;
If I understand this correctly, you're trying to make backspace delete both the visible * character on screen and the cached character in your pass variable?
If so, then just change your else block to this:
else
{
Console.Write("\b");
pass = pass.Remove(pass.Length -1);
}
I think you are looking for std::any_of
, which will return a true/false answer to detect if an element is in a container (array, vector, deque, etc.)
int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
return i == val;
});
If you want to know where the element is, std::find
will return an iterator to the first element matching whatever criteria you provide (or a predicate you give it).
int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
// not found
}
else
{
// found
}