Sometimes you need to remove the .lock file to get the service to run
I find letter identifiers to be more readable and more indicative of parsed type:
1 - 7f / 10
1 - 7 / 10f
or:
1 - 7d / 10
1 - 7 / 10d
As others have pointed out, thread safety means that a piece of code will work without errors if it's used by more than one thread at once.
It's worth being aware that this sometimes comes at a cost, of computer time and more complex coding, so it isn't always desirable. If a class can be safely used on only one thread, it may be better to do so.
For example, Java has two classes that are almost equivalent, StringBuffer
and StringBuilder
. The difference is that StringBuffer
is thread-safe, so a single instance of a StringBuffer
may be used by multiple threads at once. StringBuilder
is not thread-safe, and is designed as a higher-performance replacement for those cases (the vast majority) when the String is built by only one thread.
this code will return duplicate value in same array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
if(array_count_values($arr)[$item] > 1){
echo "Found Matched value : ".$item." <br />";
}
}
If you only have TypeScript installed for Visual Studio then:
tsc -v
and hit EnterVisual Studio 2017 versions 15.3 and above bind the TypeScript version to individual projects, as this answer points out:
- Right click on the project node in Solution Explorer
- Click Properties
- Go to the TypeScript Build tab
Please check whether you have set two JAVA paths in the Environment Variable section. If you already installed two versions of the JDK, it might be, then double check you have put PATH for Java like below.
PATH --> C:\ProgramData\Oracle\Java\javapath
and also
JAVA_HOME ---> C:\Program Files\Java\jdk1.7.0_02\bin
If both are there, then this sort of error may occur.
If it's OK, then check in the ".ini" file the below area is OK or not. Open ".ini" file and check
-VM path is C:\Program Files\Java\jdk1.7.0_79\bin\
If not, please set it like that and run again.
This is super old, but I figured I'd add my 2c. DATE_FORMAT
does indeed return a string, but I was looking for the CAST
function, in the situation that I already had a datetime string in the database and needed to pattern match against it:
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
In this case, you'd use:
CAST(date_value AS char)
This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.
With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself.
If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__
to help you out here. __file__
is the full path to where the script you are running is located.
So you can fiddle with something like this:
import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
From Excel Macro Security - www.excelfunctions.net:
Macro Security in Excel 2007, 2010 & 2013:
.....
The different Excel file types provided by the latest versions of Excel make it clear when workbook contains macros, so this in itself is a useful security measure. However, Excel also has optional macro security settings, which are controlled via the options menu. These are :
'Disable all macros without notification'
This setting does not allow any macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.
'Disable all macros with notification'
This setting prevents macros from running. However, if there are macros in a workbook, a pop-up is displayed, to warn you that the macros exist and have been disabled.
'Disable all macros except digitally signed macros'
This setting only allow macros from trusted sources to run. All other macros do not run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.
'Enable all macros'
This setting allows all macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros and may not be aware of macros running while you have the file open.
If you trust the macros and are ok with enabling them, select this option:
'Enable all macros'
and this dialog box should not show up for macros.
As for the dialog for saving, after noting that this was running on Excel for Mac 2011, I came across the following question on SO, StackOverflow - Suppress dialog when using VBA to save a macro containing Excel file (.xlsm) as a non macro containing file (.xlsx). From it, removing the dialog does not seem to be possible, except for possibly by some Keyboard Input simulation. I would post another question to inquire about that. Sorry I could only get you halfway. The other option would be to use a Windows computer with Microsoft Excel, though I'm not sure if that is a option for you in this case.
Use a sub query similar to the below.
UPDATE P
SET extrasPrice = sub.TotalPrice from
BookingPitches p
inner join
(Select PitchID, Sum(Price) TotalPrice
from dbo.BookingPitchExtras
Where [Required] = 1
Group by Pitchid
) as Sub
on p.Id = e.PitchId
where p.BookingId = 1
Make sure that your package is installed in your $GOPATH
directory or already inside your workspace/package.
For example: if your $GOPATH = "c:\go"
, make sure that the package inside C:\Go\src\pkgName
Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.
As Joshua Bloch states in Effective Java, 2nd Edition:
The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.
We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:
Pizza(int size) { ... }
Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) { ... }
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.
One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.
The better alternative is to use the Builder Pattern.
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
}
Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.
Pizza pizza = new Pizza.Builder(12)
.cheese(true)
.pepperoni(true)
.bacon(true)
.build();
This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.
I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.
Declare @date1 date = '2016-01-01'
,@date2 date = '2016-03-31'
,@date_index date
Declare @calender table (D date)
SET @date_index = @date1
WHILE @date_index<=@date2
BEGIN
INSERT INTO @calender
SELECT @date_index
SET @date_index = dateadd(day,1,@date_index)
IF @date_index>@date2
Break
ELSE
Continue
END
In your case, because of the constraint you need to delete the duplicated records.
created_at
date - in this case I'm keeping the oldestUSING
to filter the right rowsWITH duplicated AS (
SELECT id,
count(*)
FROM products
GROUP BY id
HAVING count(*) > 1),
ordered AS (
SELECT p.id,
created_at,
rank() OVER (partition BY p.id ORDER BY p.created_at) AS rnk
FROM products o
JOIN duplicated d ON d.id = p.id ),
products_to_delete AS (
SELECT id,
created_at
FROM ordered
WHERE rnk = 2
)
DELETE
FROM products
USING products_to_delete
WHERE products.id = products_to_delete.id
AND products.created_at = products_to_delete.created_at;
Comparing the performance of all the answers mentioned here on Python 3.9.1 and Python 2.7.16.
Answers are mentioned in order of performance:
Arkku's set
difference using subtraction "-" operation - (91.3 nsec per loop)
mquadri$ python3 -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1 - l2"
5000000 loops, best of 5: 91.3 nsec per loop
Moinuddin Quadri's using set().difference()
- (133 nsec per loop)
mquadri$ python3 -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1.difference(l2)"
2000000 loops, best of 5: 133 nsec per loop
Moinuddin Quadri's list comprehension with set
based lookup- (366 nsec per loop)
mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "[x for x in l1 if x not in l2]"
1000000 loops, best of 5: 366 nsec per loop
Donut's list comprehension on plain list - (489 nsec per loop)
mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = [2,3,5,8];" "[x for x in l1 if x not in l2]"
500000 loops, best of 5: 489 nsec per loop
Daniel Pryden's generator expression with set
based lookup and type-casting to list
- (583 nsec per loop) : Explicitly type-casting to list to get the final object as list
, as requested by OP. If generator expression is replaced with list comprehension, it'll become same as Moinuddin Quadri's list comprehension with set
based lookup.
mquadri$ mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "list(x for x in l1 if x not in l2)"
500000 loops, best of 5: 583 nsec per loop
Moinuddin Quadri's using filter()
and explicitly type-casting to list
(need to explicitly type-cast as in Python 3.x, it returns iterator) - (681 nsec per loop)
mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "list(filter(lambda x: x not in l2, l1))"
500000 loops, best of 5: 681 nsec per loop
Akshay Hazari's using combination of functools.reduce
+ filter
-(3.36 usec per loop) : Explicitly type-casting to list
as from Python 3.x it started returned returning iterator. Also we need to import functools
to use reduce
in Python 3.x
mquadri$ python3 -m timeit "from functools import reduce; l1 = [1,2,6,8]; l2 = [2,3,5,8];" "list(reduce(lambda x,y : filter(lambda z: z!=y,x) ,l1,l2))"
100000 loops, best of 5: 3.36 usec per loop
Answers are mentioned in order of performance:
Arkku's set
difference using subtraction "-" operation - (0.0783 usec per loop)
mquadri$ python -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1 - l2"
10000000 loops, best of 3: 0.0783 usec per loop
Moinuddin Quadri's using set().difference()
- (0.117 usec per loop)
mquadri$ mquadri$ python -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1.difference(l2)"
10000000 loops, best of 3: 0.117 usec per loop
Moinuddin Quadri's list comprehension with set
based lookup- (0.246 usec per loop)
mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "[x for x in l1 if x not in l2]"
1000000 loops, best of 3: 0.246 usec per loop
Donut's list comprehension on plain list - (0.372 usec per loop)
mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = [2,3,5,8];" "[x for x in l1 if x not in l2]"
1000000 loops, best of 3: 0.372 usec per loop
Moinuddin Quadri's using filter()
- (0.593 usec per loop)
mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "filter(lambda x: x not in l2, l1)"
1000000 loops, best of 3: 0.593 usec per loop
Daniel Pryden's generator expression with set
based lookup and type-casting to list
- (0.964 per loop) : Explicitly type-casting to list to get the final object as list
, as requested by OP. If generator expression is replaced with list comprehension, it'll become same as Moinuddin Quadri's list comprehension with set
based lookup.
mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "list(x for x in l1 if x not in l2)"
1000000 loops, best of 3: 0.964 usec per loop
Akshay Hazari's using combination of functools.reduce
+ filter
-(2.78 usec per loop)
mquadri$ python -m timeit "l1 = [1,2,6,8]; l2 = [2,3,5,8];" "reduce(lambda x,y : filter(lambda z: z!=y,x) ,l1,l2)"
100000 loops, best of 3: 2.78 usec per loop
pd.wide_to_long
You can add a prefix to your year columns and then feed directly to pd.wide_to_long
. I won't pretend this is efficient, but it may in certain situations be more convenient than pd.melt
, e.g. when your columns already have an appropriate prefix.
df.columns = np.hstack((df.columns[:2], df.columns[2:].map(lambda x: f'Value{x}')))
res = pd.wide_to_long(df, stubnames=['Value'], i='name', j='Date').reset_index()\
.sort_values(['location', 'name'])
print(res)
name Date location Value
0 test Jan-2010 A 12
2 test Feb-2010 A 20
4 test March-2010 A 30
1 foo Jan-2010 B 18
3 foo Feb-2010 B 20
5 foo March-2010 B 25
Properties
.Libraries
.Compile tab
- click Add Jar/Folder
button.Or
Libraries
.Add Jar/Folder
.when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.
//ARGUMENTS
function func(){
console.log(arguments);//[1, 2, 3, 4]
//var arrArguments = arguments.slice();//Uncaught TypeError: undefined is not a function
var arrArguments = [].slice.call(arguments);//cp array with explicity THIS
arrArguments.push('new');
console.log(arrArguments)
}
func(1,2,3,4)//[1, 2, 3, 4, "new"]
Create a table with a normal numeric auto_increment ID, but either define it with ZEROFILL
, or use LPAD
to add zeroes when selecting. Then CONCAT
the values to get your intended behavior. Example #1:
create table so (
id int(3) unsigned zerofill not null auto_increment primary key,
name varchar(30) not null
);
insert into so set name = 'John';
insert into so set name = 'Mark';
select concat('LHPL', id) as id, name from so;
+---------+------+
| id | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+
Example #2:
create table so (
id int unsigned not null auto_increment primary key,
name varchar(30) not null
);
insert into so set name = 'John';
insert into so set name = 'Mark';
select concat('LHPL', LPAD(id, 3, 0)) as id, name from so;
+---------+------+
| id | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+
There is GitHub Enterprise to satisfy your needs. And there is an open source "clone" of Github Enterprise.
PS: Now Github provides unlimited private repositories, bitbucket does the same. you can give a try to both. There are several other solutions as well.
I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:
multiDexEnabled true
And it worked!
Example
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
And clean the project.
I know that the question is answered perfectly, but I also found another way to add new properties and wanted to share it with you:
You can use the function Object.defineProperty()
Found on Mozilla Developer Network
Example:
var o = {}; // Creates a new object
// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", {value : 37,
writable : true,
enumerable : true,
configurable : true});
// 'a' property exists in the o object and its value is 37
// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", {get : function(){ return bValue; },
set : function(newValue){ bValue = newValue; },
enumerable : true,
configurable : true});
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined
// You cannot try to mix both :
Object.defineProperty(o, "conflict", { value: 0x9f91102,
get: function() { return 0xdeadbeef; } });
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
It has the last status code (exit value) of a command.
Your case: HTTP 400
is the right status code for your case from REST perspective as its syntactically incorrect to send sales_tax
instead of tax
, though its a valid JSON. This is normally enforced by most of the server side frameworks when mapping the JSON to objects. However, there are some REST implementations that ignore new key
in JSON object. In that case, a custom content-type
specification to accept only valid fields can be enforced by server-side.
Ideal Scenario for 422:
In an ideal world, 422 is preferred and generally acceptable to send as response if the server understands the content type of the request entity and the syntax of the request entity is correct but was unable to process the data because its semantically erroneous.
Situations of 400 over 422:
Remember, the response code 422 is an extended HTTP (WebDAV) status code. There are still some HTTP clients / front-end libraries that aren't prepared to handle 422. For them, its as simple as "HTTP 422 is wrong, because it's not HTTP". From the service perspective, 400 isn't quite specific.
In enterprise architecture, the services are deployed mostly on service layers like SOA, IDM, etc. They typically serve multiple clients ranging from a very old native client to a latest HTTP clients. If one of the clients doesn't handle HTTP 422, the options are that asking the client to upgrade or change your response code to HTTP 400 for everyone. In my experience, this is very rare these days but still a possibility. So, a careful study of your architecture is always required before deciding on the HTTP response codes.
To handle situation like these, the service layers normally use versioning
or setup configuration
flag for strict HTTP conformance clients to send 400, and send 422 for the rest of them. That way they provide backwards compatibility support for existing consumers but at the same time provide the ability for the new clients to consume HTTP 422.
The latest update to RFC7321 says:
The 400 (Bad Request) status code indicates that the server cannot or
will not process the request due to something that is perceived to be
a client error (e.g., malformed request syntax, invalid request
message framing, or deceptive request routing).
This confirms that servers can send HTTP 400 for invalid request. 400 doesn't refer only to syntax error anymore, however, 422 is still a genuine response provided the clients can handle it.
You can use %%:
printf("100%%");
The result is:
100%
Click on 'Output' tab and make sure you don't have something like:
========== Rebuild All: 14 succeeded, 1 failed, 0 skipped =========
And open your bin
folder and check to see if it's up to date.
I had a whole bunch of typescript errors that I ignored at first, forgetting that they were breaking the build and leading to there being no DLLs copied in.
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
String res =" Application " res=res.trim();
o/p: Application
Note: White space ,blank space are trim or removed
Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.
git add
does not create any files. See also http://gitref.org/basic/#add
Github probably creates the file with touch
and adds the file for tracking automatically. You can do this on the bash
as well.
I've backported the three Material Design progress drawables to Android 4.0, which can be used as a drop-in replacement for regular ProgressBar
, with exactly the same appearance.
These drawables also backported the tinting APIs (and RTL support), and uses ?colorControlActivated
as the default tint. A MaterialProgressBar
widget which extends ProgressBar
has also been introduced for convenience.
DreaminginCodeZH/MaterialProgressBar
This project has also been adopted by afollestad/material-dialogs for progress dialog.
On Android 4.4.4:
On Android 5.1.1:
And do not forget the "new" service type (from the k8s docu):
ExternalName: Maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record with its value. No proxying of any kind is set up.
Note: You need either kube-dns version 1.7 or CoreDNS version 0.0.8 or higher to use the ExternalName type.
Two utilities in package taRifx can be used in concert to produce multi-row tables of nested heirarchies.
library(datasets)
library(taRifx)
library(xtable)
test.by <- bytable(ChickWeight$weight, list( ChickWeight$Chick, ChickWeight$Diet) )
colnames(test.by) <- c('Diet','Chick','Mean Weight')
print(latex.table.by(test.by), include.rownames = FALSE, include.colnames = TRUE, sanitize.text.function = force)
# then add \usepackage{multirow} to the preamble of your LaTeX document
# for longtable support, add ,tabular.environment='longtable' to the print command (plus add in ,floating=FALSE), then \usepackage{longtable} to the LaTeX preamble
I believe you need to reference the current HttpContext
if you are outside of the controller. The MVC controllers have a base reference to the current context. However, outside of that, you have to explicitly declare you want the current HttpContext
return HttpContext.Current.GetOwinContext().Authentication;
As for it not showing up, a new MVC 5 project template using the code you show above (the IAuthenticationManager
) has the following using statements at the top of the account controller:
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using WebApplication2.Models;
Commenting out each one, it appears the GetOwinContext()
is actually a part of the System.Web.Mvc assembly.
Just like Namespace of C# codes.
For the record, general_log and slow_log were introduced in 5.1.6:
http://dev.mysql.com/doc/refman/5.1/en/log-destinations.html
5.2.1. Selecting General Query and Slow Query Log Output Destinations
As of MySQL 5.1.6, MySQL Server provides flexible control over the destination of output to the general query log and the slow query log, if those logs are enabled. Possible destinations for log entries are log files or the general_log and slow_log tables in the mysql database
My case, the server was encrypting with padding disabled. But the client was trying to decrypt with the padding enabled.
While using EVP_CIPHER*, by default the padding is enabled. To disable explicitly we need to do
EVP_CIPHER_CTX_set_padding(context, 0);
So non matching padding options can be one reason.
I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join
helper=1
for i in df1.index:
df1.loc[i,'helper']=helper
helper=helper+1
for i in df2.index:
df2.loc[i,'helper']=helper
helper=helper+1
df1.merge(df2,on='helper',how='outer')
Select Java editor settings for Intellij Select values for Tabsize, Indent & Continuation Intent (I choose 4,4 & 4)
Then Ctrl + Alt + L to format your file (or your selection).
Just an additional note about reflection: I have observed in some special cases, when several classes with the same name exist in different packages, that reflection as used in the top answer may fail to pick the correct class from the object. So if you know what is the package.class of the object, then it's better to access its private field values as follows:
org.deeplearning4j.nn.layers.BaseOutputLayer ll = (org.deeplearning4j.nn.layers.BaseOutputLayer) model.getLayer(0);
Field f = Class.forName("org.deeplearning4j.nn.layers.BaseOutputLayer").getDeclaredField("solver");
f.setAccessible(true);
Solver s = (Solver) f.get(ll);
(This is the example class that was not working for me)
You need to do one thing:
async
before function.const gulp = require('gulp');
gulp.task('message', async function() {
console.log("Gulp is running...");
});
_x000D_
You were close. This will work:
.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }
You needed to put the :hover
on image, and make the .overlay
cover the whole image by adding right:0;
and bottom:0
.
jsfiddle: http://jsfiddle.net/Zf5am/569/
Possible solution without using substr()
#include<iostream>
#include<string>
using namespace std;
int main() {
string c="12345";
int p=0;
for(int i=0;i<c.length();i++) {
cout<<c[i];
p++;
if (p % 2 == 0 && i != c.length()-1) {
cout<<" "<<c[i];
p++;
}
}
}
I would use CSS class .hide { display: none!important; }
.
For hiding/showing, I call .addClass("hide")/.removeClass("hide")
. For checking visibility, I use .hasClass("hide")
.
It's a simple and clear way to check/hide/show elements, if you don't plan to use .toggle()
or .animate()
methods.
Probably because you're using unsafe code.
Are you doing something with pointers or unmanaged assemblies somewhere?
If you ever have the same trouble and try everything online and it doesn't work, it is probably the config cache file that is sending the wrong information. You can find it in bootstrap/cache/config.php. Make sure the credentials are right in there. It took me a week to figure that out. I hope this will help someone someday.
This /[^a-z]/g
solves the problem.
function pangram(str) {
let regExp = /[^a-z]/g;
let letters = str.toLowerCase().replace(regExp, '');
document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2@# %hfr efg uor7 489(*&^% knt lhtkjj ngnm!@#$%^&*()_');
_x000D_
<h4 id="letters"></h4>
_x000D_
Redirection of program output is performed by the shell.
grep ... > output.txt
grep
has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1)
man page for details, specifically the -C
and --color
options.
Swift 5
Similar to @liorco, but need to replace @objc with @IBAction.
class DetailViewController: UIViewController {
@IBOutlet weak var tripDetails: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
...
let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction))
tripDetails.isUserInteractionEnabled = true
tripDetails.addGestureRecognizer(tap)
}
@IBAction func tapFunction(sender: UITapGestureRecognizer) {
print("tap working")
}
}
This is working on Xcode 10.2.
As of PowerShell 5.1 there cmdlet New-LocalUser
which could create local user account.
Example of usage:
Create a user account
New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword
or Create a user account that has a password
$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."
or Create a user account that is connected to a Microsoft account
New-LocalUser -Name "MicrosoftAccount\usr [email protected]" -Description "Description of this account."
Cross platform solution using wxPython:
import wx
wx.App() # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem # Release bitmap
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
If you are using Hibernate 3.6 you can use the code in the accepted answer (provided by Brian Deterling) with slight modification:
CriteriaImpl c = (CriteriaImpl) criteria;
SessionImpl s = (SessionImpl) c.getSession();
SessionFactoryImplementor factory = (SessionFactoryImplementor) s.getSessionFactory();
String[] implementors = factory.getImplementors(c.getEntityOrClassName());
LoadQueryInfluencers lqis = new LoadQueryInfluencers();
CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable) factory.getEntityPersister(implementors[0]), factory, c, implementors[0], lqis);
Field f = OuterJoinLoader.class.getDeclaredField("sql");
f.setAccessible(true);
String sql = (String) f.get(loader);
You don't need awk for that. Using read
in Bash shell should be enough, e.g.
some_command | while read c1 c2; do echo $c2; done
or:
while read c1 c2; do echo $c2; done < in.txt
I faced this issue, and resolved this issue using getchar() to catch the ('\n') new char
let signUpVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUp")
// self.present(signUpVC, animated: false, completion: nil)
self.navigationController?.pushViewController(signUpVC, animated: true)
The following would need extensive customisation to format the table correctly, but the bones of it works:
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import pandas as pd
df = pd.DataFrame({ 'A' : 1.,
'B' : pd.Series(1,index=list(range(4)),dtype='float32'),
'C' : np.array([3] * 4,dtype='int32'),
'D' : pd.Categorical(["test","train","test","train"]),
'E' : 'foo' })
class DrawTable():
def __init__(self,_df):
self.rows,self.cols = _df.shape
img_size = (300,200)
self.border = 50
self.bg_col = (255,255,255)
self.div_w = 1
self.div_col = (128,128,128)
self.head_w = 2
self.head_col = (0,0,0)
self.image = Image.new("RGBA", img_size,self.bg_col)
self.draw = ImageDraw.Draw(self.image)
self.draw_grid()
self.populate(_df)
self.image.show()
def draw_grid(self):
width,height = self.image.size
row_step = (height-self.border*2)/(self.rows)
col_step = (width-self.border*2)/(self.cols)
for row in range(1,self.rows+1):
self.draw.line((self.border-row_step//2,self.border+row_step*row,width-self.border,self.border+row_step*row),fill=self.div_col,width=self.div_w)
for col in range(1,self.cols+1):
self.draw.line((self.border+col_step*col,self.border-col_step//2,self.border+col_step*col,height-self.border),fill=self.div_col,width=self.div_w)
self.draw.line((self.border-row_step//2,self.border,width-self.border,self.border),fill=self.head_col,width=self.head_w)
self.draw.line((self.border,self.border-col_step//2,self.border,height-self.border),fill=self.head_col,width=self.head_w)
self.row_step = row_step
self.col_step = col_step
def populate(self,_df2):
font = ImageFont.load_default().font
for row in range(self.rows):
print(_df2.iloc[row,0])
self.draw.text((self.border-self.row_step//2,self.border+self.row_step*row),str(_df2.index[row]),font=font,fill=(0,0,128))
for col in range(self.cols):
text = str(_df2.iloc[row,col])
text_w, text_h = font.getsize(text)
x_pos = self.border+self.col_step*(col+1)-text_w
y_pos = self.border+self.row_step*row
self.draw.text((x_pos,y_pos),text,font=font,fill=(0,0,128))
for col in range(self.cols):
text = str(_df2.columns[col])
text_w, text_h = font.getsize(text)
x_pos = self.border+self.col_step*(col+1)-text_w
y_pos = self.border - self.row_step//2
self.draw.text((x_pos,y_pos),text,font=font,fill=(0,0,128))
def save(self,filename):
try:
self.image.save(filename,mode='RGBA')
print(filename," Saved.")
except:
print("Error saving:",filename)
table1 = DrawTable(df)
table1.save('C:/Users/user/Pictures/table1.png')
The output looks like this:
In host computer/server go to Sql server management studio --> open Security Section on left hand --> right click on Login, select New Login and then create a new account for your database which you want to connect to.
Check the TCP/IP Protocol is Enable. go to All programs --> Microsoft SQL server 2008 --> Configuration Tools --> open Sql server configuration manager. On the left hand select client protocols (based on your operating system 32/64 bit). On the right hand, check TCP/IP Protocol be Enabled.
In Remote computer/server, open Data source administrator. Control panel --> Administrative tools --> Data sources (ODBC).
In User DSN or System DSN , click Add button and select Sql Server driver and then press Finish.
Enter Name.
Enter Server, note that: if you want to enter host computer address, you should enter that`s IP address without "\\". eg. 192.168.1.5 and press Next.
Select With SQL Server authentication using a login ID and password entered by the user.
At the bellow enter your login ID and password which you created on first step. and then click Next.
If shown Database is your database, click Next and then Finish.
I faced the same issue, I tried the below solution and it worked for me
In Android SDK Manager Window, click on Tools->Options-> under "Others", check "Force https://... sources to be fetched using http://..."
Okay I have got it working, hope this information is useful.
First of all I now realize that not only do self-extracting zip start extracting with doubleclick, but they require no extraction application to be installed on the users computer because the extractor code is in the archive itself. This means that you will get a different user experience depending on what you application you use to create the sfx
I went with WinRar as follows, this does not require you to create an sfx file, everything can be created via the gui:
The resultant exe unzips to a temporary folder and then starts the installer
Another way to do this would be to by using map
.
>>> a
[1, 2, 3]
>>> b
[4, 5, 6]
>>> for i,j in map(None,a,b):
... print i,j
...
1 4
2 5
3 6
One difference in using map compared to zip is, with zip the length of new list is
same as the length of shortest list.
For example:
>>> a
[1, 2, 3, 9]
>>> b
[4, 5, 6]
>>> for i,j in zip(a,b):
... print i,j
...
1 4
2 5
3 6
Using map on same data:
>>> for i,j in map(None,a,b):
... print i,j
...
1 4
2 5
3 6
9 None
Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.
An example:
function changeParam(x, y, z) {
x = 3;
y = "new string";
z["key2"] = "new";
z["key3"] = "newer";
z = {"new" : "object"};
}
var a = 1,
b = "something",
c = {"key1" : "whatever", "key2" : "original value"};
changeParam(a, b, c);
// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...
Press Ctrl+` (Back Quote).
Then select "Switch Color Scheme" or press 1.
Select "Dracula" or press 2.
This error occurred to me while trying to connect to the Google Cloud SQL using MySQL Workbench 6.3.
After a little research I found that my IP address has been changed by the internet provider and he was not allowed in the Cloud SQL.
I authorized it and went back to work.
While configure could find my Boost installation, CMake could not.
Locate FindBoost.cmake and look for LIBRARY_HINTS to see what sub-packages it is looking for. In my case it wanted the MPI and graph libraries.
# Compute component-specific hints.
set(_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT "")
if(${COMPONENT} STREQUAL "mpi" OR ${COMPONENT} STREQUAL "mpi_python" OR
${COMPONENT} STREQUAL "graph_parallel")
foreach(lib ${MPI_CXX_LIBRARIES} ${MPI_C_LIBRARIES})
if(IS_ABSOLUTE "${lib}")
get_filename_component(libdir "${lib}" PATH)
string(REPLACE "\\" "/" libdir "${libdir}")
list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT ${libdir})
endif()
endforeach()
endif()
apt-cache search ... I installed the dev packages since I was building code, and the dev package drags in all the dependencies. I'm not so sure that a standard Boost install needs Open MPI, but this is OK for now.
sudo apt-get install libboost-mpi-dev libboost-mpi-python-dev
sudo apt-get install libboost-graph-parallel-dev
DROP
The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE. Table level lock will be added when Truncating.
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. Row level lock will be added when deleting.
From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands
Looking at the source code of Virtus, I'd maybe do something like this:
def to_boolean(s)
map = Hash[%w[true yes 1].product([true]) + %w[false no 0].product([false])]
map[s.to_s.downcase]
end
For all the Kotlin developers out there:
Here is the Android Studio proposed solution to send data to your Fragment (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").
Put this in your Fragment:
class MyFragment: Fragment {
...
companion object {
@JvmStatic
fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
arguments = Bundle().apply {
putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
}
}
}
}
.apply
is a nice trick to set data when an object is created, or as they state here:
Calls the specified function [block] with
this
value as its receiver and returnsthis
value.
Then in your Activity or Fragment do:
val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here
and read the Arguments in your Fragment such as:
private var isMyBoolean = false
override fun onAttach(context: Context?) {
super.onAttach(context)
arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
isMyBoolean = it
}
}
To "send" data back to your Activity, simply define a function in your Activity and do the following in your Fragment:
(activity as? YourActivityClass)?.callYourFunctionLikeThis(date) // your function will not be called if your Activity is null or is a different Class
Enjoy the magic of Kotlin!
Here is a version that uses a sequence or numbers table rather than a loop. You can modify the WHERE clause to suite your personal rules for when to convert a character to upper case. I have just included a simple set that will upper case any letter that is proceeded by a non-letter with the exception of apostrophes. This does how ever mean that 123apple would have a match on the "a" because "3" is not a letter. If you want just white-space (space, tab, carriage-return, line-feed), you can replace the pattern '[^a-z]'
with '[' + Char(32) + Char(9) + Char(13) + Char(10) + ']'
.
CREATE FUNCTION String.InitCap( @string nvarchar(4000) ) RETURNS nvarchar(4000) AS
BEGIN
-- 1. Convert all letters to lower case
DECLARE @InitCap nvarchar(4000); SET @InitCap = Lower(@string);
-- 2. Using a Sequence, replace the letters that should be upper case with their upper case version
SELECT @InitCap = Stuff( @InitCap, n, 1, Upper( SubString( @InitCap, n, 1 ) ) )
FROM (
SELECT (1 + n1.n + n10.n + n100.n + n1000.n) AS n
FROM (SELECT 0 AS n UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS n1
CROSS JOIN (SELECT 0 AS n UNION SELECT 10 UNION SELECT 20 UNION SELECT 30 UNION SELECT 40 UNION SELECT 50 UNION SELECT 60 UNION SELECT 70 UNION SELECT 80 UNION SELECT 90) AS n10
CROSS JOIN (SELECT 0 AS n UNION SELECT 100 UNION SELECT 200 UNION SELECT 300 UNION SELECT 400 UNION SELECT 500 UNION SELECT 600 UNION SELECT 700 UNION SELECT 800 UNION SELECT 900) AS n100
CROSS JOIN (SELECT 0 AS n UNION SELECT 1000 UNION SELECT 2000 UNION SELECT 3000) AS n1000
) AS Sequence
WHERE
n BETWEEN 1 AND Len( @InitCap )
AND SubString( @InitCap, n, 1 ) LIKE '[a-z]' /* this character is a letter */
AND (
n = 1 /* this character is the first `character` */
OR SubString( @InitCap, n-1, 1 ) LIKE '[^a-z]' /* the previous character is NOT a letter */
)
AND (
n < 3 /* only test the 3rd or greater characters for this exception */
OR SubString( @InitCap, n-2, 3 ) NOT LIKE '[a-z]''[a-z]' /* exception: The pattern <letter>'<letter> should not capatolize the letter following the apostrophy */
)
-- 3. Return the modified version of the input
RETURN @InitCap
END
itemgetter
(see other answers) is (as I know) more efficient for large dictionaries but for the common case, I believe that d.get
wins. And it does not require an extra import
.
>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
... k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)
Note that alternatively you can set d.__getitem__
as key
function which may provide a small performance boost over d.get
.
Tip: Please do not consider this as an answer. Just to help someone else too.
I had similar issue while installing psycopg2. I installedbuild-essential
, python-dev
and also libpq-dev
but it thrown same error.
error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
As I was in hurry in deployment so finally just copied full line from @user3440631's answer.
sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev
And It worked like a charm. but could not find which package has resolved my issue.
Please update the comment if anyone have idea about psycopg2
dependancy package from above command.
I think this will bring it back using 3.0
.navbar .divider-vertical {
height: 50px;
margin: 0 9px;
border-right: 1px solid #ffffff;
border-left: 1px solid #f2f2f2;
}
.navbar-inverse .divider-vertical {
border-right-color: #222222;
border-left-color: #111111;
}
@media (max-width: 767px) {
.navbar-collapse .nav > .divider-vertical {
display: none;
}
}
You can disable SSL certificate checking by adding one or more of these command line parameters:
-Dmaven.wagon.http.ssl.insecure=true
- enable use of relaxed SSL check for user generated certificates.-Dmaven.wagon.http.ssl.allowall=true
- enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.-Dmaven.wagon.http.ssl.ignore.validity.dates=true
- ignore issues with certificate dates.Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/
Here's the oneliner for an easy copy-and-paste:
-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true
Ajay Gautam suggested that you could also add the above to the ~/.mavenrc
file as not to have to specify it every time at command line:
$ cat ~/.mavenrc
MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"
here is a solution:
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
For this you can use the readonly
modifier. Object properties which are readonly
can only be assigned during initialization of the object.
Example in classes:
class Circle {
readonly radius: number;
constructor(radius: number) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius * 2;
}
}
const circle = new Circle(12);
circle.radius = 12; // Cannot assign to 'radius' because it is a read-only property.
Example in Object literals:
type Rectangle = {
readonly height: number;
readonly width: number;
};
const square: Rectangle = { height: 1, width: 2 };
square.height = 5 // Cannot assign to 'height' because it is a read-only property
It's also worth knowing that the readonly
modifier is purely a typescript construct and when the TS is compiled to JS the construct will not be present in the compiled JS. When we are modifying properties which are readonly the TS compiler will warn us about it (it is valid JS).
My version of the regular expressions technique that's been suggested already:
values=(foo bar)
requestedValue=bar
requestedValue=${requestedValue##[[:space:]]}
requestedValue=${requestedValue%%[[:space:]]}
[[ "${values[@]/#/X-}" =~ "X-${requestedValue}" ]] || echo "Unsupported value"
What's happening here is that you're expanding the entire array of supported values into words and prepending a specific string, "X-" in this case, to each of them, and doing the same to the requested value. If this one is indeed contained in the array, then the resulting string will at most match one of the resulting tokens, or none at all in the contrary. In the latter case the || operator triggers and you know you're dealing with an unsupported value. Prior to all of that the requested value is stripped of all leading and trailing whitespace through standard shell string manipulation.
It's clean and elegant, I believe, though I'm not too sure of how performant it may be if your array of supported values is particularly large.
What you call "Two-Way SSL" is usually called TLS/SSL with client certificate authentication.
In a "normal" TLS connection to example.com only the client verifies that it is indeed communicating with the server for example.com. The server doesn't know who the client is. If the server wants to authenticate the client the usual thing is to use passwords, so a client needs to send a user name and password to the server, but this happens inside the TLS connection as part of an inner protocol (e.g. HTTP) it's not part of the TLS protocol itself. The disadvantage is that you need a separate password for every site because you send the password to the server. So if you use the same password on for example PayPal and MyPonyForum then every time you log into MyPonyForum you send this password to the server of MyPonyForum so the operator of this server could intercept it and try it on PayPal and can issue payments in your name.
Client certificate authentication offers another way to authenticate the client in a TLS connection. In contrast to password login, client certificate authentication is specified as part of the TLS protocol. It works analogous to the way the client authenticates the server: The client generates a public private key pair and submits the public key to a trusted CA for signing. The CA returns a client certificate that can be used to authenticate the client. The client can now use the same certificate to authenticate to different servers (i.e. you could use the same certificate for PayPal and MyPonyForum without risking that it can be abused). The way it works is that after the server has sent its certificate it asks the client to provide a certificate too. Then some public key magic happens (if you want to know the details read RFC 5246) and now the client knows it communicates with the right server, the server knows it communicates with the right client and both have some common key material to encrypt and verify the connection.
You can create a Blob
from your base64 data, and then read it asDataURL
:
var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];
var the_file = new Blob([window.atob(png)], {type: 'image/png', encoding: 'utf-8'});
var fr = new FileReader();
fr.onload = function ( oFREvent ) {
var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
v = atob(v);
var good_b64 = btoa(decodeURIComponent(escape(v)));
document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);
Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/
Alternatively, you can use .readAsText
, it works fine, and its more elegant.. but for some reason text does not sound right ;)
fr.onload = function ( oFREvent ) {
document.getElementById("uploadPreview").src = "data:image/png;base64,"
+ btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here
Full example: http://jsfiddle.net/tTYb8/3/
In my case I had the same issue on running from eclipse. Just did the following to resolve it: Right Click the Project --> Mavan --> Update Project.
And it worked!
try using %%
to print % sign .
Missing implementation of a function in class
The reason I faced this issue was because I had deleted the function's implementation from the cpp file, but forgotten to delete the declaration from the .h file.
My answer doesn't specifically answer your question, but lets people who come to this thread looking for answer know that this can also one cause.
$int = settype("100", "integer"); //convert the numeric string to int
I don't think desc
takes an na.rm
argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NA
s, use na.omit
(base) or tidyr::drop_na
:
outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If you only want to remove NA
s from the HeartAttackDeath column, filter with is.na
, or use tidyr::drop_na
:
outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
As pointed out at the dupe, complete.cases
can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:
outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If it's fixed layout you can do like that:
public void onClick(View v) {
ViewGroup parent = (ViewGroup) IdNumber.this.getParent();
EditText firstName = (EditText) parent.findViewById(R.id.display_name);
firstName.setText("Some Text");
}
If you want find the EditText in flexible layout, I will help you later. Hope this help.
As Jim Garrison said in the comment, no obvious reason why you'd make a one-element list out of drug.upper()
(which implies drug is a string).
But that's not your error, as your function medications_minimum3()
doesn't even use the second argument (something you should fix).
TypeError: unhashable type: 'list'
usually means that you are trying to use a list as a hash argument (like for accessing a dictionary). I'd look for the error in counter[row[11]]+=1
-- are you sure that row[11]
is of the right type? Sounds to me it might be a list.
For more general boolean functions that you would like to use as a filter and that depend on more than one column, you can use:
df = df[df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)]
where f is a function that is applied to every pair of elements (x1, x2) from col_1 and col_2 and returns True or False depending on any condition you want on (x1, x2).
I had the same issue but solved it by using !important
. I forgot about the inheritance in CSS
. Just a tip to check first.
<?php if ($my_name == 'aboutme') { ?>
HTML_GOES_HERE
<?php } ?>
Try the following snippet, using a dictionary comprehension:
value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }
In the above code we find the difference of the keys and then rebuild a dict
taking the corresponding values.
Others have pointed out that a get_FOO_display method is what you need. I'm using this:
def get_type(self):
return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]
which iterates over all of the choices that a particular item has until it finds the one that matches the items type
@Edward Brey's method works great. If someone would also like to copy & paste the imports for the OnSwipeTouchListener
, here they are:
import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
you try this:
<input type="submit" style="font-face: 'Comic Sans MS'; font-size: larger; color: teal; background-color: #FFFFC0; border: 3pt ridge lightgrey" value=" Send Me! ">
There is a "Enable Version Control Integration..." option from the VCS popup (control V). Until you do this and select a VCS the VCS system context menus do not show up and the VCS features are not fully integrated. Not sure why this is so hidden?
Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads
From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.
$ pip install --user ipykernel
$ python -m ipykernel install --user --name=test2
You can somehow reproduce the behavior of "OR" using & and :not.
SomeElement.SomeClass [data-statement="things are getting more complex"] :not(:not(A):not(B)) {
/* things aren't so complex for A or B */
}
Use the Stopwatch
class.
Provides a set of methods and properties that you can use to accurately measure elapsed time.
There is some good info on implementing it here:
Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch
I have never considered it to be a bad practice to throw an exception in the constructor. When the class is designed, you have a certain idea in mind of what the structure for that class should be. If someone else has a different idea and tries to execute that idea, then you should error accordingly, giving the user feedback on what the error is. In your case, you might consider something like
if (age < 0) throw new NegativeAgeException("The person you attempted " +
"to construct must be given a positive age.");
where NegativeAgeException
is an exception class that you constructed yourself, possibly extending another exception like IndexOutOfBoundsException
or something similar.
Assertions don't exactly seem to be the way to go, either, since you're not trying to discover bugs in your code. I would say terminating with an exception is absolutely the right thing to do here.
width: 80vmin; height: 80vmin;
CSS does 80% of the smallest view, height or width
verify
itself returns an error if expired. Safer as @Gabriel said.
const jwt = require('jsonwebtoken')
router.use((req, res, next) => {
const token = yourJwtService.getToken(req) // Get your token from the request
jwt.verify(token, req.app.get('your-secret'), function(err, decoded) {
if (err) throw new Error(err) // Manage different errors here (Expired, untrusted...)
req.auth = decoded // If no error, token info is returned in 'decoded'
next()
});
})
And same written in async/await
syntax:
const jwt = require('jsonwebtoken')
const jwtVerifyAsync = util.promisify(jwt.verify);
router.use(async (req, res, next) => {
const token = yourJwtService.getToken(req) // Get your token from the request
try {
req.auth = await jwtVerifyAsync(token, req.app.get('your-secret')) // If no error, token info is returned
} catch (err) {
throw new Error(err) // Manage different errors here (Expired, untrusted...)
}
next()
});
In your_controller write this...
public function update_title()
{
$data = array
(
'table_id' => $this->input->post('table_id'),
'table_title' => $this->input->post('table_title')
);
$this->load->model('your_model'); // First load the model
if($this->your_model->update_title($data)) // call the method from the controller
{
// update successful...
}
else
{
// update not successful...
}
}
While in your_model...
public function update_title($data)
{
$this->db->set('table_title',$data['title'])
->where('table_id',$data['table_id'])
->update('your_table');
}
This will works fine...
Here is a simple example:
EXEC sp_executesql @sql, N'@p1 INT, @p2 INT, @p3 INT', @p1, @p2, @p3;
Your call will be something like this
EXEC sp_executesql @statement, N'@LabID int, @BeginDate date, @EndDate date, @RequestTypeID varchar', @LabID, @BeginDate, @EndDate, @RequestTypeID
If working with Python =2.6 (including 3.x), you can:
from __future__ import division
import operator, itertools
def getmin(alist):
return min(
(operator.div(*pair), pair)
for pair in itertools.product(alist, repeat=2)
)[1]
getmin([1, 2, 3, 4, 5])
EDIT: Now that I think of it and if I remember my mathematics correctly, this should also give the answer assuming that all numbers are non-negative:
def getmin(alist):
return min(alist), max(alist)
You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data. -don
You can do something like this instead.
return new DateTime(2010, Month, 1).ToString("MMM");
Work 100% sure try this code for the get all hashmap key and value
static HashMap<String, String> map = new HashMap<>();
map.put("one" " a " );
map.put("two" " b " );
map.put("three" " c " );
map.put("four" " d " );
just call this method whenever you want to show the HashMap value
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
Sql server internally build the script. It create a temporary table with new changes and copy the data and drop current table then recreate the table insert from temp table. I find it from "Generate Change script" option ssms 2014. Script like this. From Here: How to change column order in a table using sql query
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_emps
(
id int NULL,
ename varchar(20) NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_emps SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.emps)
EXEC('INSERT INTO dbo.Tmp_emps (id, ename)
SELECT id, ename FROM dbo.emps WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.emps
GO
EXECUTE sp_rename N'dbo.Tmp_emps', N'emps', 'OBJECT'
GO
COMMIT
Eli, it is important to remember that in css specificity goes a long way. If your inline css is using the !important and isn't overriding the imported stylesheet rules then closely observe the code using a tool such as 'firebug' for firefox. It will show you the css being applied to your element. If there is a syntax error firebug will show you in the warning panel that it has thrown out the declaration.
Also remember that in general an id is more specific than a class is more specific than an element.
Hope that helps.
-Rick
It was mentioned in the unset manual's page in 2009:
unset()
does just what its name says - unset a variable. It does not force immediate memory freeing. PHP's garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway, or as late as before the script would run out of memory, whatever occurs first.If you are doing
$whatever = null;
then you are rewriting variable's data. You might get memory freed / shrunk faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time.
(Since 2013, that unset
man page don't include that section anymore)
Note that until php5.3, if you have two objects in circular reference, such as in a parent-child relationship, calling unset() on the parent object will not free the memory used for the parent reference in the child object. (Nor will the memory be freed when the parent object is garbage-collected.) (bug 33595)
The question "difference between unset and = null" details some differences:
unset($a)
also removes $a
from the symbol table; for example:
$a = str_repeat('hello world ', 100);
unset($a);
var_dump($a);
Outputs:
Notice: Undefined variable: a in xxx
NULL
But when
$a = null
is used:
$a = str_repeat('hello world ', 100);
$a = null;
var_dump($a);
Outputs:
NULL
It seems that
$a = null
is a bit faster than itsunset()
counterpart: updating a symbol table entry appears to be faster than removing it.
unset
) variable, an error will be triggered and the value for the variable expression will be null. (Because, what else should PHP do? Every expression needs to result in some value.)3 years of experience later, I've come back to this question and would suggest to write it like this:
string output = new JavaScriptSerializer().Serialize(ListOfMyObject);
One line of code.
You can always take a look at the .size
attribute. It is defined as an integer, and is zero (0
) when there are no elements in the array:
import numpy as np
a = np.array([])
if a.size == 0:
# Do something when `a` is empty
This answer describes a solution using MVVM.
This solution is great if you want to add a logging box to a window, that automatically scrolls to the bottom each time a new logging message is added.
Once these attached properties are added, they can be reused anywhere, so it makes for very modular and reusable software.
Add this XAML:
<TextBox IsReadOnly="True"
Foreground="Gainsboro"
FontSize="13"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True"
attachedBehaviors:TextBoxApppendBehaviors.AppendText="{Binding LogBoxViewModel.AttachedPropertyAppend}"
attachedBehaviors:TextBoxClearBehavior.TextBoxClear="{Binding LogBoxViewModel.AttachedPropertyClear}"
TextWrapping="Wrap">
Add this attached property:
public static class TextBoxApppendBehaviors
{
#region AppendText Attached Property
public static readonly DependencyProperty AppendTextProperty =
DependencyProperty.RegisterAttached(
"AppendText",
typeof (string),
typeof (TextBoxApppendBehaviors),
new UIPropertyMetadata(null, OnAppendTextChanged));
public static string GetAppendText(TextBox textBox)
{
return (string)textBox.GetValue(AppendTextProperty);
}
public static void SetAppendText(
TextBox textBox,
string value)
{
textBox.SetValue(AppendTextProperty, value);
}
private static void OnAppendTextChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
if (args.NewValue == null)
{
return;
}
string toAppend = args.NewValue.ToString();
if (toAppend == "")
{
return;
}
TextBox textBox = d as TextBox;
textBox?.AppendText(toAppend);
textBox?.ScrollToEnd();
}
#endregion
}
And this attached property (to clear the box):
public static class TextBoxClearBehavior
{
public static readonly DependencyProperty TextBoxClearProperty =
DependencyProperty.RegisterAttached(
"TextBoxClear",
typeof(bool),
typeof(TextBoxClearBehavior),
new UIPropertyMetadata(false, OnTextBoxClearPropertyChanged));
public static bool GetTextBoxClear(DependencyObject obj)
{
return (bool)obj.GetValue(TextBoxClearProperty);
}
public static void SetTextBoxClear(DependencyObject obj, bool value)
{
obj.SetValue(TextBoxClearProperty, value);
}
private static void OnTextBoxClearPropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
if ((bool)args.NewValue == false)
{
return;
}
var textBox = (TextBox)d;
textBox?.Clear();
}
}
Then, if you're using a dependency injection framework such as MEF, you can place all of the logging-specific code into it's own ViewModel:
public interface ILogBoxViewModel
{
void CmdAppend(string toAppend);
void CmdClear();
bool AttachedPropertyClear { get; set; }
string AttachedPropertyAppend { get; set; }
}
[Export(typeof(ILogBoxViewModel))]
public class LogBoxViewModel : ILogBoxViewModel, INotifyPropertyChanged
{
private readonly ILog _log = LogManager.GetLogger<LogBoxViewModel>();
private bool _attachedPropertyClear;
private string _attachedPropertyAppend;
public void CmdAppend(string toAppend)
{
string toLog = $"{DateTime.Now:HH:mm:ss} - {toAppend}\n";
// Attached properties only fire on a change. This means it will still work if we publish the same message twice.
AttachedPropertyAppend = "";
AttachedPropertyAppend = toLog;
_log.Info($"Appended to log box: {toAppend}.");
}
public void CmdClear()
{
AttachedPropertyClear = false;
AttachedPropertyClear = true;
_log.Info($"Cleared the GUI log box.");
}
public bool AttachedPropertyClear
{
get { return _attachedPropertyClear; }
set { _attachedPropertyClear = value; OnPropertyChanged(); }
}
public string AttachedPropertyAppend
{
get { return _attachedPropertyAppend; }
set { _attachedPropertyAppend = value; OnPropertyChanged(); }
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Here's how it works:
2 ways to do it
insert tbl (other, col1, intcol) values ('abc', 123, NULL)
or just omit it from the column list
insert tbl (other, col1) values ('abc', 123)
Don't forget for long long int
:
long long int id = [obj.id longLongValue];
[NSString stringWithFormat:@"this is my id: %lld", id]
When you use a web service you have a client and a server:
When you use a message queue like RabbitMQ, Beanstalkd, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:
Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.
Since Eclipse 4.7/Oxygen released in June 2017, there is a new concept of "Triggers for breakpoints", which is displayed as a small "T" next to the breakpoint "blue bullet" icon.
All the other breakpoints that are initially suppressed by triggers will be hit only after any of the trigger points has been hit. All the triggers are disabled after a trigger point is hit and will be re-enabled after the run.
In order to reset all the "trigger" flags, you need to do the following steps :
Note : this step does not delete all your breakpoints, which occurs when selecting "Remove All" in the same contextual menu.
Note : the keyboard shortcut to enable the triggers is "Alt-R", which takes precedence on the shortcut to open the "Run" menu with its mnemonics, when the "Breakpoints" view is selected.
Performance-Wise this probably might not be the best solution but it works.
var str = "filename:with&bad$separators.txt";
char[] charArray = new char[] { '#', '%', '&', '{', '}', '\\', '<', '>', '*', '?', '/', ' ', '$', '!', '\'', '"', ':', '@' };
foreach (var singleChar in charArray)
{
str = str.Replace(singleChar, '_');
}
How to post file using an object in memory (like a JSON object):
import axios from 'axios';
import * as FormData from 'form-data'
async function sendData(jsonData){
// const payload = JSON.stringify({ hello: 'world'});
const payload = JSON.stringify(jsonData);
const bufferObject = Buffer.from(payload, 'utf-8');
const file = new FormData();
file.append('upload_file', bufferObject, "b.json");
const response = await axios.post(
lovelyURL,
file,
headers: file.getHeaders()
).toPromise();
console.log(response?.data);
}
You must use one of the following ways:
string s = @"loooooooooooooooooooooooong loooooong
long long long";
string s = "loooooooooong loooong" +
" long long" ;
$letters = array("a", "b", "c", "d", "e", "f", "g"); // this array can n no. of values
$result = substr(implode(", ", $letters), 0);
echo $result
output-> a,b,c,d,e,f,g
These paradigms don't have to be mutually exclusive. If you look at python, it supports functions and classes, but at the same time, everything is an object, including functions. You can mix and match functional/oop/procedural style all in one piece of code.
What I mean is, in functional languages (at least in Haskell, the only one I studied) there are no statements! functions are only allowed one expression inside them!! BUT, functions are first-class citizens, you can pass them around as parameters, along with a bunch of other abilities. They can do powerful things with few lines of code.
While in a procedural language like C, the only way you can pass functions around is by using function pointers, and that alone doesn't enable many powerful tasks.
In python, a function is a first-class citizen, but it can contain arbitrary number of statements. So you can have a function that contains procedural code, but you can pass it around just like functional languages.
Same goes for OOP. A language like Java doesn't allow you to write procedures/functions outside of a class. The only way to pass a function around is to wrap it in an object that implements that function, and then pass that object around.
In Python, you don't have this restriction.
for Binary installer use this:
to stop:
sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
to start:
sudo /Library/StartupItems/MySQLCOM/MySQLCOM start
to restart:
sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart
If you add a new line of text at the end of the existing file which does not already have a newline character
at the end, the diff will show the old last line as having been modified, even though conceptually it wasn’t.
This is at least one good reason to add a newline character
at the end.
A file contains:
A() {
// do something
}
Hexdump:
00000000: 4128 2920 7b0a 2020 2020 2f2f 2064 6f20 A() {. // do
00000010: 736f 6d65 7468 696e 670a 7d something.}
You now edit it to
A() {
// do something
}
// Useful comment
Hexdump:
00000000: 4128 2920 7b0a 2020 2020 2f2f 2064 6f20 A() {. // do
00000010: 736f 6d65 7468 696e 670a 7d0a 2f2f 2055 something.}.// U
00000020: 7365 6675 6c20 636f 6d6d 656e 742e 0a seful comment..
The git diff will show:
-}
\ No newline at end of file
+}
+// Useful comment.
In other words, it shows a larger diff than conceptually occurred. It shows that you deleted the line }
and added the line }\n
. This is, in fact, what happened, but it’s not what conceptually happened, so it can be confusing.
<div class="button_style">
This is your button value
</div>
.button_style{
background-color: Transparent;
border: none; /* Your can add different style/properties of button Here*/
cursor:pointer;
}
Yes, this happens when manipulating an element which doesn't exist yet (a few contributors here also made a good point with the unique ID). I ran into a similar issue. I also need to pass an argument to the function manipulating the element soon to be rendered.
The solution checked off here didn't help me. Finally I found one that worked right out of the box. And it's very pretty, too - a callback.
Instead of:
$( '#header' ).focus();
or the tempting:
setTimeout( $( '#header' ).focus(), 500 );
Try this:
setTimeout( function() { $( '#header' ).focus() }, 500 );
In my code, testing passing the argument, this didn't work, the timeout was ignored:
setTimeout( alert( 'Hello, '+name ), 1000 );
This works, the timeout ticks:
setTimeout( function() { alert( 'Hello, '+name ) }, 1000 );
It sucks that w3schools doesn't mention it.
Credits go to: makemineatriple.com.
Hopefully, this helps somebody who comes here.
This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf
Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.
After successfully running autogen.sh/configure, compile with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make
The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.
I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
Bellow code working as fine, when we don't know identity column name.
Need to copy data into new temp table like Invoice_DELETED
.
and next time we using:
insert into Invoice_DELETED select * from Invoice where ...
SELECT t1.*
INTO Invoice_DELETED
FROM Invoice t1
LEFT JOIN Invoice ON 1 = 0
--WHERE t1.InvoiceID = @InvoiceID
For more explanation see: https://dba.stackexchange.com/a/138345/101038
List is an interface. You need a specific class in the end so either try
List l = new ArrayList();
or
List l = new LinkedList();
Whichever suit your needs.
var groupedCustomerList = CustomerList
.GroupBy(u => u.GroupID, u=>{
u.Name = "User" + u.Name;
return u;
}, (key,g)=>g.ToList())
.ToList();
If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:
public class Customer {
public int ID { get; set; }
public string Name { get; set; }
public int GroupID { get; set; }
public Customer CloneWithNamePrepend(string prepend){
return new Customer(){
ID = this.ID,
Name = prepend + this.Name,
GroupID = this.GroupID
};
}
}
//Then
var groupedCustomerList = CustomerList
.GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
.ToList();
I think you may want to display the Customer
differently without modifying the original data. If so you should design your class Customer
differently, like this:
public class Customer {
public int ID { get; set; }
public string Name { get; set; }
public int GroupID { get; set; }
public string Prefix {get;set;}
public string FullName {
get { return Prefix + Name;}
}
}
//then to display the fullname, just get the customer.FullName;
//You can also try adding some override of ToString() to your class
var groupedCustomerList = CustomerList
.GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
.ToList();
I've solved it, it can be done executing:
netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33
To remove forwarding:
netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111
My solution, using a SwitchCompat
and Kotlin. In my situation, i needed to react to a change only if the user triggered it through the UI. In fact, my switch reacts to a LiveData
, and this made both setOnClickListener
and setOnCheckedChangeListener
unusable. setOnClickListener
in fact reacts correctly to user interaction, but it's not triggered if the user drags the thumb across the switch. setOnCheckedChangeListener
on the other end is triggered also if the switch is toggled programmatically (for example by an observer). Now in my case the switch was present on two fragments, and so onRestoreInstanceState would trigger in some cases the switch with an old value overwriting the correct value.
So, i looked at the code of SwitchCompat, and was able to mimic it's behaviour successfully in distinguishing click and drag and used that to build a custom touchlistener that works as it should. Here we go:
/**
* This function calls the lambda function passed with the right value of isChecked
* when the switch is tapped with single click isChecked is relative to the current position so we pass !isChecked
* when the switch is dragged instead, the position of the thumb centre where the user leaves the
* thumb is compared to the middle of the switch, and we assume that left means false, right means true
* (there is no rtl or vertical switch management)
* The behaviour is extrapolated from the SwitchCompat source code
*/
class SwitchCompatTouchListener(private val v: SwitchCompat, private val lambda: (Boolean)->Unit) : View.OnTouchListener {
companion object {
private const val TOUCH_MODE_IDLE = 0
private const val TOUCH_MODE_DOWN = 1
private const val TOUCH_MODE_DRAGGING = 2
}
private val vc = ViewConfiguration.get(v.context)
private val mScaledTouchSlop = vc.scaledTouchSlop
private var mTouchMode = 0
private var mTouchX = 0f
private var mTouchY = 0f
/**
* @return true if (x, y) is within the target area of the switch thumb
* x,y and rect are in view coordinates, 0,0 is top left of the view
*/
private fun hitThumb(x: Float, y: Float): Boolean {
val rect = v.thumbDrawable.bounds
return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom
}
override fun onTouch(view: View, event: MotionEvent): Boolean {
if (view == v) {
when (MotionEventCompat.getActionMasked(event)) {
MotionEvent.ACTION_DOWN -> {
val x = event.x
val y = event.y
if (v.isEnabled && hitThumb(x, y)) {
mTouchMode = TOUCH_MODE_DOWN;
mTouchX = x;
mTouchY = y;
}
}
MotionEvent.ACTION_MOVE -> {
val x = event.x
val y = event.y
if (mTouchMode == TOUCH_MODE_DOWN &&
(abs(x - mTouchX) > mScaledTouchSlop || abs(y - mTouchY) > mScaledTouchSlop)
)
mTouchMode = TOUCH_MODE_DRAGGING;
}
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
if (mTouchMode == TOUCH_MODE_DRAGGING) {
val r = v.thumbDrawable.bounds
if (r.left + r.right < v.width) lambda(false)
else lambda(true)
} else lambda(!v.isChecked)
mTouchMode = TOUCH_MODE_IDLE;
}
}
}
return v.onTouchEvent(event)
}
}
How to use it:
the actual touch listener that accepts a lambda with the code to execute:
myswitch.setOnTouchListener(
SwitchCompatTouchListener(myswitch) {
// here goes all the code for your callback, in my case
// i called a service which, when successful, in turn would
// update my liveData
viewModel.sendCommandToMyService(it)
}
)
For the sake of completeness, this is how the observer for the state switchstate
(if you have it) looked like:
switchstate.observe(this, Observer {
myswitch.isChecked = it
})
It is amusing to return 418 I'm a teapot
to requests that are obviously crafted or malicious and "can't happen", such as failing CSRF check or missing request properties.
2.3.2 418 I'm a teapot
Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
To keep it reasonably serious, I restrict usage of funny error codes to RESTful endpoints that are not directly exposed to the user.
give the body of your iframe page an ID (or class if you wish)
<html>
<head></head>
<body id="myId">
</body>
</html>
then, also within the iframe's page, assign a background to that in CSS
#myId {
background-color: white;
}
*Windows only*
The clue is to arrange the entries in the path variable right.
As the NPM wiki tells us:
Because the installer puts C:\Program Files (x86)\nodejs before C:\Users<username>\AppData\Roaming\npm on your PATH, it will always use version of npm installed with node instead of the version of npm you installed using npm -g install npm@.
So your path variable will look something like:
C:\<path-to-node-installation>;%appdata%\npm;
Now you have to possibilities:
…;%appdata%\npm;C:\<path-to-node-installation>;…
This will load the npm version installed with npm (and not with node) and with it the installed Agnular CLI version.
…;C:\Users\<username>\AppData\Roaming\npm\node_modules\@angular\cli;C:\<path-to-node-installation>;%appdata%\npm;…
or
…;%appdata%\npm\node_modules\@angular\cli;C:\<path-to-node-installation>;%appdata%\npm;…
for the short form.
This worked for me since a while now.
Just something I found for Wordpress users,
As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.
So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.
Simple I know ^_^
According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/
function setMapOnAll(map1) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map1);
}
}
Next create another function to take away all these markers
function clearMarker(){
setMapOnAll(null);
}
Then create this final function to erase all the markers when ever this function is called upon.
function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to
}
Hope that helped good luck
make req.host/req.hostname effective must have two condition when Express behind proxies:
app.set('trust proxy', 'loopback');
in app.jsX-Forwarded-Host
header must specified by you own in webserver. eg. apache, nginxnginx:
server {
listen myhost:80;
server_name myhost;
location / {
root /path/to/myapp/public;
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://myapp:8080;
}
}
apache:
<VirtualHost myhost:80>
ServerName myhost
DocumentRoot /path/to/myapp/public
ProxyPass / http://myapp:8080/
ProxyPassReverse / http://myapp:8080/
</VirtualHost>
If the function is not defined when using that function in html, such as onclick = ‘function () ', it means function is in a callback, in my case is 'DOMContentLoaded'.
To get the post by George Howarth working properly with more than one replacement you need to remove the break, assign the output to a variable ($line) and then output the variable:
$lookupTable = @{
'something1' = 'something1aa'
'something2' = 'something2bb'
'something3' = 'something3cc'
'something4' = 'something4dd'
'something5' = 'something5dsf'
'something6' = 'something6dfsfds'
}
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
Get-Content -Path $original_file | ForEach-Object {
$line = $_
$lookupTable.GetEnumerator() | ForEach-Object {
if ($line -match $_.Key)
{
$line = $line -replace $_.Key, $_.Value
}
}
$line
} | Set-Content -Path $destination_file
var is not a member of inner class.
To access var, a pointer or reference to an outer class instance should be used. e.g. pOuter->var will work if the inner class is a friend of outer, or, var is public, if one follows C++ standard strictly.
Some compilers treat inner classes as the friend of the outer, but some may not. See this document for IBM compiler:
"A nested class is declared within the scope of another class. The name of a nested class is local to its enclosing class. Unless you use explicit pointers, references, or object names, declarations in a nested class can only use visible constructs, including type names, static members, and enumerators from the enclosing class and global variables.
Member functions of a nested class follow regular access rules and have no special access privileges to members of their enclosing classes. Member functions of the enclosing class have no special access to members of a nested class."
Per HTML syntax, and even HTML5, the following are all valid options:
<option value=""asd">test</option>
<option value=""asd">test</option>
<option value='"asd'>test</option>
<option value='"asd'>test</option>
<option value='"asd'>test</option>
<option value="asd>test</option>
<option value="asd>test</option>
Note that if you are using XML syntax the quotes (single or double) are required.
I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.
Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )
sqs = boto3.client('sqs')
s3 = boto3.resource('s3')
Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.
# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')
# you have two choices of create custom client session.
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')
Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.
import boto3
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket')
video_bucket = video_s3.Bucket('videobucket')
# just pass the instantiated bucket object
def list_bucket_contents(bucket):
for object in bucket.objects.all():
print(object.key)
list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)
Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.
For example, if you only deal with the default session, this looks similar to boto3.resource.
import boto3
s3 = boto3.client('s3')
def list_bucket_contents(bucket_name):
for object in s3.list_objects_v2(Bucket=bucket_name) :
print(object.key)
list_bucket_contents('Mybucket')
However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.
import boto3
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')
# you must pass boto3.Session.client and the bucket name
def list_bucket_contents(s3session, bucket_name):
response = s3session.list_objects_v2(Bucket=bucket_name)
if 'Contents' in response:
for obj in response['Contents']:
print(obj['key'])
list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket')
If you use $window.localStorage.setItem(key,value)
to store,$window.localStorage.getItem(key)
to retrieve and $window.localStorage.removeItem(key)
to remove, then you can access the values in any page.
You have to pass the $window
service to the controller. Though in JavaScript, window
object is available globally.
By using $window.localStorage.xxXX()
the user has control over the localStorage
value. The size of the data depends upon the browser. If you only use $localStorage
then value remains as long as you use window.location.href to navigate to other page and if you use <a href="location"></a>
to navigate to other page then your $localStorage
value is lost in the next page.
The compiler doesn't know that Environment.Exit() does not return. Why not just "return" from Main()?
I faced the same problem in eclipse with tomcat7 with the error javax.servlet cannot be resolved. If I select the server in targeted runtime mode and build project again, the error get's resolved.
To keep your current mysql settings and disable ONLY_FULL_GROUP_BY
I suggest to visit your phpmyadmin or whatever client you are using and type:
SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','') copy_me
next copy result to your my.ini
file.
mint: sudo nano /etc/mysql/my.cnf
ubuntu 16 and up: sudo nano /etc/mysql/my.cnf
ubuntu 14-16: /etc/mysql/mysql.conf.d/mysqld.cnf
copy_me
result can contain a long text which might be trimmed by default. Make sure you copy whole text!old answer:
If you want to disable permanently error "Expression #N of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db.table.COL' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by" do those steps:
sudo nano /etc/mysql/my.cnf
Add this to the end of the file
[mysqld]
sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
sudo service mysql restart
to restart MySQL
This will disable ONLY_FULL_GROUP_BY
for ALL users
Best way would be to declare Boolean
variable within the code block and return
it at end of code, like this:
public boolean Test(){
boolean booleanFlag= true;
if (A>B)
{booleanFlag= true;}
else
{booleanFlag = false;}
return booleanFlag;
}
I find this the best way.
Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.
You have to decide if:
If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)
If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:
If you give more details about your stack, it's easier to provide examples or resources.
EDIT: For client side JS highlighting you can try higlight.js, for instance.
try it.......i solve this problem using code:-
EditText inputArea;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputArea = (EditText) findViewById(R.id.inputArea);
//This line is you answer.Its unable your click ability in this Edit Text
//just write
inputArea.setInputType(0);
}
nothing u can input by default calculator on anything but u can set any string.
try it
Object.defineProperty(Array.prototype, "last", {_x000D_
get: function() {_x000D_
if (this[this.length -1] == undefined) { return [] }_x000D_
else { return this[this.length -1] }_x000D_
}_x000D_
});_x000D_
_x000D_
console.log([1,2,3,4].last) //returns 4
_x000D_
I needed a solution to this as well. I used leifg's solution and made it generic.
private <T> Set<T> findDuplicates(Collection<T> collection) {
Set<T> duplicates = new LinkedHashSet<>();
Set<T> uniques = new HashSet<>();
for(T t : collection) {
if(!uniques.add(t)) {
duplicates.add(t);
}
}
return duplicates;
}
simplified generic form,
int div_up(int n, int d) {
return n / d + (((n < 0) ^ (d > 0)) && (n % d));
} //i.e. +1 iff (not exact int && positive result)
For a more generic answer, C++ functions for integer division with well defined rounding strategy
Here's a simple single line alternative for users who don't have the watch
command who want to execute a command every 3 seconds:
while :; do your-command; sleep 3; done
It's an infinite loop that is basically the same as doing the following:
watch -n3 your-command
Chain
You can now use the chain
feature in packed
mode as describe in Eugene's answer.
Guideline
You can use a horizontal guideline at 50% position and add bottom and top (8dp) constraints to edittext and button:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<android.support.design.widget.TextInputLayout
android:id="@+id/client_id_input_layout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/guideline"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/login_client_id"
android:inputType="textEmailAddress"/>
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/authenticate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/login_auth"
app:layout_constraintTop_toTopOf="@+id/guideline"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"/>
<android.support.constraint.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
</android.support.constraint.ConstraintLayout>
In the context of Drupal, the difference will depend whether clean URLs are on or not.
With them off, $_SERVER['REQUEST_URI']
will have the full path of the page as called w/ /index.php
, while $_GET["q"]
will just have what is assigned to q
.
With them on, they will be nearly identical w/o other arguments, but $_GET["q"]
will be missing the leading /
. Take a look towards the end of the default .htaccess to see what is going on. They will also differ if additional arguments are passed into the page, eg when a pager is active.
I'm not an expert in JQuery but I have the same scenario and I able to accomplis like this:
$("#data tr").click(function(){
$(this).addClass("selected").siblings().removeClass("selected");
});
Style:
<style type="text/css">
.selected {
background: red;
}
</style>
While they are not the same thing, in one sense DISTINCT
implies a GROUP BY
, because every DISTINCT
could be re-written using GROUP BY
instead. With that in mind, it doesn't make sense to order by something that's not in the aggregate group.
For example, if you have a table like this:
col1 col2 ---- ---- 1 1 1 2 2 1 2 2 2 3 3 1
and then try to query it like this:
SELECT DISTINCT col1 FROM [table] WHERE col2 > 2 ORDER BY col1, col2
That would make no sense, because there could end up being multiple col2
values per row. Which one should it use for the order? Of course, in this query you know the results wouldn't be that way, but the database server can't know that in advance.
Now, your case is a little different. You included all the columns from the order by
clause in the select
clause, and therefore it would seem at first glance that they were all grouped. However, some of those columns were included in a calculated field. When you do that in combination with distinct, the distinct
directive can only be applied to the final results of the calculation: it doesn't know anything about the source of the calculation any more.
This means the server doesn't really know it can count on those columns any more. It knows that they were used, but it doesn't know if the calculation operation might cause an effect similar to my first simple example above.
So now you need to do something else to tell the server that the columns are okay to use for ordering. There are several ways to do that, but this approach should work okay:
SELECT rsc.RadioServiceCodeId,
rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg
ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN
(SELECT val FROM dbo.fnParseArray(@RadioServiceGroup,','))
OR @RadioServiceGroup IS NULL
GROUP BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
This is not directly answering your question at all, but simply providing an alternative. I've found in the many long Excel calculations most of the time waiting is having Excel update values on the screen. If this is the case, you could insert the following code at the front of your sub:
Application.ScreenUpdating = False
Application.EnableEvents = False
and put this as the end
Application.ScreenUpdating = True
Application.EnableEvents = True
I've found that this often speeds up whatever code I'm working with so much that having to alert the user to the progress is unnecessary. It's just an idea for you to try, and its effectiveness is pretty dependent on your sheet and calculations.
Your file needs to be located inside your www directory. For example, if you're using wamp server on Windows, j3evn.jpg should be located,
C:/wamp/www/img/j3evn.jpg
and you can access it in html via
<img class="sealImage" alt="Image of Seal" src="../img/j3evn.jpg">
Look for the www, public_html, or html folder belonging to your web server. Place all your files and resources inside that folder.
Hope this helps!
I am using below code for today and database date.
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20
According to the documentation, the first argument can be any of the following:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
Technically in C++, the strict aliasing rule is probably never applicable.
Note the definition of indirection (* operator):
The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points.
Also from the definition of glvalue
A glvalue is an expression whose evaluation determines the identity of an object, (...snip)
So in any well defined program trace, a glvalue refers to an object. So the so called strict aliasing rule doesn't apply, ever. This may not be what the designers wanted.
You can use the toolchain file mechanism of cmake for this purpose, see e.g. here. You write a toolchain file for each compiler containing the corresponding definitions. At config time, you run e.g
cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/clang-toolchain.cmake ..
and all the compiler information will be set during the project() call from the toolchain file. Though in the documentation is mentionend only in the context of cross-compiling, it works as well for different compilers on the same system.
Based on @ionden's answer, the call to the delegate could be simplified using null propagation since C# 6.0.
Your code would simply be:
class MyClass {
public event EventHandler MyEvent;
public void Method() {
MyEvent?.Invoke(this, EventArgs.Empty);
}
}
Use it like this:
MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();
These are GCC functions for the programmer to give a hint to the compiler about what the most likely branch condition will be in a given expression. This allows the compiler to build the branch instructions so that the most common case takes the fewest number of instructions to execute.
How the branch instructions are built are dependent upon the processor architecture.
Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.
In my case, I am using homestead.
cd ~/Homestead
and run composer install
.
I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop
David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop
OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop
Note that I'm purposefully putting the smallest item last in the list to make .index
as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).
'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).
if( x != null && x.equals("*BINGO*") {
then do something with x...
}
From http://developer.android.com/reference/android/app/Activity.html
public final void showDialog (int id) Added in API level 1
This method was deprecated in API level 13. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
Simple version of showDialog(int, Bundle) that does not take any arguments. Simply calls showDialog(int, Bundle) with null arguments.
Why
How to solve?
More
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
1 - You can set a timeout in your application :
var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite
It is in milliseconds.
2 - Also you can increase timeout value in httpruntime tag in web/app.config :
<configuration>
<system.web>
<httpRuntime executionTimeout="<<**seconds**>>" />
...
</system.web>
</configuration>
For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source
I think the code below
<item name="android:actionMenuTextAppearance">@style/MyActionBar.MenuTextStyle</item>
must be in MyAppTheme
section.
In my case I had a pem file which contained two certificates and an encrypted private key to be used in mutual SSL authentication. So my pem file looked like this:
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9
...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
Here is what I did:
Split the file into three separate files, so that each one contains just one entry, starting with "---BEGIN.." and ending with "---END.." lines. Lets assume we now have three files: cert1.pem cert2.pem and pkey.pem
Convert pkey.pem into DER format using openssl and the following syntax:
openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER
Note, that if the private key is encrypted you need to supply a password( obtain it from the supplier of the original pem file ) to convert to DER format, openssl will ask you for the password like this: "enter a pass phraze for pkey.pem: " If conversion is successful, you will get a new file called "pkey.der"
Create a new java key store and import the private key and the certificates:
String keypass = "password"; // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
// this section does not make much sense to me,
// but I will leave it intact as this is how it was in the original example I found on internet:
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore" ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ), keypass.toCharArray());
// end of section..
// read the key file from disk and create a PrivateKey
FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();
PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);
// read the certificates from the files and load them into the key store:
Collection col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));
Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };
String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();
ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);
// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );
// save the key store to a file
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());
(optional) Verify the content of your new key store:
keytool -list -keystore mykeystore -storepass password
Keystore type: JKS Keystore provider: SUN
Your keystore contains 3 entries
cn=...,ou=...,o=.., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 2C:B8: ...
importkey, Sep 2, 2014, PrivateKeyEntry, Certificate fingerprint (SHA1): 9C:B0: ...
cn=...,o=...., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83:63: ...
(optional) Test your certificates and private key from your new key store against your SSL server: ( You may want to enable debugging as an VM option: -Djavax.net.debug=all )
char[] passw = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
ks.load(new FileInputStream ( "mykeystore" ), passw );
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passw);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] tm = tmf.getTrustManagers();
SSLContext sclx = SSLContext.getInstance("TLS");
sclx.init( kmf.getKeyManagers(), tm, null);
SSLSocketFactory factory = sclx.getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
socket.startHandshake();
//if no exceptions are thrown in the startHandshake method, then everything is fine..
Finally register your certificates with HttpsURLConnection if plan to use it:
char[] passw = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
ks.load(new FileInputStream ( "mykeystore" ), passw );
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passw);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] tm = tmf.getTrustManagers();
SSLContext sclx = SSLContext.getInstance("TLS");
sclx.init( kmf.getKeyManagers(), tm, null);
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
{
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
HttpsURLConnection.setDefaultHostnameVerifier(hv);
only variable/object declaration statement are written outside of method
public class details{
public static void main(String arg[]){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
here is example try to learn java book and see the syntax then try to develop the program
Remove the required: true
rule.
Demo: Fiddle
jQuery('.validatedForm').validate({
rules : {
password : {
minlength : 5
},
password_confirm : {
minlength : 5,
equalTo : "#password"
}
}
Always use tax_query to get posts/products from a particular category or any other taxonomy. You can also get the products using ID/slug of particular taxonomy...
$the_query = new WP_Query( array(
'post_type' => 'product',
'tax_query' => array(
array (
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'accessories',
)
),
) );
while ( $the_query->have_posts() ) :
$the_query->the_post();
the_title(); echo "<br>";
endwhile;
wp_reset_postdata();
The first thing you need to understand is that when you pass something to a function, that something is copied to the function's arguments.
Suppose you have the following:
void swap1(int a, int b) {
int temp = a;
a = b;
b = temp;
assert(a == 17);
assert(b == 42);
// they're swapped!
}
int x = 42;
int y = 17;
swap1(x, y);
assert(x == 42);
assert(y == 17);
// no, they're not swapped!
The original variables will not be swapped, because their values are copied into the function's arguments. The function then proceeds to swap the values of those arguments, and then returns. The original values are not changed, because the function only swaps its own private copies.
Now how do we work around this? The function needs a way to refer to the original variables, not copies of their values. How can we refer to other variables in C? Using pointers.
If we pass pointers to our variables into the function, the function can swap the values in our variables, instead of its own argument copies.
void swap2(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
assert(*a == 17);
assert(*b == 42);
// they're swapped!
}
int x = 42;
int y = 17;
swap2(&x, &y); // give the function pointers to our variables
assert(x == 17);
assert(y == 42);
// yes, they're swapped!
Notice how inside the function we're not assigning to the pointers, but assigning to what they point to. And the pointers point to our variables x
and y
. The function is changing directly the values stored in our variables through the pointers we give it. And that's exactly what we needed.
Now what happens if we have two pointer variables and want to swap the pointers themselves (as opposed to the values they point to)? If we pass pointers, the pointers will simply be copied (not the values they point to) to the arguments.
void swap3(int* a, int* b) {
int* temp = a;
a = b;
b = temp;
assert(*a == 17);
assert(*b == 42);
// they're swapped!
}
void swap4(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
assert(*a == 17);
assert(*b == 42);
// they're swapped!
}
int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap3(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 42);
assert(y == 17);
// Didn't swap anything!
swap4(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 17);
assert(y == 42);
// Swapped the stored values instead!
The function swap3
only swaps its own private copies of our pointers that it gets in its arguments. It's the same issue we had with swap1
. And swap4
is changing the values our variables point to, not the pointers! We're giving the function a means to refer to the variables x
and y
but we want them to refer to xp
and yp
.
How do we do that? We pass it their addresses!
void swap5(int** a, int** b) {
int* temp = *a;
*a = *b;
*b = temp;
assert(**a == 17);
assert(**b == 42);
// they're swapped!
}
int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap5(&xp, &yp);
assert(xp == &y);
assert(yp == &x);
assert(x == 42);
assert(y == 17);
// swapped only the pointers variables
This way it swaps our pointer variables (notice how xp
now points to y
) but not the values they point to. We gave it a way to refer to our pointer variables, so it can change them!
By now it should be easy to understand how to swap two strings in the form of char*
variables. The swap function needs to receive pointers to char*
.
void swapStrings(char** a, char** b){
char *temp = *a;
*a = *b;
*b = temp;
assert(strcmp(*a, "world") == 0);
assert(strcmp(*b, "Hello") == 0);
}
char* x = "Hello";
char* y = "world";
swapStrings(&x, &y);
assert(strcmp(x, "world") == 0);
assert(strcmp(y, "Hello") == 0);
If it has something to do control updates on cached pages here I have a nice method how to do this.
www.yoursite.com/page/about?getVer=1&__[date]
This method requires at least one request even when no request is needed because it already exists in the local browser cache. But the overhead is less comparing to using no cache at all (to be sure the page will show the right updated content). This requires just a few bytes for each page request instead of all content for each page.
IMPORTANT: The version info request must be implemented on your server otherwise it will return the whole page.
Example of version string returned by www.yoursite.com/page/about?getVer=1&__[date]
:
skg2pl-v8kqb
To give you an example in code, here is a part of my library (I don't think you can use it but maybe it gives you some idea how to do it):
o.gCheckDocVersion = function() // Because of the hard caching method, check document for changes with ajax
{
var sUrl = o.getQuerylessUrl(window.location.href),
sDocVer = o.gGetData( sUrl, false );
o.ajaxRequest({ url:sUrl+'?getVer=1&'+o.uniqueId(), cache:0, dataType:'text' },
function(sVer)
{
if( typeof sVer == 'string' && sVer.length )
{
var bReload = (( typeof sDocVer == 'string' ) && sDocVer != sVer );
if( bReload || !sDocVer )
{
o.gSetData( sUrl, sVer );
sDocVer = o.gGetData( sUrl, false );
if( bReload && ( typeof sDocVer != 'string' || sDocVer != sVer ))
{ bReload = false; }
}
if( bReload )
{ // Hard refresh page contents
window.location.reload(true); }
}
}, false, false );
};
If you are using version independent resources like javascript or css files, add versionnumbers (implemented with a url rewrite and not with a query because they mostly won't be cached). For example: www.yoursite.com/ver-01/about.js
For me, this method is working great, maybe it can help you too.
It serves as padding.
A more complete answer is that a base64 encoded string doesn't always end with a =
, it will only end with one or two =
if they are required to pad the string out to the proper length.
Sample:
Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;
None is a special value in Python which usually designates an uninitialized variable. To test whether A does not have this particular value you use:
if A is not None
Falsey values are a special class of objects in Python (e.g. false, []). To test whether A is falsey use:
if not A
Thus, the two expressions are not the same And you'd better not treat them as synonyms.
P.S. None is also falsey, so the first expression implies the second. But the second covers other falsey values besides None. Now... if you can be sure that you can't have other falsey values besides None in A, then you can replace the first expression with the second.
read -n1
is not portable. A portable way to do the same might be:
( trap "stty $(stty -g;stty -icanon)" EXIT
LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
) </dev/tty
Besides using read
, for just a press ENTER
to continue prompt you could do:
sed -n q </dev/tty
to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;
Just go to rails console and type:
rails new YOURAPPNAME -d mysql
You can use 100vw / 100vh
. CSS3 gives us viewport-relative units. 100vw means 100% of the viewport width. 100vh; 100% of the height.
<div style="display:flex; justify-content: space-between;background-color: lightyellow; width:100%; height:85vh">
<div style="width:70%; height: 100%; border: 2px dashed red"></div>
<div style="width:30%; height: 100%; border: 2px dashed red"></div>
</div>
If you want to completely abuse the data.frame (as I do) and like to keep the $ functionality, one way is to split you data.frame into one-line data.frames gathered in a list :
> df = data.frame(x=c('a','b','c'), y=3:1)
> df
x y
1 a 3
2 b 2
3 c 1
# 'convert' into a list of data.frames
ldf = lapply(as.list(1:dim(df)[1]), function(x) df[x[1],])
> ldf
[[1]]
x y
1 a 3
[[2]]
x y
2 b 2
[[3]]
x y
3 c 1
# and the 'coolest'
> ldf[[2]]$y
[1] 2
It is not only intellectual masturbation, but allows to 'transform' the data.frame into a list of its lines, keeping the $ indexation which can be useful for further use with lapply (assuming the function you pass to lapply uses this $ indexation)
No there's not and developers still don't know why google doesn't pay attention to this request!
As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!
All Answers here seem to be outdated. Please use this now:
document.querySelector("[name='acc']");
document.querySelector("[name='pass']")
use this in style
body
{
overflow:hidden;
width:100%;
}
Use this in head tag
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
Instead of using a margin, could you use a border? You should do this with <div>
, anyway.
Something like this?
var xxxx : { [key:number]: MyType };
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?
, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
You can do it in one line -
df.groupby(['job']).apply(lambda x: x.sort_values(['count'], ascending=False).head(3)
.drop('job', axis=1))
what apply() does is that it takes each group of groupby and assigns it to the x in lambda function.
The problem with all these solutions is that the height of the iframe
never really changes.
This means you won't be able to center elements inside the iframe
using Javascript, position:fixed;
, or position:absolute;
since the iframe
itself never scrolls.
My solution detailed here is to wrap all the content of the iframe inside a div
using this CSS:
#wrap {
position: fixed;
top: 0;
right:0;
bottom:0;
left: 0;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
This way Safari believes the content has no height and lets you assign the height of the iframe
properly. This also allows you to position elements in any way you wish.
Try using list.AddRange(VTSWeb.GetDailyWorktimeViolations(VehicleID2));