Best and proper legal way to test Java private method from test framework is @VisibleForTesting annotation over the method so same method will be visible for test framework as like public method.
Use one of these as per your requirements.
Open the linked document in a new window or tab:
<a href="xyz.html" target="_blank"> Link </a>
Open the linked document in the same frame as it was clicked (this is default):
<a href="xyz.html" target="_self"> Link </a>
Open the linked document in the parent frame:
<a href="xyz.html" target="_parent"> Link </a>
Open the linked document in the full body of the window:
<a href="xyz.html" target="_top"> Link </a>
Open the linked document in a named frame:
<a href="xyz.html" target="framename"> Link </a>
The following signature will do:
List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);
Spring Data JPA supports a large number of keywords to build a query. IN
and AND
are among them.
In Expression Language you can just use the ==
or eq
operator to compare object values. Behind the scenes they will actually use the Object#equals()
. This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).
So the particular line
<c:when test="${lang}.equals(${pageLang})">
should be written as (note that the whole expression is inside the {
and }
)
<c:when test="${lang == pageLang}">
or, equivalently
<c:when test="${lang eq pageLang}">
Both are behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))
If you want to compare constant String
values, then you need to quote it
<c:when test="${lang == 'en'}">
or, equivalently
<c:when test="${lang eq 'en'}">
which is behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals("en")
I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear:
And trying to move a not-too-long basename to a too-long-pathname is also very clear:
The pathname error is deceptive, though. Quite unhelpful:
This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.
I solved this problem by going to folder .vagrant.d/boxes/
under your home and changed name of the folder from laravel-VAGRANTSLASH-homestead
to base
.
And it worked for me.
Please check if virtualization is enabled in your BIOS.
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
make sure that you insert your module and controller in your index.html first.
then use this code in your module var app = angular.module("MesaViewer", []);
Agree it is probably due to a problem in resources that is preventing build of R.Java in gen. In my case a cut n paste had given a duplicate app name in string. Sort the fault, delete gen directory and clean.
Maybe one of the easiest solutions would be to use the x
descriptor of the srcset
attribute as such:
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />
<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />
<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
Currently supported by all browsers except IE. (caniuse)
For me, setting the uploadReadAheadSize
to int.MaxValue also fixed the problem, after also increasing the limits on the WCF binding.
It seems that, when using SSL, the entire request entity body is preloaded, for which this metabase property is used.
For more info, see:
The page was not displayed because the request entity is too large. iis7
Why not keep track of the state of through a class without CSS rules on the clickable anchor itself
$(function() {
$("#show-background").click(function () {
$("#content-area").animate({opacity: 'toggle'}, 'slow');
$("#show-background").toggleClass("clicked");
if ( $("#show-background").hasClass("clicked") ) {
$(this).text("Show Text");
}
else {
$(this).text("Show Background");
}
});
});
I got same issue on Catalina mac. I also installed the R from the source in following diretory. ./Documents/R-4.0.3
Now from the terminal type
ls -a
and open
vim .bash_profile
type
export LANG="en_US.UTF-8"
save with :wq
then type
source .bash_profile
and then open
./Documents/R-4.0.3/bin/R
./Documents/R-4.0.3/bin/Rscript
I always have to run "source /Users/yourComputerName/.bash_profile" before running R scripts.
Where specific formatting is required, you should write your own routine or use a library function that does what you need. The basic ECMAScript functionality is usually insufficient for displaying formatted numbers.
A thorough explanation of rounding and formatting is here: http://www.merlyn.demon.co.uk/js-round.htm#RiJ
As a general rule, rounding and formatting should only be peformed as a last step before output. Doing so earlier may introduce unexpectedly large errors and destroy the formatting.
Most database servers have a COALESCE function, which will return the first argument that is non-null, so the following should do what you want:
SELECT COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
Since there seems to be a lot of discussion about
COALESCE/ISNULL will still return NULL if no rows match, try this query you can copy-and-paste into SQL Server directly as-is:
SELECT coalesce(SUM(column_id),0) AS TotalPrice
FROM sys.columns
WHERE (object_id BETWEEN -1 AND -2)
Note that the where clause excludes all the rows from sys.columns from consideration, but the 'sum' operator still results in a single row being returned that is null, which coalesce fixes to be a single row with a 0.
can you try
<p:column width="20">
I originally used Plantface's answer, but I didn't like how the syntax looked in my view.
I reworked it to use $q.defer to post-process the data and return a list on unique teams, which is then uses as the filter.
http://plnkr.co/edit/waWv1donzEMdsNMlMHBa?p=preview
<ul>
<li ng-repeat="team in teams">{{team}}
<ul>
<li ng-repeat="player in players | filter: {team: team}">{{player.name}}</li>
</ul>
</li>
</ul>
app.controller('MainCtrl', function($scope, $q) {
$scope.players = []; // omitted from SO for brevity
// create a deferred object to be resolved later
var teamsDeferred = $q.defer();
// return a promise. The promise says, "I promise that I'll give you your
// data as soon as I have it (which is when I am resolved)".
$scope.teams = teamsDeferred.promise;
// create a list of unique teams. unique() definition omitted from SO for brevity
var uniqueTeams = unique($scope.players, 'team');
// resolve the deferred object with the unique teams
// this will trigger an update on the view
teamsDeferred.resolve(uniqueTeams);
});
The date filter always formats the dates using the local timezone. You'll have to write your own filter, based on the getUTCXxx()
methods of Date
, or on a library like moment.js.
If you start tomcat from startup.bat, you need to add a system variable :JAVA_OPTS as name and the parameters that you wants (in your case :
-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:
import pylab
datalist = [ ( pylab.loadtxt(filename), label ) for filename, label in list_of_files ]
for data, label in datalist:
pylab.plot( data[:,0], data[:,1], label=label )
pylab.legend()
pylab.title("Title of Plot")
pylab.xlabel("X Axis Label")
pylab.ylabel("Y Axis Label")
You also might want to add something like fmt='o' to the plot command, in order to change from a line to points. By default, matplotlib with pylab plots onto the same figure without clearing it, so you can just run the plot command multiple times.
EDIT 7/1/15:
I wrote this answer a pretty long time ago and haven't been keeping up a lot with angular for a while, but it seems as though this answer is still relatively popular, so I wanted to point out that a couple of the point @nicolas makes below are good. For one, injecting $rootScope and attaching the helpers there will keep you from having to add them for every controller. Also - I agree that if what you're adding should be thought of as Angular services OR filters, they should be adopted into the code in that manner.
Also, as of the current version 1.4.2, Angular exposes a "Provider" API, which is allowed to be injected into config blocks. See these resources for more:
https://docs.angularjs.org/guide/module#module-loading-dependencies
AngularJS dependency injection of value inside of module.config
I don't think I'm going to update the actual code blocks below, because I'm not really actively using Angular these days and I don't really want to hazard a new answer without feeling comfortable that it's actually conforming to new best practices. If someone else feels up to it, by all means go for it.
EDIT 2/3/14:
After thinking about this and reading some of the other answers, I actually think I prefer a variation of the method brought up by @Brent Washburne and @Amogh Talpallikar. Especially if you're looking for utilities like isNotString() or similar. One of the clear advantages here is that you can re-use them outside of your angular code and you can use them inside of your config function (which you can't do with services).
That being said, if you're looking for a generic way to re-use what should properly be services, the old answer I think is still a good one.
What I would do now is:
app.js:
var MyNamespace = MyNamespace || {};
MyNamespace.helpers = {
isNotString: function(str) {
return (typeof str !== "string");
}
};
angular.module('app', ['app.controllers', 'app.services']).
config(['$routeProvider', function($routeProvider) {
// Routing stuff here...
}]);
controller.js:
angular.module('app.controllers', []).
controller('firstCtrl', ['$scope', function($scope) {
$scope.helpers = MyNamespace.helpers;
});
Then in your partial you can use:
<button data-ng-click="console.log(helpers.isNotString('this is a string'))">Log String Test</button>
Old answer below:
It might be best to include them as a service. If you're going to re-use them across multiple controllers, including them as a service will keep you from having to repeat code.
If you'd like to use the service functions in your html partial, then you should add them to that controller's scope:
$scope.doSomething = ServiceName.functionName;
Then in your partial you can use:
<button data-ng-click="doSomething()">Do Something</button>
Here's a way you might keep this all organized and free from too much hassle:
Separate your controller, service and routing code/config into three files: controllers.js, services.js, and app.js. The top layer module is "app", which has app.controllers and app.services as dependencies. Then app.controllers and app.services can be declared as modules in their own files. This organizational structure is just taken from Angular Seed:
app.js:
angular.module('app', ['app.controllers', 'app.services']).
config(['$routeProvider', function($routeProvider) {
// Routing stuff here...
}]);
services.js:
/* Generic Services */
angular.module('app.services', [])
.factory("genericServices", function() {
return {
doSomething: function() {
//Do something here
},
doSomethingElse: function() {
//Do something else here
}
});
controller.js:
angular.module('app.controllers', []).
controller('firstCtrl', ['$scope', 'genericServices', function($scope, genericServices) {
$scope.genericServices = genericServices;
});
Then in your partial you can use:
<button data-ng-click="genericServices.doSomething()">Do Something</button>
<button data-ng-click="genericServices.doSomethingElse()">Do Something Else</button>
That way you only add one line of code to each controller and are able to access any of the services functions wherever that scope is accessible.
I was having a similar problem. I was not using the ACL stuff, so I didn't need s3:PutObjectAcl
.
In my case, I was doing (in Serverless Framework YML):
- Effect: Allow
Action:
- s3:PutObject
Resource: "arn:aws:s3:::MyBucketName"
Instead of:
- Effect: Allow
Action:
- s3:PutObject
Resource: "arn:aws:s3:::MyBucketName/*"
Which adds a /*
to the end of the bucket ARN.
Hope this helps.
Very easy to do it ,
Write it at your controller
$this->validate($request,[
'email'=>['required',Rule::unique('yourTableName')->ignore($request->id)]
]);
Note : Rule::unique('yourTableName')->ignore($idParameter) , here $idParameter you can receive from get url also you can get it from hidden field.
Most important is don't forget to import Rule at the top.
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9
Just because java's implementation of Cloneable is broken it doesn't mean you can't create one of your own.
If OP real purpose was to create a deep clone, i think that it is possible to create an interface like this:
public interface Cloneable<T> {
public T getClone();
}
then use the prototype constructor mentioned before to implement it:
public class AClass implements Cloneable<AClass> {
private int value;
public AClass(int value) {
this.vaue = value;
}
protected AClass(AClass p) {
this(p.getValue());
}
public int getValue() {
return value;
}
public AClass getClone() {
return new AClass(this);
}
}
and another class with an AClass object field:
public class BClass implements Cloneable<BClass> {
private int value;
private AClass a;
public BClass(int value, AClass a) {
this.value = value;
this.a = a;
}
protected BClass(BClass p) {
this(p.getValue(), p.getA().getClone());
}
public int getValue() {
return value;
}
public AClass getA() {
return a;
}
public BClass getClone() {
return new BClass(this);
}
}
In this way you can easely deep clone an object of class BClass without need for @SuppressWarnings or other gimmicky code.
Using explode and implode function we can improvise a solution :
$array = array('lastname', 'email', 'phone');
define('DEFAULT_ROLES', implode (',' , $array));
echo explode(',' ,DEFAULT_ROLES ) [1];
This will echo email
.
If you want it to optimize it more you can define 2 functions to do the repetitive things for you like this :
//function to define constant
function custom_define ($const , $array) {
define($const, implode (',' , $array));
}
//function to access constant
function return_by_index ($index,$const = DEFAULT_ROLES) {
$explodedResult = explode(',' ,$const ) [$index];
if (isset ($explodedResult))
return explode(',' ,$const ) [$index] ;
}
Hope that helps . Happy coding .
You could add
cd /some/directory/somewhere/named/Foo
to your .bashrc
file (or .profile
or whatever you call it) at the other host. That way, no matter what you do or where you ssh
from, whenever you log onto that server, it will cd
to the proper directory for you, and all you have to do is use ssh
like normal.
Of curse, rogeriopvl's solution works too, but it's a tad bit more verbose, and you have to remember to do it every time (unless you make an alias) so it seems a bit less "fun".
If the container has already exited (maybe due to some error), you can do
$ docker run --rm -it --entrypoint /bin/ash image_name
or
$ docker run --rm -it --entrypoint /bin/sh image_name
or
$ docker run --rm -it --entrypoint /bin/bash image_name
to create a new container and get a shell into it. Since you specified --rm, the container would be deleted when you exit the shell.
Sets require their items to be hashable. Out of types predefined by Python only the immutable ones, such as strings, numbers, and tuples, are hashable. Mutable types, such as lists and dicts, are not hashable because a change of their contents would change the hash and break the lookup code.
Since you're sorting the list anyway, just place the duplicate removal after the list is already sorted. This is easy to implement, doesn't increase algorithmic complexity of the operation, and doesn't require changing sublists to tuples:
def uniq(lst):
last = object()
for item in lst:
if item == last:
continue
yield item
last = item
def sort_and_deduplicate(l):
return list(uniq(sorted(l, reverse=True)))
CSS transformations create a new stacking context and containing block, as described in the spec. In plain English, this means that fixed position elements with a transformation applied to them will act more like absolutely positioned elements, and z-index
values are likely to get screwed with.
If you take a look at this demo, you'll see what I mean. The second div has a transformation applied to it, meaning that it creates a new stacking context, and the pseudo elements are stacked on top rather than below.
So basically, don't do that. Apply a 3D transformation only when you need the optimization. -webkit-font-smoothing: antialiased;
is another way to tap into 3D acceleration without creating these problems, but it only works in Safari.
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
model.fit(train_x, train_y,validation_split = 0.1, epochs=50, batch_size=4)
y_pred=model.predict(test_x,batch_size=15)
cm =confusion_matrix(test_y.argmax(axis=1), y_pred.argmax(axis=1))
index = ['neutral','happy','sad']
columns = ['neutral','happy','sad']
cm_df = pd.DataFrame(cm,columns,index)
plt.figure(figsize=(10,6))
sns.heatmap(cm_df, annot=True)
Looking at the source code I also think there must be some issue with the private key.
What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.
If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.
(see source code from class SecureChannnel, method EnsurePrivateKey)
So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.
You can activate Network Tracing to try to debug this. It will give you output like this:
Based on the answer of Mark Byers, my python implementation:
def permutations(string):
if len(string) == 1:
return [string]
permutations=[]
for i in range(len(string)):
for perm in permutations(string[:i]+string[i+1:]):
permutations.append(string[i] + perm)
return permutations
There is a good stackoverflow answer here by Mark Rajcok:
AngularJS directive controllers requiring parent directive controllers?
with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/
<div ng-controller="MyCtrl">
<div screen>
<div component>
<div widget>
<button ng-click="widgetIt()">Woo Hoo</button>
</div>
</div>
</div>
</div>
JavaScript
var myApp = angular.module('myApp',[])
.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomethingScreeny = function() {
alert("screeny!");
}
}
}
})
.directive('component', function() {
return {
scope: true,
require: '^screen',
controller: function($scope) {
this.componentFunction = function() {
$scope.screenCtrl.doSomethingScreeny();
}
},
link: function(scope, element, attrs, screenCtrl) {
scope.screenCtrl = screenCtrl
}
}
})
.directive('widget', function() {
return {
scope: true,
require: "^component",
link: function(scope, element, attrs, componentCtrl) {
scope.widgetIt = function() {
componentCtrl.componentFunction();
};
}
}
})
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects
I faced the same Maven connection timeout issue and resolved by disabling/whitelisting the anti-virus & firewall setting.
The issue got resolved immediately:
org.apache.maven.wagon.providers.http.httpclient.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239)
it seems that the ubuntu community has completed the documentation on installing openCV,
so all you have to do now is to download the installation script from here and execute it.
don't forget to make it executable:
chmod +x opencv_latest.sh
then
./opencv_latest.sh
You need to escape the ampersand:
<div class="test">&times</div>
×
means a multiplication sign. (Technically it should be ×
but lenient browsers let you omit the ;
.)
Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/
Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.
@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront
. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.
Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.
You need to add this value to the form data that is submitted to the server. You can use
<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">
inside your form tag.
I just had the same issue and this helped me:
html {
height: auto;
min-height: 100%;
background-size:cover;
}
Surely:
if (useAdditionalClauses)
{
results =
results.Where(o => o.OrderStatus == OrderStatus.Open &&
o.CustomerID == customerID)
}
Or just another .Where()
call like this one (although I don't know why you would want to, unless it's split by another boolean control variable):
if (useAdditionalClauses)
{
results = results.Where(o => o.OrderStatus == OrderStatus.Open).
Where(o => o.CustomerID == customerID);
}
Or another reassignment to results
: `results = results.Where(blah).
Simply use a class literal, i.e. NameOfClass.class
This project on github may be your solution
Define the float property of the check element to none:
float: none;
And center the parent element:
text-align: center;
It was the only that works for me.
Didn't see the answer that worked for me, so here it is: On my OSX system I found yarn at ~/.yarn/bin/yarn
. rm -rf ~/.yarn
took care of it.
...
WHERE ...
AND (@Location is null OR (Location like '%' + @Location + '%'))
AND (@Date is null OR (Date = @Date))
This way it is more obvious the parameter is not used when null.
$str = trim(preg_replace('/\s+/',' ', $str));
The above line of code will remove extra spaces, as well as leading and trailing spaces.
I know you said you didn't want to read the file in by hand, but this is pretty easy
public class FooTest
{
private BufferedReader in = null;
@Before
public void setup()
throws IOException
{
in = new BufferedReader(
new InputStreamReader(getClass().getResourceAsStream("/data.txt")));
}
@After
public void teardown()
throws IOException
{
if (in != null)
{
in.close();
}
in = null;
}
@Test
public void testFoo()
throws IOException
{
String line = in.readLine();
assertThat(line, notNullValue());
}
}
All you have to do is ensure the file in question is in the classpath. If you're using Maven, just put the file in src/test/resources and Maven will include it in the classpath when running your tests. If you need to do this sort of thing a lot, you could put the code that opens the file in a superclass and have your tests inherit from that.
In the case where you don't know the locale of the string value received and it is not necessarily the same locale as the current default locale you can use this :
private static double parseDouble(String price){
String parsedStringDouble;
if (price.contains(",") && price.contains(".")){
int indexOfComma = price.indexOf(",");
int indexOfDot = price.indexOf(".");
String beforeDigitSeparator;
String afterDigitSeparator;
if (indexOfComma < indexOfDot){
String[] splittedNumber = price.split("\\.");
beforeDigitSeparator = splittedNumber[0];
afterDigitSeparator = splittedNumber[1];
}
else {
String[] splittedNumber = price.split(",");
beforeDigitSeparator = splittedNumber[0];
afterDigitSeparator = splittedNumber[1];
}
beforeDigitSeparator = beforeDigitSeparator.replace(",", "").replace(".", "");
parsedStringDouble = beforeDigitSeparator+"."+afterDigitSeparator;
}
else {
parsedStringDouble = price.replace(",", "");
}
return Double.parseDouble(parsedStringDouble);
}
It will return a double no matter what the locale of the string is. And no matter how many commas or points there are. So passing 1,000,000.54
will work so will 1.000.000,54
so you don't have to rely on the default locale for parsing the string anymore. The code isn't as optimized as it can be so any suggestions are welcome. I tried to test most of the cases to make sure it solves the problem but I am not sure it covers all. If you find a breaking value let me know.
In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.
I'd like to share my steps which is a bit different to what offered by rynop and superluminary.
A
Record is exactly the same but CNAME
for www
I would prefer to redirect it to my blank domain (non-www
)This configuration is referring to guidance of preferred domain. The domain setting of www
to non www
or vise versa can be different on each of the domain providers. Since my domain is under GoDaddy, so under the Domain Setting I set it using the Subdomain Forwarding (301).
As the result of pointing the domain to Github repository, it will then give all the URLs for both of master
and gh-pages
branch similar like the ones I listed below goes to the preferred domain:
master
By creating CNAME
file on master
branch (check it on my user repository).
http://hyipworld.github.io/
http://www.hyip.world/
http://hyip.world/
gh-pages
By creating the same CNAME
file on gh-pages
branch (check it on my project repository).
http://hyipworld.github.io/maps/
http://www.hyip.world/maps/
http://hyip.world/maps/
As addition to the CNAME
file above, you may need to completely bypass Jekyll processing on GitHub Pages by creating a file named .nojekyll
in the root of your pages repo.
Workaround....
In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.
Try this
declare @v varchar(20)
set @v = 'Number'
select case when isnumeric(@v) = 1 then @v
else @v end
and
declare @v varchar(20)
set @v = '7082.7758172'
select case when isnumeric(@v) = 1 then @v
else convert(numeric(18,0),@v) end
You can do this by creating a constraint and connecting it via interface builder
See explanation: Auto_Layout_Constraints_in_Interface_Builder
raywenderlich beginning-auto-layout
AutolayoutPG Articles constraint Fundamentals
@interface ViewController : UIViewController {
IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
IBOutlet NSLayoutConstraint *topSpaceConstraint;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
connect this Constraint outlet with your sub views Constraint or connect super views Constraint too and set it according to your requirements like this
self.leadingSpaceConstraint.constant = 10.0;//whatever you want to assign
I hope this clarifies it.
A rather different way to solve this:
li = [0,1,2,3]
for i in range(len(li)):
if i < len(li)-1:
# until end is reached
print 'this', li[i]
print 'next', li[i+1]
else:
# end
print 'this', li[i]
I had tried:
string[] sample = new string[0];
But I could only insert one string into it, and then I got an exceptionOutOfBound error, so I just simply put a size for it, like
string[] sample = new string[100];
Or another way that work for me:
List<string> sample = new List<string>();
Assigning Value for list:
sample.Add(your input);
There are two ways I usually do this, both use ssh:
scp -r sourcedir/ [email protected]:/dest/dir/
or, the more robust and faster (in terms of transfer speed) method:
rsync -auv -e ssh --progress sourcedir/ [email protected]:/dest/dir/
Read the man pages for each command if you want more details about how they work.
jQuery provides event hooks for when AJAX requests start and end. You can hook into these to show your loader.
For example, create the following div:
<div id="spinner">
<img src="images/spinner.gif" alt="Loading" />
</div>
Set it to display: none
in your stylesheets. You can style it whatever way you want to. You can generate a nice loading image at Ajaxload.info, if you want to.
Then, you can use something like the following to make it be shown automatically when sending Ajax requests:
$(document).ready(function () {
$('#spinner').bind("ajaxSend", function() {
$(this).show();
}).bind("ajaxComplete", function() {
$(this).hide();
});
});
Simply add this Javascript block to the end of your page before closing your body tag or wherever you see fit.
Now, whenever you send Ajax requests, the #spinner
div will be shown. When the request is complete, it'll be hidden again.
push is a native javascript method. You could use it like this:
var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]
Have you googled about it - insert update delete access vb.net, there are lots of reference about this.
Insert Update Delete Navigation & Searching In Access Database Using VB.NET
what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB
is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.
it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:
Example code snippet:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class DBUtil
Private connectionString As String
Public Sub New()
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=d:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
End Sub
Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Public SubUpdateCategories(ByVal name As String)
Dim query As String = "update Categories set name = 'new2' where name = ?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
Return FillDataSet(cmd, "Categories")
End Sub
Public Function GetItems() As DataSet
Dim query As String = "SELECT * FROM Items"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Items")
End Function
Public Function GetItems(ByVal categoryID As Integer) As DataSet
'Create the command.
Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("category_ID", categoryID)
'Fill the dataset.
Return FillDataSet(cmd, "Items")
End Function
Public Sub AddCategory(ByVal name As String)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Categories "
insertSQL &= "VALUES(?)"
Dim cmd As New OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Name", name)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Public Sub AddItem(ByVal title As String, ByVal description As String, _
ByVal price As Decimal, ByVal categoryID As Integer)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Items "
insertSQL &= "(Title, Description, Price, Category_ID)"
insertSQL &= "VALUES (?, ?, ?, ?)"
Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Title", title)
cmd.Parameters.AddWithValue("Description", description)
cmd.Parameters.AddWithValue("Price", price)
cmd.Parameters.AddWithValue("CategoryID", categoryID)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=D:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
con.ConnectionString = connectionString
cmd.Connection = con
Dim adapter As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
Try
con.Open()
adapter.Fill(ds, tableName)
Finally
con.Close()
End Try
Return ds
End Function
End Class
Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back
With new pandas version, it is easy to get as dataframe
unique_count = pd.groupby(['YEARMONTH'], as_index=False).agg(uniq_CLIENTCODE =('CLIENTCODE',pd.Series.count))
As long as the column is not a unique identifier
UPDATE table set columnName = 0 where columnName is null
Then
Alter the table and set the field to non null and specify a default value of 0
I see this issue come up a lot. Yes, Tomcat 7 does automatically deregister it, but it that REALLY taking control of your code and a good coding practice? Surely YOU want to know that you have all the correct code in place to close all your objects, shut down database connection pool threads, and get rid of all warnings. I certainly do.
This is how I do it.
Step 1: Register a Listener
web.xml
<listener>
<listener-class>com.mysite.MySpecialListener</listener-class>
</listener>
Step 2: Implement the Listener
com.mysite.MySpecialListener.java
public class MySpecialListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// On Application Startup, please…
// Usually I'll make a singleton in here, set up my pool, etc.
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// On Application Shutdown, please…
// 1. Go fetch that DataSource
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource datasource = (DataSource)envContext.lookup("jdbc/database");
// 2. Deregister Driver
try {
java.sql.Driver mySqlDriver = DriverManager.getDriver("jdbc:mysql://localhost:3306/");
DriverManager.deregisterDriver(mySqlDriver);
} catch (SQLException ex) {
logger.info("Could not deregister driver:".concat(ex.getMessage()));
}
// 3. For added safety, remove the reference to dataSource for GC to enjoy.
dataSource = null;
}
}
Please feel free to comment and/or add...
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
Visually you can open "SQL Server Configuration Manager" and check properties of "Network Configuration":
Here i have updated for swift 3
applicationFrame deprecated from iOS 9
In swift three they have removed () and they have changed few naming convention, you can refer here Link
func windowHeight() -> CGFloat {
return UIScreen.main.bounds.size.height
}
func windowWidth() -> CGFloat {
return UIScreen.main.bounds.size.width
}
Settings (Ctrl+Alt+s)--> Apprarance-->Override default fonts by(not recommended):
then change Size to 16+.
There is also th:classappend
.
<a href="" class="baseclass" th:classappend="${isAdmin} ? adminclass : userclass"></a>
If isAdmin
is true
, then this will result in:
<a href="" class="baseclass adminclass"></a>
One notable difference is that if you pass a .c
file to gcc it will compile as C.
The default behavior of g++ is to treat .c
files as C++ (unless -x c
is specified).
In this case you need to go up to the <tr>
then use .next()
, like this:
$(obj).closest('tr').next().find('.class');
Or if there may be rows in-between without the .class
inside, you can use .nextAll()
, like this:
$(obj).closest('tr').nextAll(':has(.class):first').find('.class');
Is it proper to "reach into" an object and use its dict property?
In general, I would say "no". However Namespace
has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.
On the other hand, Namespace
does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__
, but the limits of my imagination are not the same as yours.
We can add ng-click event conditionally without using disabled class.
HTML:
<div ng-repeat="object in objects">
<span ng-click="!object.status && disableIt(object)">{{object.value}}</span>
</div>
NOTE: This changed in Jenkins 1.597, Please see here for more info regarding the migration
You should be able to view all the global environment variables that are available during the build by navigating to https://<your-jenkins>/env-vars.html
.
Replace https://<your-jenkins>/
with the URL you use to get to Jenkins webpage (for example, it could be http://localhost:8080/env-vars.html
).
One of the environment variables is :
BUILD_ID
The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss)
If you use jenkins editable email notification, you should be able to use ${ENV, var="BUILD_ID"}
in the subject line of your email.
If you just want the last character or any character at know position you can simply trat string as an array! - strings are iteratorable in javascript -
Var x = "hello_world";
x[0]; //h
x[x.length-1]; //d
Yet if you need more than just one character then use splice is effective
x.slice(-5); //world
Regarding your example
"rating_element-<?php echo $id?>"
To extract id you can easily use split + pop
Id= inputId.split('rating_element-')[1];
This will return the id, or undefined if no id was after 'rating_element' :)
Extending Alex's answer slightly:
class User:
def __init__(self):
self.data = [1,2,3]
self.other_data = [4,5,6]
def doSomething(self, source):
dataSource = getattr(self,source)
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
will yield:
[1, 2, 3] [4, 5, 6]
However, personally I don't think that's great style - getattr
will let you access any attribute of the instance, including things like the doSomething
method itself, or even the __dict__
of the instance. I would suggest that instead you implement a dictionary of data sources, like so:
class User:
def __init__(self):
self.data_sources = {
"data": [1,2,3],
"other_data":[4,5,6],
}
def doSomething(self, source):
dataSource = self.data_sources[source]
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
again yielding:
[1, 2, 3] [4, 5, 6]
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);
var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);
This code worked for me.
No need to take any javscript or any method you can just do it with your html css
HTML
<select id="myAwesomeSelect">
<option selected="selected" class="s">Country Name</option>
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
Css
.s
{
color:white;
font-size:0px;
display:none;
}
A better option is to add the constraints directly during CREATE TABLE query (assuming you have the information about the tables)
CREATE TABLE products(
productId INT AUTO_INCREMENT PRIMARY KEY,
productName varchar(100) not null,
categoryId INT NOT NULL,
CONSTRAINT fk_category
FOREIGN KEY (categoryId)
REFERENCES categories(categoryId)
ON UPDATE CASCADE
ON DELETE CASCADE
) ENGINE=INNODB;
I have encounterd the same issue, but I find a anwser showing below.
web.xml
<!-- set this param value for the filter-->
<init-param>
<param-name>freePages</param-name>
<param-value>
MainFrame.jsp;
</param-value>
</init-param>
filter.java
strFreePages = config.getInitParameter("freePages"); //get the exclue pattern from config file
isFreePage(strRequestPage) //decide the exclude path
this way you don't have to harass the concrete Filter class.
If you are using C++11
, you should probably use stoi
because it can distinguish between an error and parsing "0"
.
try {
int number = std::stoi("1234abc");
} catch (std::exception const &e) {
// This could not be parsed into a number so an exception is thrown.
// atoi() would return 0, which is less helpful if it could be a valid value.
}
It should be noted that "1234abc" is implicitly converted from a char[]
to a std:string
before being passed to stoi()
.
The following function comes in three forms:
method = "mode" [default]: calculates the mode for a unimodal vector, else returns an NA
method = "nmodes": calculates the number of modes in the vector
method = "modes": lists all the modes for a unimodal or polymodal vector
modeav <- function (x, method = "mode", na.rm = FALSE)
{
x <- unlist(x)
if (na.rm)
x <- x[!is.na(x)]
u <- unique(x)
n <- length(u)
#get frequencies of each of the unique values in the vector
frequencies <- rep(0, n)
for (i in seq_len(n)) {
if (is.na(u[i])) {
frequencies[i] <- sum(is.na(x))
}
else {
frequencies[i] <- sum(x == u[i], na.rm = TRUE)
}
}
#mode if a unimodal vector, else NA
if (method == "mode" | is.na(method) | method == "")
{return(ifelse(length(frequencies[frequencies==max(frequencies)])>1,NA,u[which.max(frequencies)]))}
#number of modes
if(method == "nmode" | method == "nmodes")
{return(length(frequencies[frequencies==max(frequencies)]))}
#list of all modes
if (method == "modes" | method == "modevalues")
{return(u[which(frequencies==max(frequencies), arr.ind = FALSE, useNames = FALSE)])}
#error trap the method
warning("Warning: method not recognised. Valid methods are 'mode' [default], 'nmodes' and 'modes'")
return()
}
Use <location>
configuration tag, and <allow users="?"/>
to allow anonymous only or <allow users="*"/>
for all:
<configuration>
<location path="Path/To/Public/Folder">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
Here is some code that might help you out. Strings can be treated as an array of characters
string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
//Start of Code
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot snapshot){
GenericTypeIndicator<List<YourClassName>> t = new GenericTypeIndicator<List<YourClassName>>{};
List<YourClassName> messages = snapshot.getValue(t);
Log.d("Get Data Size", messages.size());
}
}
@Override
public void onCancelled(FirebaseError firebaseError){
Log.e("The read failed: ",firebaseError.getMessage());
}
});
If you use the gson.JsonObject you can have something like that:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)
Make sure you concatenate the multiple emails with ',' instead of ';'
Trunk : After the completion of every sprint in agile we come out with a partially shippable product. These releases are kept in trunk.
Branches : All parallel developments codes for each ongoing sprint are kept in branches.
Tags : Every time we release a partially shippable product kind of beta version, we make a tag for it. This gives us the code that was available at that point of time, allowing us to go back at that state if required at some point during development.
Instead of using a sheet name, in case you don't know or can't open the excel file to check in ubuntu (in my case, Python 3.6.7, ubuntu 18.04), I use the parameter index_col (index_col=0 for the first sheet)
import pandas as pd
file_name = 'some_data_file.xlsx'
df = pd.read_excel(file_name, index_col=0)
print(df.head()) # print the first 5 rows
<div id="load" style="display:none"><img src="ajax-loader.gif"/></div>
function getData(p){
var page=p;
document.getElementById("load").style.display = "block"; // show the loading message.
$.ajax({
url: "loadData.php?id=<? echo $id; ?>",
type: "POST",
cache: false,
data: "&page="+ page,
success : function(html){
$(".content").html(html);
document.getElementById("load").style.display = "none";
}
});
Create a gesture recognizer (subclass), that will implement touch events, like touchesBegan
. You can add it to the view after that.
This way you'll use composition instead subclassing (which was the request).
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
you would put them inside a <p>
or a <div>
<p style="text-align:center">
<a href="http//www.google.com">Search</a>
<a href="Contact Us">Contact Us</a>
</p>
sample: http://jsfiddle.net/X8HM4/1/
pathlib
module, introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths), makes path-related experience much much better.
$ pwd
/home/skovorodkin/stack
$ tree
.
+-- scripts
+-- 1.py
+-- 2.py
In order to get current working directory use Path.cwd()
:
from pathlib import Path
print(Path.cwd()) # /home/skovorodkin/stack
To get an absolute path to your script file, use Path.resolve()
method:
print(Path(__file__).resolve()) # /home/skovorodkin/stack/scripts/1.py
And to get path of a directory where your script is located, access .parent
(it is recommended to call .resolve()
before .parent
):
print(Path(__file__).resolve().parent) # /home/skovorodkin/stack/scripts
Remember that __file__
is not reliable in some situations: How do I get the path of the current executed file in Python?.
Please note, that Path.cwd()
, Path.resolve()
and other Path
methods return path objects (PosixPath
in my case), not strings. In Python 3.4 and 3.5 that caused some pain, because open
built-in function could only work with string or bytes objects, and did not support Path
objects, so you had to convert Path
objects to strings or use Path.open()
method, but the latter option required you to change old code:
$ cat scripts/2.py
from pathlib import Path
p = Path(__file__).resolve()
with p.open() as f: pass
with open(str(p)) as f: pass
with open(p) as f: pass
print('OK')
$ python3.5 scripts/2.py
Traceback (most recent call last):
File "scripts/2.py", line 11, in <module>
with open(p) as f:
TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')
As you can see open(p)
does not work with Python 3.5.
PEP 519 — Adding a file system path protocol, implemented in Python 3.6, adds support of PathLike
objects to open
function, so now you can pass Path
objects to open
function directly:
$ python3.6 scripts/2.py
OK
Potential library: https://pypi.org/project/stringcase/
Example:
import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"
Though it's questionable whether it will leave spaces in. (Examples show it removing space, but there is a bug tracker issue noting that it leaves them in.)
The simplest way with quotation marks:
B=Bar
b=bar
var="$B""$b""a"
echo "Hello ""$var"
Path2D is supported by all major browsers now
You can now use ctx.drawImage
to draw HTMLImageElements that have a .svg source in some but not all browsers. Chrome, IE11, and Safari work, Firefox works with some bugs (but nightly has fixed them).
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";
Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg>
element inserted into the DOM for reference.
You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:
var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);
There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.
I'd suggest looking in to canvg:
Here is an example using shell (bash
):
#!/bin/bash
# loop & print a folder recusively,
print_folder_recurse() {
for i in "$1"/*;do
if [ -d "$i" ];then
echo "dir: $i"
print_folder_recurse "$i"
elif [ -f "$i" ]; then
echo "file: $i"
fi
done
}
# try get path from param
path=""
if [ -d "$1" ]; then
path=$1;
else
path="/tmp"
fi
echo "base path: $path"
print_folder_recurse $path
Value validation wouldn't be a responsibility of jQuery. You can use pure JavaScript for this. Two ways that come to my mind are:
/^\d+$/.match(value)
Number(value) == value
This is the batch script I wrote for renaming a database on Windows:
@echo off
set olddb=olddbname
set newdb=newdbname
SET count=1
SET act=mysql -uroot -e "select table_name from information_schema.tables where table_schema='%olddb%'"
mysql -uroot -e "create database %newdb%"
echo %act%
FOR /f "tokens=*" %%G IN ('%act%') DO (
REM echo %count%:%%G
echo mysql -uroot -e "RENAME TABLE %olddb%.%%G to %newdb%.%%G"
mysql -uroot -e "RENAME TABLE %olddb%.%%G to %newdb%.%%G"
set /a count+=1
)
mysql -uroot -e "drop database %olddb%"
you have to use this css property,
position:relative;
use it for your #contentframe div tag
This will definitely work, In this, Send message without using any intent .
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("Phone Number", null, "Message", null, null);
This code is used for send message in background (Not showing message composer), It can also work inside the Broadcast receiver. If you want to send a message from Broadcast receiver.
<uses-permission android:name="android.permission.SEND_SMS"/>
If it has a .then
function - that's the only standard promise libraries use.
The Promises/A+ specification has a notion called then
able which is basically "an object with a then
method". Promises will and should assimilate anything with a then method. All of the promise implementation you've mentioned do this.
If we look at the specification:
2.3.3.3 if
then
is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise
It also explains the rationale for this design decision:
This treatment of
then
ables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliantthen
method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.
You shouldn't - instead call Promise.resolve(x)
(Q(x)
in Q) that will always convert any value or external then
able into a trusted promise. It is safer and easier than performing these checks yourself.
You can always run it through the test suite :D
Yes I think this would be quicker.
Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1
Progress Bar in Layout
<ProgressBar
android:id="@+id/download_progressbar"
android:layout_width="200dp"
android:layout_height="24dp"
android:background="@drawable/download_progress_bg_track"
android:progressDrawable="@drawable/download_progress_style"
style="?android:attr/progressBarStyleHorizontal"
android:indeterminate="false"
android:indeterminateOnly="false" />
download_progress_style.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/progress">
<scale
android:useIntrinsicSizeAsMinimum="true"
android:scaleWidth="100%"
android:drawable="@drawable/store_download_progress" />
</item>
Just had this issue but had to find the config for IIS Express so I could add the mime types. For me, it was located at C:\Users\<username>\Documents\IISExpress\config\applicationhost.config
and I was able to add in the correct "mime map" there.
I fixed my entire 500 problem like this:
A. Check php.ini parameters
B. Update IIS manager parameters
in this step, you get 500 errors like this and with no html loading.
in this step, you can see html page including php errors like this.
AND DONE :)
Try this sample SQL scripts for easy understanding,
CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))
--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2
INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'
INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'
SELECT * FROM TABLE1
SELECT * FROM TABLE2
DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO
Your case is:
DELETE pgc
FROM guide_category pgc
LEFT JOIN guide g
ON g.id_guide = gc.id_guide
WHERE g.id_guide IS NULL
This can be done with PIL
. First, install it, then you can take a full screenshot like this:
import PIL.ImageGrab
im = PIL.ImageGrab.grab()
im.show()
Let me try to make it simple, suppose URL of the site is www.example.com and you need to sign up by filling username and password, so we go to the login page say http://www.example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like
<form name="loginform" method="post" action="userinfo.php">
now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script
import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
'password': 'pass'}
r = requests.post(url, data=values)
print r.content
I Hope that this helps someone somewhere someday.
Try this:
git checkout [revision] .
where [revision]
is the commit hash (for example: 12345678901234567890123456789012345678ab
).
Don't forget the .
at the end, very important. This will apply changes to the whole tree. You should execute this command in the git project root. If you are in any sub directory, then this command only changes the files in the current directory. Then commit and you should be good.
You can undo this by
git reset --hard
that will delete all modifications from the working directory and staging area.
ep = datetime.datetime(1970,1,1,0,0,0)
x = (datetime.datetime.utcnow()- ep).total_seconds()
This should be different from int(time.time())
, but it is safe to use something like x % (60*60*24)
datetime — Basic date and time types:
Unlike the time module, the datetime module does not support leap seconds.
Try using additional condition in join:
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1
INNER JOIN Table2
ON (Table1.Col1 = Table2.Col1
OR (Table1.Col1 IS NULL AND Table2.Col1 IS NULL)
)
Lodash has a few Math utility methods that can round, floor, and ceil a number to a given decimal precision. This leaves off trailing zeroes.
They take an interesting approach, using the exponent of a number. Apparently this avoids rounding issues.
(Note: func
is Math.round
or ceil
or floor
in the code below)
// Shift with exponential notation to avoid floating-point issues.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
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
It's a double not
operation. The first !
converts the value to boolean and inverts its logical value. The second !
inverts the logical value back.
You should put your processing into the class constructor or an OnInit
hook method.
I'm making a guess here, but your start
invocation probably looks like this:
start "\Foo\Bar\Path with spaces in it\program.exe"
This will open a new console window, using “\Foo\Bar\Path with spaces in it\program.exe” as its title.
If you use start
with something that is (or needs to be) surrounded by quotes, you need to put empty quotes as the first argument:
start "" "\Foo\Bar\Path with spaces in it\program.exe"
This is because start
interprets the first quoted argument it finds as the window title for a new console window.
Try getppid()
if you want your C program to print your shell's PID.
Scala inherits most of Java's arithmetic operators. This includes bitwise-or |
(single pipe character), bitwise-and &
, bitwise-exclusive-or ^
, as well as logical (boolean) or ||
(two pipe characters) and logical-and &&
. Interestingly, you can use the single character operators on boolean
, so the java'ish logical operators are totally redundant:
true && true // valid
true & true // valid as well
3 & 4 // bitwise-and (011 & 100 yields 000)
3 && 4 // not valid
As pointed out in another post, calls ending in an equals sign =
, are resolved (if a method with that name does not exist!) by a reassignment:
var x = 3
x += 1 // `+=` is not a method in `int`, Scala makes it `x = x + 1`
This 'double-check' makes it possible, to easily exchange a mutable for an immutable collection:
val m = collection.mutable.Set("Hallo") // `m` a val, but holds mutable coll
var i = collection.immutable.Set("Hallo") // `i` is a var, but holds immutable coll
m += "Welt" // destructive call m.+=("Welt")
i += "Welt" // re-assignment i = i + "Welt" (creates a new immutable Set)
To match regexes you need to use the =~
operator.
Try this:
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
Alternatively, you can use wildcards (instead of regexes) with the ==
operator:
[[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched
If portability is not a concern, I recommend using [[
instead of [
or test
as it is safer and more powerful. See What is the difference between test, [ and [[ ? for details.
apache-tomcat-8.0.33
If you want to enable debug logging in tomcat for TLD scanned jars then you have to change /conf/logging.properties file in tomcat directory.
uncomment the line :
org.apache.jasper.servlet.TldScanner.level = FINE
FINE level is for debug log.
This should work for normal tomcat.
If the tomcat is running under eclipse. Then you have to set the path of tomcat logging.properties in eclipse.
Now the jar files that scanned for TLDs should show in the log.
This should solve your problem, you should try to run the following below:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
You can try by adding following line to catalina.bat after last entry of JAVA_OPTS
set JAVA_OPTS=%JAVA_OPTS% -Dhttps.protocols=TLSv1.2 -Djdk.tls.client.protocols=TLSv1.2
You kill a session like this:
Session.Abandon()
If, however, you just want to empty the session, use:
Session.Clear()
You can use the data.table package:
How to reorder data.table columns (without copying)
require(data.table)
setcolorder(DT,myOrder)
It Works , try out this :
InputStream in_s1 = TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");
background-image
instead of background
This works in Opera : http://jsfiddle.net/ZNsbU/5/
But it doesn't work in FF5 nor IE8. (yay for outdated browsers :D )
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 200px / 600px 400px no-repeat;
}
You could do it like this :
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 400px no-repeat;
background-size:20px 20px
}
Which works in FF5 and Opera but not in IE8.
If you want string to be on the left and image on the right, this should be fine (Swift 5)
/// [ String ------------------ Image ] Style Custom Button
/// For use, just define 'Title Text' and 'Image' on ib / source with setting the class 'DistantTextImageButton'.
class DistantTextImageButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
self.semanticContentAttribute = .forceRightToLeft
self.contentHorizontalAlignment = .left
guard let imageView = imageView,
let title = title(for: .normal),
let font = titleLabel?.font else { return }
imageEdgeInsets = UIEdgeInsets(top: 0, left: bounds.width - imageView.bounds.width - title.textSizeWithFont(font).width, bottom: 0, right: 0)
titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
extension String {
func textSizeWithFont(_ font: UIFont) -> CGSize {
return self.size(withAttributes: [.font: font])
}
}
I had the same problem. Open the cmd and type:
python -m pip install pylint
docker container list -f "status=exited"
or
docker container ls -f "status=exited"
or
docker ps -f "status=exited"
just pass the img file object which is obtained by the input element when we select the correct file it will give the netural height and width of image
function getNeturalHeightWidth(file) {
let h, w;
let reader = new FileReader();
reader.onload = () => {
let tmpImgNode = document.createElement("img");
tmpImgNode.onload = function() {
h = this.naturalHeight;
w = this.naturalWidth;
};
tmpImgNode.src = reader.result;
};
reader.readAsDataURL(file);
}
return h, w;
}
Other than the builtin developer tools, there is none that i know of. You might, however, be able to use Firebug Lite.
It's possible that your WCF service is returning HTML. In this case, you'll want to set up a binding on the service side to return XML instead. However, this is unlikely: if it is the case, let me know and I'll make an edit with more details.
The more likely reason is that your service is throwing an error, which is returning an HTML error page. You can take a look at this blog post if you want details.
tl;dr:
There are a few possible configurations for error pages. If you're hosting on IIS, you'll want to remove the <httpErrors>
section from the WCF service's web.config
file. If not, please provide details of your service hosting scenario and I can come up with an edit to match them.
EDIT:
Having seen your edit, you can see the full error being returned. Apache can't tell which service you want to call, and is throwing an error for that reason. The service will work fine once you have the correct endpoint - you're pointed at the wrong location. I unfortunately can't tell from the information available what the right location is, but either your action (currently null
!) or the URL is incorrect.
Can get ID before add documents in database:
var idBefore = this.afs.createId();
console.log(idBefore);
See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
You need to specify a field in latest(). eg.
obj= Model.objects.filter(testfield=12).latest('testfield')
Or if your model’s Meta specifies get_latest_by, you can leave off the field_name
argument to earliest() or latest()
. Django will use the field specified in get_latest_by
by default.
You can't rewrite a line without rewriting the entire file (unless the lines happen to be the same length). If your files are small then reading the entire target file into memory and then writing it out again might make sense. You can do that like this:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2; // Warning: 1-based indexing!
string sourceFile = "source.txt";
string destinationFile = "target.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read the old file.
string[] lines = File.ReadAllLines(destinationFile);
// Write the new file over the old file.
using (StreamWriter writer = new StreamWriter(destinationFile))
{
for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
{
if (currentLine == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(lines[currentLine - 1]);
}
}
}
}
}
If your files are large it would be better to create a new file so that you can read streaming from one file while you write to the other. This means that you don't need to have the whole file in memory at once. You can do that like this:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2;
string sourceFile = "source.txt";
string destinationFile = "target.txt";
string tempFile = "target2.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read from the target file and write to a new file.
int line_number = 1;
string line = null;
using (StreamReader reader = new StreamReader(destinationFile))
using (StreamWriter writer = new StreamWriter(tempFile))
{
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(line);
}
line_number++;
}
}
// TODO: Delete the old file and replace it with the new file here.
}
}
You can afterwards move the file once you are sure that the write operation has succeeded (no excecption was thrown and the writer is closed).
Note that in both cases it is a bit confusing that you are using 1-based indexing for your line numbers. It might make more sense in your code to use 0-based indexing. You can have 1-based index in your user interface to your program if you wish, but convert it to a 0-indexed before sending it further.
Also, a disadvantage of directly overwriting the old file with the new file is that if it fails halfway through then you might permanently lose whatever data wasn't written. By writing to a third file first you only delete the original data after you are sure that you have another (corrected) copy of it, so you can recover the data if the computer crashes halfway through.
A final remark: I noticed that your files had an xml extension. You might want to consider if it makes more sense for you to use an XML parser to modify the contents of the files instead of replacing specific lines.
this way is a bit more flexible than using all()
:
my_list = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
all_zeros = False if False in [x[2] == 0 for x in my_list] else True
any_zeros = True if True in [x[2] == 0 for x in my_list] else False
or more succinctly:
all_zeros = not False in [x[2] == 0 for x in my_list]
any_zeros = 0 in [x[2] for x in my_list]
RadioButton by default takes the colour of colorAccent in res/values/colors.xml file. So go to that file and change the value of
<color name="colorAccent">#3F51B5</color>
to the colour you want.
Even in base Python you can do the computation in generic form
result = sum(x**2 for x in some_vector) ** 0.5
x ** 2
is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).
Using instead x ** 0.5
to take the square root doesn't do the exact same computations as math.sqrt
as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.
I often use x ** 0.5
simply because I don't want to add math
just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.
I like Fernandes' answer even though you ask for the obj twice.
This should also do (more or less the same as Martin's A).
id obj;
if ((obj=[dict objectForKey:@"blah"])) {
// use obj
} else {
// Do something else like creating the obj and add the kv pair to the dict
}
Martin's and this answer both work on iPad2 iOS 5.0.1 9A405
You can also face problems if a subdirectory itself is a git repository - ie .has a .git directory - check with ls -a
.
To remove go to the subdirectory and rm .git -rf
.
since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:
npx mocha <args>
Note: the optional args are forwarded to the command being executed (mocha in this case)
this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).
Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.
You can read more on npx here
Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...
you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:
node node_modules/.bin/mocha
npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:
"scripts": {
"test": "mocha"
}
and invoke it with
npm test
If you're using Python 3, raw_input
has changed to input
Python 3 example:
line = input('Enter a sentence:')
If you happen to be using a mac keyboard on linux (ubuntu), Insert
is actually fn
+ return
. You can also click on the zero of the number pad to switch between the cursor types.
Took me a while to figure that out. :-P
This is probably the easiest way:
new Date(<your-date-object>.toDateString());
Example: To get the Current Date without time component:
new Date(new Date().toDateString());
gives: Thu Jul 11 2019 00:00:00 GMT-0400 (Eastern Daylight Time)
Note this works universally, because toDateString()
produces date string with your browser's localization (without the time component), and the new Date()
uses the same localization to parse that date string.
This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
@model TestProject.Models.TestModel
<script>
function testButton_Click(){
var javaModel ={
ModelId: '@Model.TestId',
CreatedDate: '@Model.CreatedDate.ToShortDateString()',
TestDescription: '@Model.TestDescription',
//Here I am using a Kendo editor and I want to bind the text value to my javascript
//object. This may be different for you depending on what controls you use.
TestStatus: ($('#StatusTextBox'))[0].value,
TestType: '@Model.TestType'
}
//Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
//selected value. This puzzled me due to the conversion to Json object in the Ajax call.
//By parsing the Type to an int this worked.
javaModel.TestType = parseInt(javaModel.TestType);
$.ajax({
//This is where you want to post to.
url:'@Url.Action("TestModelUpdate","TestController")',
async:true,
type:"POST",
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(javaModel)
});
}
</script>
//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.
[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
TestModel.UpdateTestModel(newTestModel);
return //do some return action;
}
What you are missing, as idljarn already mentioned in a comment is that if you are overriding a function from a base class, then you cannot possibly mark it as non-virtual:
struct base {
virtual void f();
};
struct derived : base {
void f() final; // virtual as it overrides base::f
};
struct mostderived : derived {
//void f(); // error: cannot override!
};
I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.
For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.
I think the challenge here is not to call upon global()
I would personally define a list for your (dynamic) variables to be held and then append to it within a for loop. Then use a separate for loop to view each entry or even execute other operations.
Here is an example - I have a number of network switches (say between 2 and 8) at various BRanches. Now I need to ensure I have a way to determining how many switches are available (or alive - ping test) at any given branch and then perform some operations on them.
Here is my code:
import requests
import sys
def switch_name(branchNum):
# s is an empty list to start with
s = []
#this FOR loop is purely for creating and storing the dynamic variable names in s
for x in range(1,8,+1):
s.append("BR" + str(branchNum) + "SW0" + str(x))
#this FOR loop is used to read each of the switch in list s and perform operations on
for i in s:
print(i,"\n")
# other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.
def main():
# for example's sake - hard coding the site code
branchNum= "123"
switch_name(branchNum)
if __name__ == '__main__':
main()
Output is:
BR123SW01
BR123SW02
BR123SW03
BR123SW04
BR123SW05
BR123SW06
BR123SW07
I suggest you use an underscore instead of a hyphen (-), since ...
<form name="myForm">
<input name="myInput" id="my-Id" value="myValue"/>
</form>
<script>
var x = document.myForm.my-Id.value;
alert(x);
</script>
you can access the value by id easily in like that. But if you use a hyphen it will cause a syntax error.
This is an old sample, but it can work without jquery -:)
thanks to @jean_ralphio, there is work around way to avoid by
var x = document.myForm['my-Id'].value;
Dash-style would be a google code style, but I don't really like it. I would prefer TitleCase for id and camelCase for class.
You can use method shown here and replace isNull
with isnan
:
from pyspark.sql.functions import isnan, when, count, col
df.select([count(when(isnan(c), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
| 0| 0| 3|
+-------+----------+---+
or
df.select([count(when(isnan(c) | col(c).isNull(), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
| 0| 0| 5|
+-------+----------+---+
I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.
import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JFrame; import javax.swing.JPanel; import org.jdesktop.swingx.JXDatePicker; public class DatePickerExample extends JPanel { public static void main(String[] args) { JFrame frame = new JFrame("JXPicker Example"); JPanel panel = new JPanel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(400, 400, 250, 100); JXDatePicker picker = new JXDatePicker(); picker.setDate(Calendar.getInstance().getTime()); picker.setFormats(new SimpleDateFormat("dd.MM.yyyy")); panel.add(picker); frame.getContentPane().add(panel); frame.setVisible(true); } }
Control Panel > Turn Windows Features on or off
Internet Information Services > World Wide Web Services > Application Development Features
Enable the two options
.NET Extensibility 3.5
.ASP.NET 3.5
This has been solved by flexbox, once and forever:
https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/
The HTML
<body class="Site">
<header>…</header>
<main class="Site-content">…</main>
<footer>…</footer>
</body>
The CSS
.Site {
display: flex;
min-height: 100vh;
flex-direction: column;
}
.Site-content {
flex: 1;
}
I was trying to do this but having problems with Kjetil Watnedal's solution because I don't use the inline linq syntax - I prefer method-style syntax. My specific problem was in trying to do dynamic sorting using a custom IComparer
.
My solution ended up like this:
Given an IQueryable query like so:
List<DATA__Security__Team> teams = TeamManager.GetTeams();
var query = teams.Where(team => team.ID < 10).AsQueryable();
And given a run-time sort field argument:
string SortField; // Set at run-time to "Name"
The dynamic OrderBy looks like so:
query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField));
And that's using a little helper method called GetReflectedPropertyValue():
public static string GetReflectedPropertyValue(this object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}
One last thing - I mentioned that I wanted the OrderBy
to use custom IComparer
- because I wanted to do Natural sorting.
To do that, I just alter the OrderBy
to:
query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField), new NaturalSortComparer<string>());
See this post for the code for NaturalSortComparer()
.
This approach worked for me and is less cluttered than some solutions:
try:
from ..components.core import GameLoopEvents
except ValueError:
from components.core import GameLoopEvents
The parent directory is in my PYTHONPATH, and there are __init__.py
files in the parent directory and this directory.
The above always worked in python 2, but python 3 sometimes hit an ImportError or ModuleNotFoundError (the latter is new in python 3.6 and a subclass of ImportError), so the following tweak works for me in both python 2 and 3:
try:
from ..components.core import GameLoopEvents
except ( ValueError, ImportError):
from components.core import GameLoopEvents
You have mixed 2 standard.
The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";
The function http_build_query($filedata)
is only for "Content-Type: application/x-www-form-urlencoded", or none.
This will solve your problem
interface
TArrayStr = Array Of string;
implementation
function SplitString(Text: String): TArrayStr;
var
intIdx: Integer;
intIdxOutput: Integer;
const
Delimiter = ';';
begin
intIdxOutput := 0;
SetLength(Result, 1);
Result[0] := '';
for intIdx := 1 to Length(Text) do
begin
if Text[intIdx] = Delimiter then
begin
intIdxOutput := intIdxOutput + 1;
SetLength(Result, Length(Result) + 1);
end
else
Result[intIdxOutput] := Result[intIdxOutput] + Text[intIdx];
end;
end;
@Eric
Why is a code solution that works getting voted down? Sure, it's ugly and might not be the fastest way to do it, but it's more instructive that saying "strtol" or "sscanf". If you try it yourself you will learn something about how things happen under the hood.
I don't really think your solution should have been voted down, but my guess as to why it's happening is because it's less practical. The idea with voting is that the "best" answer will float to the top, and while your answer might be more instructive about what happens under the hood (or a way it might happen), it's definitely not the best way to parse hex numbers in a production system.
Again, I don't think there's anything wrong with your answer from an educational standpoint, and I certainly wouldn't (and didn't) vote it down. Don't get discouraged and stop posting just because some people didn't like one of your answers. It happens.
I doubt my answer makes you feel any better about yours being voted down, but I know it's especially not fun when you ask why something's being voted down and no one answers.
Your error is caused by these:
Dim oTable As Table, oRow As Row,
These types, Table
and Row
are not variable types native to Excel. You can resolve this in one of two ways:
Dim oTable as Word.Table, oRow as Word.Row
. This is called early-binding. Object
type: Dim oTable as Object, oRow as Object
. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.I have not tested your code but I suspect ActiveDocument
won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:
Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long
Set wdApp = GetObject(,"Word.Application")
Application.ScreenUpdating = False
For Each oTable In wdApp.ActiveDocument.Tables
simply change <div>
to <tbody>
<table id="authenticationSetting" style="display: none">
<tbody id="authenticationOuterIdentityBlock" style="display: none;">
<tr>
<td class="orionSummaryHeader">
<orion:message key="policy.wifi.enterprise.authentication.outeridentitity" />:</td>
<td class="orionSummaryColumn">
<orion:textbox id="authenticationOuterIdentity" size="30" />
</td>
</tr>
</tbody>
</table>
Click Run on the menu and then Edit Configurations... then click on Android Application on the left and click the + button. Choose Android Application from the pop-up menu. Then pick the module (its normally app or something like that). Then click apply and ok.
If you have more errors after that, try to re-import the project in Android Studio.
In simple words.
In Python you should add self
argument as the first argument to all defined methods in classes:
class MyClass:
def method(self, arg):
print(arg)
Then you can use your method according to your intuition:
>>> my_object = MyClass()
>>> my_object.method("foo")
foo
This should solve your problem :)
For a better understanding, you can also read the answers to this question: What is the purpose of self?
isinstance(your_object, basestring)
will be True if your object is indeed a string-type. 'str' is reserved word.
my apologies, the correct answer is using 'basestring' instead of 'str' in order of it to include unicode strings as well - as been noted above by one of the other responders.
Simplest solution without extra extensions, enums, classes and etc.:
NSException(name:NSExceptionName(rawValue: "name"), reason:"reason", userInfo:nil).raise()
Yes. Try:
class USBDevice : GenericDevice, IOurDevice
Note: The base class should come before the list of interface names.
Of course, you'll still need to implement all the members that the interfaces define. However, if the base class contains a member that matches an interface member, the base class member can work as the implementation of the interface member and you are not required to manually implement it again.
You can define a method in spec_helper.rb that sends a message both to Rails.logger.info and to puts and use that for debugging:
def log_test(message)
Rails.logger.info(message)
puts message
end
Full working solution :
HTML:
<form id="myform">
<button>erase</button>
<select id="fs">
<option value="Arial">Arial</option>
<option value="Verdana ">Verdana </option>
<option value="Impact ">Impact </option>
<option value="Comic Sans MS">Comic Sans MS</option>
</select>
<select id="size">
<option value="7">7</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</form>
<br/>
<textarea class="changeMe">Text into textarea</textarea>
<div id="container" class="changeMe">
<div id="float">
<p>
Text into container
</p>
</div>
</div>
jQuery:
$("#fs").change(function() {
//alert($(this).val());
$('.changeMe').css("font-family", $(this).val());
});
$("#size").change(function() {
$('.changeMe').css("font-size", $(this).val() + "px");
});
Fiddle here: http://jsfiddle.net/AaT9b/
The advantage of Java 1.8 forEach method over 1.7 Enhanced for loop is that while writing code you can focus on business logic only.
forEach method takes java.util.function.Consumer object as an argument, so It helps in having our business logic at a separate location that you can reuse it anytime.
Have look at below snippet,
Here I have created new Class that will override accept class method from Consumer Class, where you can add additional functionility, More than Iteration..!!!!!!
class MyConsumer implements Consumer<Integer>{
@Override
public void accept(Integer o) {
System.out.println("Here you can also add your business logic that will work with Iteration and you can reuse it."+o);
}
}
public class ForEachConsumer {
public static void main(String[] args) {
// Creating simple ArrayList.
ArrayList<Integer> aList = new ArrayList<>();
for(int i=1;i<=10;i++) aList.add(i);
//Calling forEach with customized Iterator.
MyConsumer consumer = new MyConsumer();
aList.forEach(consumer);
// Using Lambda Expression for Consumer. (Functional Interface)
Consumer<Integer> lambda = (Integer o) ->{
System.out.println("Using Lambda Expression to iterate and do something else(BI).. "+o);
};
aList.forEach(lambda);
// Using Anonymous Inner Class.
aList.forEach(new Consumer<Integer>(){
@Override
public void accept(Integer o) {
System.out.println("Calling with Anonymous Inner Class "+o);
}
});
}
}
After much further research, i managed to find a solution.
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}
A solution that actually works:
public void Test() {
throw new MyCustomException("You can't do that!");
}
[TestMethod]
public void ThisWillPassIfExceptionThrown()
{
var exception = Assert.ThrowsException<MyCustomException>(
() => Test(),
"This should have thrown!");
Assert.AreEqual("You can't do that!", exception.Message);
}
This works with using Microsoft.VisualStudio.TestTools.UnitTesting;
.
The following code works
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function AddRow()
{
$('#myTable').append('<tr><td>test 2</td></tr>')
}
</script>
<title></title>
</head>
<body>
<input type="button" id="btnAdd" onclick="AddRow()"/>
<a href="">test</a>
<table id="myTable">
<tbody >
<tr>
<td>
test
</td>
</tr>
</tbody>
</table>
</body>
</html>
Note this will work as of jQuery 1.4 even if the table includes a <tbody>
element:
jQuery since version 1.4(?) automatically detects if the element you are trying to insert (using any of the append(), prepend(), before(), or after() methods) is a
<tr>
and inserts it into the first<tbody>
in your table or wraps it into a new<tbody>
if one doesn't exist.
Sure you can simply use two sliders overlaying each other and add a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in @Garys) solution.
Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.
It uses JQuery but a vanillajs version is no magic though.
@Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.
(function() {
function addSeparator(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}
function rangeInputChangeEventHandler(e){
var rangeGroup = $(this).attr('name'),
minBtn = $(this).parent().children('.min'),
maxBtn = $(this).parent().children('.max'),
range_min = $(this).parent().children('.range_min'),
range_max = $(this).parent().children('.range_max'),
minVal = parseInt($(minBtn).val()),
maxVal = parseInt($(maxBtn).val()),
origin = $(this).context.className;
if(origin === 'min' && minVal > maxVal-5){
$(minBtn).val(maxVal-5);
}
var minVal = parseInt($(minBtn).val());
$(range_min).html(addSeparator(minVal*1000) + ' €');
if(origin === 'max' && maxVal-5 < minVal){
$(maxBtn).val(5+ minVal);
}
var maxVal = parseInt($(maxBtn).val());
$(range_max).html(addSeparator(maxVal*1000) + ' €');
}
$('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
})();
_x000D_
body{
font-family: sans-serif;
font-size:14px;
}
input[type='range'] {
width: 210px;
height: 30px;
overflow: hidden;
cursor: pointer;
outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
-webkit-appearance: none;
background: none;
}
input[type='range']::-webkit-slider-runnable-track {
width: 200px;
height: 1px;
background: #003D7C;
}
input[type='range']:nth-child(2)::-webkit-slider-runnable-track{
background: none;
}
input[type='range']::-webkit-slider-thumb {
position: relative;
height: 15px;
width: 15px;
margin-top: -7px;
background: #fff;
border: 1px solid #003D7C;
border-radius: 25px;
z-index: 1;
}
input[type='range']:nth-child(1)::-webkit-slider-thumb{
z-index: 2;
}
.rangeslider{
position: relative;
height: 60px;
width: 210px;
display: inline-block;
margin-top: -5px;
margin-left: 20px;
}
.rangeslider input{
position: absolute;
}
.rangeslider{
position: absolute;
}
.rangeslider span{
position: absolute;
margin-top: 30px;
left: 0;
}
.rangeslider .right{
position: relative;
float: right;
margin-right: -5px;
}
/* Proof of concept for Firefox */
@-moz-document url-prefix() {
.rangeslider::before{
content:'';
width:100%;
height:2px;
background: #003D7C;
display:block;
position: relative;
top:16px;
}
input[type='range']:nth-child(1){
position:absolute;
top:35px !important;
overflow:visible !important;
height:0;
}
input[type='range']:nth-child(2){
position:absolute;
top:35px !important;
overflow:visible !important;
height:0;
}
input[type='range']::-moz-range-thumb {
position: relative;
height: 15px;
width: 15px;
margin-top: -7px;
background: #fff;
border: 1px solid #003D7C;
border-radius: 25px;
z-index: 1;
}
input[type='range']:nth-child(1)::-moz-range-thumb {
transform: translateY(-20px);
}
input[type='range']:nth-child(2)::-moz-range-thumb {
transform: translateY(-20px);
}
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="rangeslider">
<input class="min" name="range_1" type="range" min="1" max="100" value="10" />
<input class="max" name="range_1" type="range" min="1" max="100" value="90" />
<span class="range_min light left">10.000 €</span>
<span class="range_max light right">90.000 €</span>
</div>
_x000D_
pop'n'fresh
>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>>
sys
has some useful stuff:
$ python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'c:\\Python26\\python.exe'
>>> sys.exec_prefix
'c:\\Python26'
>>>
>>> print '\n'.join(sys.path)
c:\Python26\lib\site-packages\setuptools-0.6c11-py2.6.egg
c:\Python26\lib\site-packages\nose-1.0.0-py2.6.egg
C:\Windows\system32\python26.zip
c:\Python26\DLLs
c:\Python26\lib
c:\Python26\lib\plat-win
c:\Python26\lib\lib-tk
c:\Python26
c:\Python26\lib\site-packages
c:\Python26\lib\site-packages\win32
c:\Python26\lib\site-packages\win32\lib
c:\Python26\lib\site-packages\Pythonwin
c:\Python26\lib\site-packages\wx-2.8-msw-unicode
All java objects are pointer because a variable which holds address is called pointer and object hold address.so object is pointer variable.
There are two easy methods:
\
before double quotes.''
instead of "
For example:
System.out.println("\"Hello\"");
System.out.println("''Hello''");
mysqldump will not dump database events, triggers and routines unless explicitly stated when dumping individual databases;
mysqldump -uuser -p db_name --events --triggers --routines > db_name.sql
Googling gives me this:
Command A & Command B
Execute Command A, then execute Command B (no evaluation of anything)
Command A | Command B
Execute Command A, and redirect all its output into the input of Command B
Command A && Command B
Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B
Command A || Command B
Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B
When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”
For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging
In another way,
If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”
There won't be any "merge commit" in fast-forwarding merge.
Do you need it to be;
UIImage *img = [UIImage imageNamed@"aImageName"];
It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.
Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.
For example:
class MyModel(models.model):
field1 = models.CharField(max_length=10)
field2 = models.CharField(max_length=10)
def combined_fields(self):
return '{} {}'.format(self.field1, self.field2)
Then in the admin you can add the combined_fields()
as a readonly field:
class MyModelAdmin(models.ModelAdmin):
list_display = ('field1', 'field2', 'combined_fields')
readonly_fields = ('combined_fields',)
def combined_fields(self, obj):
return obj.combined_fields()
If you want to store the combined_fields
in the database you could also save it when you save the model:
def save(self, *args, **kwargs):
self.field3 = self.combined_fields()
super(MyModel, self).save(*args, **kwargs)
CSS relates to visual styling and not behaviour, so the answer is no really.
You could however either use javascript to modify the behaviour or change the styling of the span in question so that it doesn't have the pointy finger, underline, etc. Styling it like that will still leave it clickable.
Even better, change your markup so that it reflects what you want it to do.
Using BitArray class and making an extension method as OP suggests:
public static bool GetBit(this byte b, int bitNumber)
{
System.Collections.BitArray ba = new BitArray(new byte[]{b});
return ba.Get(bitNumber);
}
If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
There's no such thing as an IEnumerable<T1, T2>
but a KeyValuePair<TKey, TValue>
is fine.
You were close:
if (typeof a_string === 'string') {
// this is a string
}
On a related note: the above check won't work if a string is created with new String('hello')
as the type will be Object
instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.
function get_time($time) {
$duration = $time / 1000;
$hours = floor($duration / 3600);
$minutes = floor(($duration / 60) % 60);
$seconds = $duration % 60;
if ($hours != 0)
echo "$hours:$minutes:$seconds";
else
echo "$minutes:$seconds";
}
get_time('1119241');
I think that @Benny Neugebauer comment on the OP question about the Fetch API should be presented here as an answer since the OP was looking for a functionality in Chrome to manually create HTTP POST requests and that exactly what the fetch command do.
There is a nice simple example of the Fetch API here
// Make sure you run it from the domain 'https://jsonplaceholder.typicode.com/'. (cross-origin-policy)
fetch('https://jsonplaceholder.typicode.com/posts',{method: 'POST', headers: {'test': 'TestPost'} })
.then(response => response.json())
.then(json => console.log(json))
Some of the advantages of the fetch command are really precious: Its simple, short, fast, available and even as a console command it stored on your chrome console and can be used later.
The simplicity of pressing F12, write the command in the console tab (or press the up key if you used it before) then press enter, see it pending and returning the response is what making it really useful for simple post requests tests.
Of course, The main disadvantage here is that unlike Postman, This wont pass the cross-origin-policy but still I find it very useful for testing in local environment or other environments where I can enable CORS manually.
It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.
Nothing. Just execute your query. If the connection has died, either your JDBC driver will reconnect (if it supports it, and you enabled it in your connection string--most don't support it) or else you'll get an exception.
If you check the connection is up, it might fall over before you actually execute your query, so you gain absolutely nothing by checking.
That said, a lot of connection pools validate a connection by doing something like SELECT 1
before handing connections out. But this is nothing more than just executing a query, so you might just as well execute your business query.
This is how I did it.
It may be faster because it is using execute_batch
:
# df is the dataframe
if len(df) > 0:
df_columns = list(df)
# create (col1,col2,...)
columns = ",".join(df_columns)
# create VALUES('%s', '%s",...) one '%s' per column
values = "VALUES({})".format(",".join(["%s" for _ in df_columns]))
#create INSERT INTO table (columns) VALUES('%s',...)
insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)
cur = conn.cursor()
psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
conn.commit()
cur.close()
Here is another case.
We have several portlets in different portlet application war and all of them use spring. So in order to reduce size of each war, we have created shared libraries for spring jars in the WebSphere Portal server.
However, I came across the same issue as above of not having the spring form tags being referred from the jsp files.
In order to resolve, I have copied the spring-form.tld file into the WEB-INF/ directory and redeployed the war and it worked.
Hope it helps for anyone having a similar issue as mine.
I had the same problem,
i solved it by:
1 - i uninstall virtual box
2 - i uninstall genymotion with all new folder that dependency
3 - download latest version of virtual box(from oracle site)
4 - download latest version of Genymotion(without virtual box version
size:about42M)
5 - first install virtual box
6 - install genymotion
7 - before run genymotion you should restart your windows os
8 - run genymotion as admin
Sorry for my english writing
I'm new to learn :D
After some time with Google I asked on the ask ubuntu chat room.
A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:
grep -P "(^|\s)abc(\s|$)"
gives the result I was looking for. -P is an experimental implementation of perl regexps.
grepping for abc
and then using filters like grep -v '@abc'
(this is far from perfect...) should also work, but my patch does something similar.
@delato468 comment must be listed as a solution as it worked for me.
In addition to defining the parameter, the user must pass it too at the time of calling the function
fetch_data(PDO $pdo, $cat_id)