Ok here's how I fixed this
My model is a list
of categories. Each category contains a list
of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton
will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton
instead of Html.RadioButtonFor
.
Here's the final 'working' pseudo-code:
@foreach (var cat in Model.Categories)
{
//A piece of code & html here
@foreach (var item in cat.SubCategories)
{
@Html.RadioButton(item.CategoryID.ToString(), item.ID)
}
}
The result is:
<input name="127" type="radio" value="110">
Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.
Thanks to all of the people who helped me solve this ;)
I just checked the status of the response object:
$promise.then( function successCallback(response) {
console.log(response);
if (response.status === 200) { ... }
});
If you want a relative link to your wiki page on GitHub, use this:
Read here: [Some other wiki page](path/to/some-other-wiki-page)
If you want a link to a file in the repository, let us say, to reference some header file, and the wiki page is at the root of the wiki, use this:
Read here: [myheader.h](../tree/master/path/to/myheader.h)
The rationale for the last is to skip the "/wiki" path with "../", and go to the master branch in the repository tree without specifying the repository name, that may change in the future.
Erik Aigner,
Please use $dirty(The field has been modified) and $invalid (The field content is not valid).
Please check below examples for angular form validation
1)
Validation example HTML for user enter inputs:
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate>
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
</form>
2)
Validation example HTML/Js for user submits :
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate form-submit-validation="">
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit">
</p>
</form>
Custom Directive :
app.directive('formSubmitValidation', function () {
return {
require: 'form',
compile: function (tElem, tAttr) {
tElem.data('augmented', true);
return function (scope, elem, attr, form) {
elem.on('submit', function ($event) {
scope.$broadcast('form:submit', form);
if (!form.$valid) {
$event.preventDefault();
}
scope.$apply(function () {
scope.submitted = true;
});
});
}
}
};
})
3)
you don't want use directive use ng-change function like below
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate ng-change="submitFun()">
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit">
</p>
</form>
Controller SubmitFun() JS:
var app = angular.module('example', []);
app.controller('exampleCntl', function($scope) {
$scope.submitFun = function($event) {
$scope.submitted = true;
if (!$scope.myForm.$valid)
{
$event.preventDefault();
}
}
});
To get the current memory_limit value, run:
php -r "echo ini_get('memory_limit').PHP_EOL;"
Try increasing the limit in your php.ini
file (ex. /etc/php5/cli/php.ini
for Debian-like systems):
; Use -1 for unlimited or define an explicit value like 2G
memory_limit = -1
Or, you can increase the limit with a command-line argument:
php -d memory_limit=-1 composer.phar require hwi/oauth-bundle php-http/guzzle6-adapter php-http/httplug-bundle
To get loaded php.ini files location try:
php --ini
Another quick solution:
php composer.phar COMPOSER_MEMORY_LIMIT=-1 require hwi/oauth-bundle php-http/guzzle6-adapter php-http/httplug-bundle
Here is another way:
df[[i for i in list(df.columns) if i != '<your column>']]
You just pass all columns to be shown except of the one you do not want.
chart.series[0].setData(data,true);
The setData
method itself will call the redraw method
I found that the new version of PhpMyAdmin put the 'config.inc.php' files in /var/lib/phpmyadmin/
I spend much time in the wrong dir (/usr/share) as this is where all the files also is located, but changes are not reflected.
After putting my settings in
/var/lib/phpmyadmin/config.inc.php
They worked
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
Note that both pcolor and "surf + view(2)" do not show the last row and the last column of your 2D data.
On the other hand, using imagesc, you have to be careful with the axes. The surf and the imagesc examples in gevang's answer only (almost -- apart from the last row and column) correspond to each other because the 2D sinc function is symmetric.
To illustrate these 2 points, I produced the figure below with the following code:
[x, y] = meshgrid(1:10,1:5);
z = x.^3 + y.^3;
subplot(3,1,1)
imagesc(flipud(z)), axis equal tight, colorbar
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc')
subplot(3,1,2)
surf(x,y,z,'EdgeColor','None'), view(2), axis equal tight, colorbar
title('surf with view(2)')
subplot(3,1,3)
imagesc(flipud(z)), axis equal tight, colorbar
axis([0.5 9.5 1.5 5.5])
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc cropped')
colormap jet
As you can see the 10th row and 5th column are missing in the surf plot. (You can also see this in images in the other answers.)
Note how you can use the "set(gca, 'YTick'..." (and Xtick) command to set the x and y tick labels properly if x and y are not 1:1:N.
Also note that imagesc only makes sense if your z data correspond to xs and ys are (each) equally spaced. If not you can use surf (and possibly duplicate the last column and row and one more "(end,end)" value -- although that's a kind of a dirty approach).
Something like:
$(".head h3").html("Public offers");
In bootstrap 4 use:
<ul class="nav navbar-nav ml-auto">
This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.
Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.
Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.
In your string file use this
<string name="redeem_point"> You currently have %s points(%s points = 1 %s)</string>
And in your code use as accordingly
coinsTextTV.setText(String.format(getContext().getString(R.string.redeem_point), rewardPoints.getReward_points()
, rewardPoints.getConversion_rate(), getString(R.string.rs)));
You can access tempfile in Spring by casting if the class of interface MultipartFile
is CommonsMultipartFile
.
public File getTempFile(MultipartFile multipartFile)
{
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
FileItem fileItem = commonsMultipartFile.getFileItem();
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
File file = new File(absPath);
//trick to implicitly save on disk small files (<10240 bytes by default)
if (!file.exists()) {
file.createNewFile();
multipartFile.transferTo(file);
}
return file;
}
To get rid of the trick with files less than 10240 bytes maxInMemorySize
property can be set to 0 in @Configuration
@EnableWebMvc
class. After that, all uploaded files will be stored on disk.
@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
resolver.setMaxInMemorySize(0);
return resolver;
}
I suggest you when working with listview or recyclerview to use SwipeRefreshLayout. Like this
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/card_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
Only wrap your view and this will create an animation of refresh when loading data or by swipping down the screen as we can do in many apps.
Here's the documentation of how to use it:
https://developer.android.com/training/swipe/add-swipe-interface.html
https://developer.android.com/training/swipe/respond-refresh-request.html
Happy coding !
do you use jquery? if then:
$('#xx').val();
or use original javascript(DOM)
document.getElementById('xx').value
or
xxxform.xx.value;
if you want to learn more, w3chool can help you a lot.
From what I can tell, the MVVM maps to the MV of MVC - meaning that in a traditional MVC pattern the V does not communicate directly with the M. In the second version of MVC, there is a direct link between M and V. MVVM appears to take all tasks related to M and V communication, and couple it to decouple it from the C. In effect, there's still the larger scope application workflow (or implementation of the use scenarios) that are not fully accounted for in MVVM. This is the role of the controller. By removing these lower level aspects from the controllers, they are cleaner and makes it easier to modify the application's use scenario and business logic, also making controllers more reusable.
I had a similar issues once. I deleted the primary key from TABLE A but when I was trying to delete the foreign key column from table B I was shown the above same error.
You can't drop the foreign key using the column name and to bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming or deleting the attribute.
If you have a worksheet with many rows that all contain the formula, by far the easiest method is to copy a row that is without data (but it does contain formulas), and then "insert copied cells" below/above the row where you want to add. The formulas remain. In a pinch, it is OK to use a row with data. Just clear it or overwrite it after pasting.
The log file will be where the configuration file (usually /etc/redis/redis.conf
) says it is :)
By default, logfile stdout
which probably isn't what you are looking for. If redis is running daemonized, then that log configuration means logs will be sent to /dev/null
, i.e. discarded.
Summary: set logfile /path/to/my/log/file.log
in your config and redis logs will be written to that file.
You can also cut other files out
if [ -e $( echo $1 | cut -d" " -f1 ) ] ; then
...
fi
getCurrentActivity() is also in ReactContextBaseJavaModule.
(Since the this question was initially asked, many Android app also has ReactNative component - hybrid app.)
class ReactContext in ReactNative has the whole set of logic to maintain mCurrentActivity which is returned in getCurrentActivity().
Note: I wish getCurrentActivity() is implemented in Android Application class.
For completeness: with dplyr v0.2 ddply
with colwise
will also do this:
> ddply(df, .(grp), colwise(mean))
grp a b c d
1 1 4.333333 4.00 1.000000 2.000000
2 2 2.000000 2.75 2.750000 2.750000
3 3 3.000000 4.00 4.333333 3.666667
but it is slower, at least in this case:
> microbenchmark(ddply(df, .(grp), colwise(mean)),
df %>% group_by(grp) %>% summarise_each(funs(mean)))
Unit: milliseconds
expr min lq mean
ddply(df, .(grp), colwise(mean)) 3.278002 3.331744 3.533835
df %>% group_by(grp) %>% summarise_each(funs(mean)) 1.001789 1.031528 1.109337
median uq max neval
3.353633 3.378089 7.592209 100
1.121954 1.133428 2.292216 100
You are looking for 2 options to java
:
Put them in your command line invocation of the java
executable, like this:
java -Xms512M -Xmx1024M my.package.MainClass
Keep in mind that you may want the starting and max heap sizes to be the same, depending on the application, as it avoids resizing the heap during runtime (which can take up time in applications that need to be responsive). Resizing the heap can entail moving a lot of objects around and redoing bookkeeping.
For every-day projects, make them whatever you think is good enough. Profile for help.
Alternatively, you could setup your submodules so that rather than being in their default detached head state you check out a branch.
Edited to add:
One way is to checkout a particular branch of the submodule when you add it with the -b flag:
git submodule add -b master <remote-repo> <path-to-add-it-to>
Another way is to just go into the submodule directory and just check it out
git checkout master
See the deprecation in the docs
.loc
uses label based indexing to select both rows and columns. The labels being the values of the index or the columns. Slicing with .loc
includes the last element.
Let's assume we have a DataFrame with the following columns:
foo
,bar
,quz
,ant
,cat
,sat
,dat
.
# selects all rows and all columns beginning at 'foo' up to and including 'sat'
df.loc[:, 'foo':'sat']
# foo bar quz ant cat sat
.loc
accepts the same slice notation that Python lists do for both row and columns. Slice notation being start:stop:step
# slice from 'foo' to 'cat' by every 2nd column
df.loc[:, 'foo':'cat':2]
# foo quz cat
# slice from the beginning to 'bar'
df.loc[:, :'bar']
# foo bar
# slice from 'quz' to the end by 3
df.loc[:, 'quz'::3]
# quz sat
# attempt from 'sat' to 'bar'
df.loc[:, 'sat':'bar']
# no columns returned
# slice from 'sat' to 'bar'
df.loc[:, 'sat':'bar':-1]
sat cat ant quz bar
# slice notation is syntatic sugar for the slice function
# slice from 'quz' to the end by 2 with slice function
df.loc[:, slice('quz',None, 2)]
# quz cat dat
# select specific columns with a list
# select columns foo, bar and dat
df.loc[:, ['foo','bar','dat']]
# foo bar dat
You can slice by rows and columns. For instance, if you have 5 rows with labels v
, w
, x
, y
, z
# slice from 'w' to 'y' and 'foo' to 'ant' by 3
df.loc['w':'y', 'foo':'ant':3]
# foo ant
# w
# x
# y
I guess the problem is that you need to start a separate thread for each connection and call serverSocket.accept()
in a loop to accept more than one connection.
It is not a problem to have more than one connection on the same port.
Do you have a Windows machine or a Linux machine?
Under Windows cron is called 'Scheduled Tasks'. It's located in the Control Panel. You can set several scripts to run at specified times in the control panel. Use the wizard to define the scheduled times. Be sure that PHP is callable in your PATH.
Under Linux you can create a crontab for your current user by typing:
crontab -e [username]
If this command fails, it's likely that cron is not installed. If you use a Debian based system (Debian, Ubuntu), try the following commands first:
sudo apt-get update
sudo apt-get install cron
If the command runs properly, a text editor will appear. Now you can add command lines to the crontab file. To run something every five minutes:
*/5 * * * * /home/user/test.pl
The syntax is basically this:
.---------------- minute (0 - 59)
| .------------- hour (0 - 23)
| | .---------- day of month (1 - 31)
| | | .------- month (1 - 12) OR jan,feb,mar,apr ...
| | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| | | | |
* * * * * command to be executed
Read more about it on the following pages: Wikipedia: crontab
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
I find an library socket.io to test asynchronous logic. It looks simple and brief way using LinkedBlockingQueue. Here is example:
@Test(timeout = TIMEOUT)
public void message() throws URISyntaxException, InterruptedException {
final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();
socket = client();
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... objects) {
socket.send("foo", "bar");
}
}).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {
@Override
public void call(Object... args) {
values.offer(args);
}
});
socket.connect();
assertThat((Object[])values.take(), is(new Object[] {"hello client"}));
assertThat((Object[])values.take(), is(new Object[] {"foo", "bar"}));
socket.disconnect();
}
Using LinkedBlockingQueue take API to block until to get result just like synchronous way. And set timeout to avoid assuming too much time to wait the result.
Why don't you pass the entire array and process it as needed inside the function?
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}
Edit:
This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
You can use this ObjectFilter:
public class ObjectFilter : ActionFilterAttribute {
public string Param { get; set; }
public Type RootType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
object o =
new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;
}
}
}
You can then apply it to your controller methods like so:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.
I presume that this question is a continuation of this one.
What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:
<TextView
android:id="@+id/rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/rate"
/>
The string "@string/rate" refers to an entry in your strings.xml file that looks like this:
<string name="rate">Rate</string>
If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:
final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
"The new text that I'd like to display now that the user has pushed a button.");
<TextView
android:id="@+id/phoneNumber"
android:autoLink="phone"
android:linksClickable="true"
android:text="+91 22 2222 2222"
/>
This is how you can open EditText label assigned number on dialer directly.
From Increase MySQL connection limit:-
MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:
For MySQL 3.x:
# vi /etc/my.cnf
set-variable = max_connections = 250
For MySQL 4.x and 5.x:
# vi /etc/my.cnf
max_connections = 250
Restart MySQL once you’ve made the changes and verify with:
echo "show variables like 'max_connections';" | mysql
EDIT:-(From comments)
The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs
Wow this was super annoying! Honestly I don't know what the problem was because I've uploaded many apps to the appstore via Xcode over the past few years but past couple days I tried like 8 different build uploads over span of 12 hours but NONE of them would show up in iTunesConnect as Processing or anywhere else. I eventually tried Application Loader even though I've NEVER had to use that before. The first try timed out "Fetching Apple Connect token" or something. I CMD+Q and tried Application Loader again and the 2nd time the upload finished ... and now my build shows up in iTunesConnect as processing. OMG that was annoying, confusing and a huge waste of time (typical Apple Dev experience I guess).
Anyhow ... thought I would share my results.
I've always assumed this was necessary as the output from the mapper is the input for the reducer, so it was sorted based on the keyspace and then split into buckets for each reducer input. You want to ensure all the same values of a Key end up in the same bucket going to the reducer so they are reduced together. There is no point sending K1,V2 and K1,V4 to different reducers as they need to be together in order to be reduced.
Tried explaining it as simply as possible
Do not encrypt/decrypt passwords, that is a significant security vulnerability. HASH passwords, using a strong hash algorithm such as PBKDF2, bcrypt, scrypts, or Argon.
When the user sets their password, hash it, and store the hash (and salt).
When the user logs in, re-hash their provided password, and compare it to the hash in the database.
out
is a PrintStream
type of static variable(object) of System
class and println()
is function of the PrintStream
class.
class PrintStream
{
public void println(){} //member function
...
}
class System
{
public static final PrintStream out; //data member
...
}
That is why the static variable(object) out
is accessed with the class name System
which further invokes the method println()
of it's type PrintStream
(which is a class).
Padding
Padding is inside of a View.For example if you give android:paddingLeft=20dp
, then the items inside the view will arrange with 20dp
width from left.You can also use paddingRight
, paddingBottom
, paddingTop
which are to give padding from right, bottom and top respectively.
Margin
Margin is outside of a View
. For example if you give android:marginLeft=20dp
, then the view will be arranged after 20dp
from left.
I fixed it by deleting the hidden .svn
folder and replaced it with the fresh checkout .svn
and it worked. Probably this hidden folder got messed up!
Try
/{(.*?)}/
That means, match any character between { and }, but don't be greedy - match the shortest string which ends with } (the ? stops * being greedy). The parentheses let you extract the matched portion.
Another way would be
/{([^}]*)}/
This matches any character except a } char (another way of not being greedy)
Concept:
To be very simple Type Safe like the meanings, it makes sure that type of the variable should be safe like
so it is all about the safety of the types of your storage in terms of variables.
I'd suggest avoiding in-line JavaScript:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
var check = confirm("Are you sure you want to leave?");
if (check == true) {
return true;
}
else {
return false;
}
};
}?
The above updated to reduce space, though maintaining clarity/function:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
return confirm("Are you sure you want to leave?");
};
}
A somewhat belated update, to use addEventListener()
(as suggested, by bažmegakapa, in the comments below):
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].addEventListener('click', reallySure);
}
The above binds a function to the event of each individual link; which is potentially quite wasteful, when you could bind the event-handling (using delegation) to an ancestor element, such as the following:
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
function actionToFunction (event) {
switch (event.target.tagName.toLowerCase()) {
case 'a' :
reallySure(event);
break;
default:
break;
}
}
document.body.addEventListener('click', actionToFunction);
Because the event-handling is attached to the body
element, which normally contains a host of other, clickable, elements I've used an interim function (actionToFunction
) to determine what to do with that click. If the clicked element is a link, and therefore has a tagName
of a
, the click-handling is passed to the reallySure()
function.
References:
I don't think execute
git rm first_file.txt
is a good idea.
when git notice your files is unmerged, you should ensure you had committed it.
And then open the conflict file:
cat first_file.txt
fix the conflict
4.
git add file
git commit -m "fix conflict"
5.
git push
it should works for you.
Refer to the jQuery API documentation: not() selector and not equal selector.
if you want to hide a whole div from the view in another screen size. You can follow bellow code as an example.
div.disabled{
display: none;
}
I Had the same error occurring as I was using the numpy version suggested by the requirements.txt in the repo. When I tried to 'import pandas as pd' this error occurred. Then the solution was to upgrade numpy version to 1.15.2 as the version suggested in the requirements was mismatching with pandas. I uninstalled the existing numpy version with pip and reinstalled the new version.
pip install numpy==1.15.2
Hope this helps someone
Everyone else has already answered it, but I think I still have something else to add.
Reasons to have that if
statement calling main()
(in no particular order):
Other languages (like C and Java) have a main()
function that is called when the program is executed. Using this if
, we can make Python behave like them, which feels more familiar for many people.
Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective)
It will be possible to import
that python code as a module without nasty side-effects.
This means it will be possible to run tests against that code.
This means we can import that code into an interactive python shell and test/debug/run it.
Variables inside def main
are local, while those outside it are global. This may introduce a few bugs and unexpected behaviors.
But, you are not required to write a main()
function and call it inside an if
statement.
I myself usually start writing small throwaway scripts without any kind of function. If the script grows big enough, or if I feel putting all that code inside a function will benefit me, then I refactor the code and do it. This also happens when I write bash
scripts.
Even if you put code inside the main function, you are not required to write it exactly like that. A neat variation could be:
import sys
def main(argv):
# My code here
pass
if __name__ == "__main__":
main(sys.argv)
This means you can call main()
from other scripts (or interactive shell) passing custom parameters. This might be useful in unit tests, or when batch-processing. But remember that the code above will require parsing of argv, thus maybe it would be better to use a different call that pass parameters already parsed.
In an object-oriented application I've written, the code looked like this:
class MyApplication(something):
# My code here
if __name__ == "__main__":
app = MyApplication()
app.run()
So, feel free to write the code that better suits you. :)
@tasseKATT's Answer is great, but if you don't want to make a directive, why not use $document
?
.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
var dumb = function (id) {
var queryResult = $document[0].getElementById(id)
var wrappedID = angular.element(queryResult);
return wrappedID;
};
I dont think you want to use the c# code you have there. They provide System.Text.Encoding.ASCII(also UTF-*)
string str = "some text;
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
your problems stem from ignoring the encoding in c# not your c++ code
The RestTemplate getForObject()
method does not support setting headers. The solution is to use the exchange()
method.
So instead of restTemplate.getForObject(url, String.class, param)
(which has no headers), use
HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.GET, entity, String.class, param);
Finally, use response.getBody()
to get your result.
This question is similar to this question.
If the Primary Key is Auto Increment, just specify each field except the primary key.
INSERT INTO table(field1,field2,field3)
SELECT (field1,field2,field3) FROM table
WHERE primarykey=1
Using Java 8+
String str = list.stream().collect(Collectors.joining())
or even
String str = String.join("", list);
i did not read above code but i learn something in simple so want to share here about bind method after bind method we can use it as any normal method.
<pre> note: do not use arrow function it will show error undefined </pre>
let solarSystem = {
sun: 'red',
moon : 'white',
sunmoon : function(){
let dayNight = this.sun + ' is the sun color and present in day and '+this.moon + ' is the moon color and prenet in night';
return dayNight;
}
}
let work = function(work,sleep){
console.log(this.sunmoon()); // accessing the solatSystem it show error undefine sunmmon untill now because we can't access directly for that we use .bind()
console.log('i work in '+ work +' and sleep in '+sleep);
}
let outPut = work.bind(solarSystem);
outPut('day','night')
_x000D_
Highlight everything you want to run and run as a script. You can do that by clicking the icon on the menu bar that looks like a text file with a lightning bolt on it. That is the same as hitting F5. So if F5 doesn't work you probably have an error in your script.
Do you have semicolons after each statement?
So 4 years later, Microsoft has open sourced their JDBC driver on Github. I got a notification about this question today, and went and had a look, and I believe I have found the culprit here, mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java:1713
.
Basically, the driver tries to understand what SQL Server sends back if it is not a definite result set. According to the comments, it goes like this:
Check for errors first. (ln 1669)
Not an error. Is it a result set? (ln 1680)
Not an error or a result set. Maybe a result from a T-SQL statement? That is, one of the following:
- a positive count of the number of rows affected (from INSERT, UPDATE, or DELETE),
- a zero indicating no rows affected, or the statement was DDL, or
- a -1 indicating the statement succeeded, but there is no update count information available (translates to Statement.SUCCESS_NO_INFO in batch update count arrays). (ln 1706)
None of the above. Last chance here... Going into the parser above, we know moreResults was initially true. If we come out with moreResults false, the we hit a DONE token (either DONE (FINAL) or DONE (RPC in batch)) that indicates that the batch succeeded overall, but that there is no information on individual statements' update counts. This is similar to the last case above, except that there is no update count. That is: we have a successful result (return true), but we have no other information about it (updateCount = -1). (ln 1693)
Only way to get here (moreResults is still true, but no apparent results of any kind) is if the TDSParser didn't actually parse anything. That is, we are at EOF in the response. In that case, there truly are no more results. We're done. (ln 1717)
(Emphasis mine)
So you guys were right in the end. SQL simply can't tell how many rows are affected, and defaults to -1
. :)
Back in the old days of Python, to call a function with arbitrary arguments, you would use apply
:
apply(f,args,kwargs)
apply
still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays,
f(*args,**kwargs)
is preferred. The multiprocessing.Pool
modules tries to provide a similar interface.
Pool.apply
is like Python apply
, except that the function call is performed in a separate process. Pool.apply
blocks until the function is completed.
Pool.apply_async
is also like Python's built-in apply
, except that the call returns immediately instead of waiting for the result. An AsyncResult
object is returned. You call its get()
method to retrieve the result of the function call. The get()
method blocks until the function is completed. Thus, pool.apply(func, args, kwargs)
is equivalent to pool.apply_async(func, args, kwargs).get()
.
In contrast to Pool.apply
, the Pool.apply_async
method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get()
.
For example:
import multiprocessing as mp
import time
def foo_pool(x):
time.sleep(2)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (i, ), callback = log_result)
pool.close()
pool.join()
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()
may yield a result such as
[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]
Notice, unlike pool.map
, the order of the results may not correspond to the order in which the pool.apply_async
calls were made.
So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply
. Like Pool.apply
, Pool.map
blocks until the complete result is returned.
If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async
. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async
.
Notice also that you could call a number of different functions with Pool.apply_async
(not all calls need to use the same function).
In contrast, Pool.map
applies the same function to many arguments.
However, unlike Pool.apply_async
, the results are returned in an order corresponding to the order of the arguments.
You can try this
$query = mysql_query("SELECT * FROM $this_table") or die (mysql_error());
or this
$query = mysql_query("SELECT * FROM $this_table") or die ("Table does not exists!");
or this
$query = mysql_query("SELECT * FROM $this_table");
if(!$query)
echo "The ".$this_table." does not exists";
Hope it helps!
as noted here, this is what worked best for me:
sudo apt-get install python3 python3-pip python3-setuptools
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
This will go through the source directory, create any directories that do not already exist in destination directory, and move files from source to the destination directory:
import os
import shutil
root_src_dir = 'Src Directory\\'
root_dst_dir = 'Dst Directory\\'
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
# in case of the src and dst are the same file
if os.path.samefile(src_file, dst_file):
continue
os.remove(dst_file)
shutil.move(src_file, dst_dir)
Any pre-existing files will be removed first (via os.remove
) before being replace by the corresponding source file. Any files or directories that already exist in the destination but not in the source will remain untouched.
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
This happened to me because strangely GIT thought that the local branch was different from the remote branch. This was visible in the branch graph: it displayed two different branches: remotes/origin/branch_name and branch_name.
The solution was simply to remove the local repo and re-clone it from remote. This way GIT would understand that remotes/origin/branch_name>and branch_name are indeed the same, and I could issue the git merge branch_name
.
rm <my_repo>
git clone <my_repo>
cd <my_repo>
git checkout <branch_name>
git pull
git checkout master
git merge <branch_name>
Those script tags are a common way to implement templating functionality (like in PHP) but on the client side.
By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.
Backbone doesn't force you to use any particular templating library - there are quite a few out there: Mustache, Haml, Eco,Google Closure template, and so on (the one used in the example you linked to is underscore.js). These will use their own syntax for you to write within those script tags.
Try this:
REGEXP '^[a-z0-9]+$'
As regexp is not case sensitive except for binary fields.
Assuming you want to access folder named xzy two folders up your python file. This works for me and platform independent.
".././xyz"
public static void WriteLine(this List<int> theList)
{
foreach (int i in list)
{
Console.Write("{0}\t", t.ToString());
}
Console.WriteLine();
}
Then, later...
list.WriteLine();
EncodeAndSend
is not a static function, which means it can be called on an instance of the class CPMSifDlg
. You cannot write this:
CPMSifDlg::EncodeAndSend(/*...*/); //wrong - EncodeAndSend is not static
It should rather be called as:
CPMSifDlg dlg; //create instance, assuming it has default constructor!
dlg.EncodeAndSend(/*...*/); //correct
If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object
Ex:
import each from 'foreach-object';
const object = {
firstName: 'Arosha',
lastName: 'Sum',
country: 'Australia'
};
each(object, (value, key, object) => {
console.log(key + ': ' + value);
});
// Console log output will be:
// firstName: Arosha
// lastName: Sum
// country: Australia
You could use String.Split method.
class ExampleClass
{
public ExampleClass()
{
string exampleString = "there is a cat";
// Split string on spaces. This will separate all the words in a string
string[] words = exampleString.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
// there
// is
// a
// cat
}
}
}
For more information see Sam Allen's article about splitting strings in c# (Performance, Regex)
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button) findViewById(R.id.uploadButton);
messageText = (TextView) findViewById(R.id.messageText);
messageText.setText("Uploading file path :- '/mnt/sdcard/"
+ uploadFileName + "'");
/************* Php script path ****************/
upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";
uploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection connection = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
+ uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ uploadFilePath + "" + uploadFileName);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // Allow Inputs
connection.setDoOutput(true); // Allow Outputs
connection.setUseCaches(false); // Don't use a Cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
// dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
// + fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ URLEncoder.encode(fileName, "UTF-8") + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " http://www.androidexample.com/media/uploads/"
+ uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
PHP File
<?php
$target_path = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else {
echo "There was an error uploading the file, please try again!";
}
?>
I've got this exception because of circular reference in entity.In entity that look like
public class Catalog
{
public int Id { get; set; }
public int ParentId { get; set; }
public Catalog Parent { get; set; }
public ICollection<Catalog> ChildCatalogs { get; set; }
}
I added [IgnoreDataMemberAttribute] to the Parent property. And that solved the problem.
You cannot read text strings with csvread. Here is another solution:
fid1 = fopen('test.csv','r'); %# open csv file for reading
fid2 = fopen('new.csv','w'); %# open new csv file
while ~feof(fid1)
line = fgets(fid1); %# read line by line
A = sscanf(line,'%*[^,],%f,%f'); %# sscanf can read only numeric data :(
if A(2)<4.185 %# test the values
fprintf(fid2,'%s',line); %# write the line to the new file
end
end
fclose(fid1);
fclose(fid2);
In the latest release of Google Play, Google removed the need to ask permission for internet as "most apps need it anyways nowadays". However, for users who have older versions, it is still recommended to leave the code below in your manifest
<uses-permission android:name="android.permission.INTERNET" />
#Creating dictionary
animals = {"Cat" : "Pat", "Dog" : "Pat", "Tiger" : "Wild"}
#Convert dictionary to list (array)
keys = list(animals)
#Printing 1st dictionary key by index
print(keys[0])
#Done :)
IMHO the best option is to use YAML's native block scalars. Specifically in this case, the folded style block.
By invoking sh -c
you can pass arguments to your container as commands, but if you want to elegantly separate them with newlines, you'd want to use the folded style block, so that YAML will know to convert newlines to whitespaces, effectively concatenating the commands.
A full working example:
apiVersion: v1
kind: Pod
metadata:
name: myapp
labels:
app: myapp
spec:
containers:
- name: busy
image: busybox:1.28
command: ["/bin/sh", "-c"]
args:
- >
command_1 &&
command_2 &&
...
command_n
Up to and including OS X v10.7 (Lion) you can set them in:
~/.MacOSX/environment.plist
See:
For PATH in the Terminal, you should be able to set in .bash_profile
or .profile
(you'll probably have to create it though)
For OS X v10.8 (Mountain Lion) and beyond you need to use launchd
and launchctl
.
There are three different font families that I know of that you can choose from and each has its own weight element that needs to be applied:
First
font-family: 'Font Awesome 5 Brands';
content: "\f373";
Second
font-family: 'Font Awesome 5 Free';
content: "\f061";
font-weight: 900;
Third
font-family: 'Font Awesome 5 Pro';
Reference here - https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements
Hope this helps.
Assuming you're getting norm
from scipy.stats
, you probably just need to sort your list:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial
And so I get:
One way to do this if dealing with sorted range index is:
data = data.sort_index(ascending=False)
This approach has the benefits of (1) being a single line, (2) not requiring a utility function, and most importantly (3) not actually changing any of the data in the dataframe.
Caveat: this works by sorting the index in descending order and so may not always be appropriate or generalize for any given Dataframe.
Follow all the steps.
Step 1: initialize git
$ git init
Step 2: Check files are exist or not.
$git ls
Step 3 : Add the file
$git add filename
Step 4: Add comment to show
$git commit -m "your comment"
Step 5: Link to your repository
$git remote add origin "copy repository link and paste here"
Step 6: Push on Git
$ git push -u origin master
Here is the best answer that I have found on the Microsoft Excel Support Team Blog
For some users, Forms Controls (FM20.dll) are no longer working as expected after installing December 2014 updates. Issues are experienced at times such as when they open files with existing VBA projects using forms controls, try to insert a forms control in to a new worksheet or run third party software that may use these components.
You may received errors such as:
"Cannot insert object" "Object library invalid or contains references to object definitions that could not be found"
Additionally, you may be unable to use or change properties of an ActiveX control on a worksheet or receive an error when trying to refer to an ActiveX control as a member of a worksheet via code. Steps to follow after the update:
To resolve this issue, you must delete the cached versions of the control type libraries (extender files) on the client computer. To do this, you must search your hard disk for files that have the ".exd" file name extension and delete all the .exd files that you find. These .exd files will be re-created automatically when you use the new controls the next time that you use VBA. These extender files will be under the user's profile and may also be in other locations, such as the following:
%appdata%\Microsoft\forms
%temp%\Excel8.0
%temp%\VBE
Scripting solution:
Because this problem may affect more than one machine, it is also possible to create a scripting solution to delete the EXD files and run the script as part of the logon process using a policy. The script you would need should contain the following lines and would need to be run for each USER as the .exd files are USER specific.
del %temp%\vbe\*.exd
del %temp%\excel8.0\*.exd
del %appdata%\microsoft\forms\*.exd
del %appdata%\microsoft\local\*.exd
del %appdata%\Roaming\microsoft\forms\*.exd
del %temp%\word8.0\*.exd
del %temp%\PPT11.0\*.exd
Additional step:
If the steps above do not resolve your issue, another step that can be tested (see warning below):
On a fully updated machine and after removing the .exd files, open the file in Excel with edit permissions.
Open Visual Basic for Applications > modify the project by adding a comment or edit of some kind to any code module > Debug > Compile VBAProject.
Save and reopen the file. Test for resolution. If resolved, provide this updated project to additional users.
Warning: If this step resolves your issue, be aware that after deploying this updated project to the other users, these users will also need to have the updates applied on their systems and .exd files removed as well.
If this does not resolve your issue, it may be a different issue and further troubleshooting may be necessary.
Microsoft is currently working on this issue. Watch the blog for updates.
So I wanted to do something slightly different: a border on the bottom ONLY, to simulate a ListView divider. I modified Piet Delport's answer and got this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape
android:shape="rectangle">
<solid android:color="@color/background_trans_light" />
</shape>
</item>
<!-- this mess is what we have to do to get a bottom border only. -->
<item android:top="-2dp"
android:left="-2dp"
android:right="-2dp"
android:bottom="1px">
<shape
android:shape="rectangle">
<stroke android:width="1dp" android:color="@color/background_trans_mid" />
<solid android:color="@null" />
</shape>
</item>
</layer-list>
Note using px instead of dp to get exactly 1 pixel divider (some phone DPIs will make a 1dp line disappear).
If you are running in Android 29 then you have to use scoped storage or for now, you can bypass this issue by using:
android:requestLegacyExternalStorage="true"
in manifest in the application tag.
Plain bash one liner
$ cat > /tmp/test
1
2
3
4
5
^D
$ echo $(( $(cat /tmp/test | tr "\n" "+" ) 0 ))
This is a definitive un-answer: eliminating a tempting-but-wrong answer to help others navigate toward correct answers.
It might seem like debugging would highlight the problem. However, the only browser the problem occurs in is IE, and in IE you can only debug code that was part of the original document. For dynamically added code, the debugger just shows the body element as the current instruction, and IE claims the error happened on a huge line number.
Here's a sample web page that will demonstrate this problem in IE:
<html>
<head>
<title>javascript debug test</title>
</head>
<body onload="attachScript();">
<script type="text/javascript">
function attachScript() {
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
document.body.appendChild(s);
s.text = "var a = document.getElementById('nonexistent'); alert(a.tagName);"
}
</script>
</body>
This yielded for me the following error:
Line: 54654408
Error: Object required
@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:
$rest = curl_exec($crl);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($crl));
}
curl_close($crl);
print_r($rest);
EDIT 1
To debug you can set CURLOPT_HEADER
to true to check HTTP response with firebug::net or similar.
curl_setopt($crl, CURLOPT_HEADER, true);
EDIT 2
About Curl error: SSL certificate problem, verify that the CA cert is OK
try adding this headers (just to debug, in a production enviroment you should keep these options in true
):
curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
8.3.5.8 If the type of a parameter includes a type of the form “pointer to array of unknown bound of T” or “reference to array of unknown bound of T,” the program is ill-formed
I ran into the same problem. It seems that setting the cell.textlabel.text
property brings the UILabel to the front of the contentView of the cell.
Add the textView after setting textLabel.text
, or (if that's not possible) call this:
[cell.contentView bringSubviewToFront:textField]
A terse solution using plain Javascript (thanks to Sygmoral for suggested improvements):
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
alert('left');
break;
case 39:
alert('right');
break;
}
};
Open the start menu and type cmd
into the search box
Hold Ctrl + Shift
and press Enter
This runs the Command Prompt in Administrator mode.
Now type regsvr32 MyComobject.dll
Just define:
#define M_PI acos(-1.0)
It should give you exact PI number that math functions are working with. So if they change PI value they are working with in tangent or cosine or sine, then your program should be always up-to-dated ;)
I agree with @zzzzBov's answer, but the "fail fast" advantage of Promise.all
is not the only difference. Some users in the comments have asked why using Promise.all
is worth it when it's only faster in the negative scenario (when some task fails). And I ask, why not? If I have two independent async parallel tasks and the first one takes a very long time to resolve but the second is rejected in a very short time, why leave the user to wait for the longer call to finish to receive an error message? In real-life applications we must consider the negative scenario. But OK - in this first difference you can decide which alternative to use: Promise.all
vs. multiple await
.
But when considering error handling, YOU MUST use Promise.all
. It is not possible to correctly handle errors of async parallel tasks triggered with multiple await
s. In the negative scenario you will always end with UnhandledPromiseRejectionWarning
and PromiseRejectionHandledWarning
, regardless of where you use try/ catch. That is why Promise.all
was designed. Of course someone could say that we can suppress those errors using process.on('unhandledRejection', err => {})
and process.on('rejectionHandled', err => {})
but this is not good practice. I've found many examples on the internet that do not consider error handling for two or more independent async parallel tasks at all, or consider it but in the wrong way - just using try/ catch and hoping it will catch errors. It's almost impossible to find good practice in this.
TL;DR: Never use multiple await
for two or more independent async parallel tasks, because you will not be able to handle errors correctly. Always use Promise.all()
for this use case.
Async/ await
is not a replacement for Promises, it's just a pretty way to use promises. Async code is written in "sync style" and we can avoid multiple then
s in promises.
Some people say that when using Promise.all()
we can't handle task errors separately, and that we can only handle the error from the first rejected promise (separate handling can be useful e.g. for logging). This is not a problem - see "Addition" heading at the bottom of this answer.
Consider this async task...
const task = function(taskNum, seconds, negativeScenario) {
return new Promise((resolve, reject) => {
setTimeout(_ => {
if (negativeScenario)
reject(new Error('Task ' + taskNum + ' failed!'));
else
resolve('Task ' + taskNum + ' succeed!');
}, seconds * 1000)
});
};
When you run tasks in the positive scenario there is no difference between Promise.all
and multiple await
s. Both examples end with Task 1 succeed! Task 2 succeed!
after 5 seconds.
// Promise.all alternative
const run = async function() {
// tasks run immediate in parallel and wait for both results
let [r1, r2] = await Promise.all([
task(1, 5, false),
task(2, 5, false)
]);
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
// multiple await alternative
const run = async function() {
// tasks run immediate in parallel
let t1 = task(1, 5, false);
let t2 = task(2, 5, false);
// wait for both results
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
However, when the first task takes 10 seconds and succeeds, and the second task takes 5 seconds but fails, there are differences in the errors issued.
// Promise.all alternative
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, false),
task(2, 5, true)
]);
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// multiple await alternative
const run = async function() {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
We should already notice here that we are doing something wrong when using multiple await
s in parallel. Let's try handling the errors:
// Promise.all alternative
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, false),
task(2, 5, true)
]);
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: Caught error Error: Task 2 failed!
As you can see, to successfully handle errors, we need to add just one catch to the run
function and add code with catch logic into the callback. We do not need to handle errors inside the run
function because async functions do this automatically - promise rejection of the task
function causes rejection of the run
function.
To avoid a callback we can use "sync style" (async/ await
+ try/ catch)
try { await run(); } catch(err) { }
but in this example it's not possible, because we can't use await
in the main thread - it can only be used in async functions (because nobody wants to block main thread). To test if handling works in "sync style" we can call the run
function from another async function or use an IIFE (Immediately Invoked Function Expression: MDN):
(async function() {
try {
await run();
} catch(err) {
console.log('Caught error', err);
}
})();
This is the only correct way to run two or more async parallel tasks and handle errors. You should avoid the examples below.
// multiple await alternative
const run = async function() {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
We can try to handle errors in the code above in several ways...
try { run(); } catch(err) { console.log('Caught error', err); };
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled
... nothing got caught because it handles sync code but run
is async.
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
... huh? We see firstly that the error for task 2 was not handled and later that it was caught. Misleading and still full of errors in console, it's still unusable this way.
(async function() { try { await run(); } catch(err) { console.log('Caught error', err); }; })();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
... the same as above. User @Qwerty in his deleted answer asked about this strange behavior where an error seems to be caught but are also unhandled. We catch error the because run()
is rejected on the line with the await
keyword and can be caught using try/ catch when calling run()
. We also get an unhandled error because we are calling an async task function synchronously (without the await
keyword), and this task runs and fails outside the run()
function.
It is similar to when we are not able to handle errors by try/ catch when calling some sync function which calls setTimeout:
function test() {
setTimeout(function() {
console.log(causesError);
}, 0);
};
try {
test();
} catch(e) {
/* this will never catch error */
}`.
Another poor example:
const run = async function() {
try {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
}
catch (err) {
return new Error(err);
}
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
... "only" two errors (3rd one is missing) but nothing is caught.
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, true).catch(err => { console.log('Task 1 failed!'); throw err; }),
task(2, 5, true).catch(err => { console.log('Task 2 failed!'); throw err; })
]);
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Run failed (does not matter which task)!'); });
// at 5th sec: Task 2 failed!
// at 5th sec: Run failed (does not matter which task)!
// at 10th sec: Task 1 failed!
... note that in this example I rejected both tasks to better demonstrate what happens (throw err
is used to fire final error).
Pure shell solution:
% rm -f error.flag; echo hello world \
| (cat || echo "First command failed: $?" >> error.flag) \
| (cat || echo "Second command failed: $?" >> error.flag) \
| (cat || echo "Third command failed: $?" >> error.flag) \
; test -s error.flag && (echo Some command failed: ; cat error.flag)
hello world
And now with the second cat
replaced by false
:
% rm -f error.flag; echo hello world \
| (cat || echo "First command failed: $?" >> error.flag) \
| (false || echo "Second command failed: $?" >> error.flag) \
| (cat || echo "Third command failed: $?" >> error.flag) \
; test -s error.flag && (echo Some command failed: ; cat error.flag)
Some command failed:
Second command failed: 1
First command failed: 141
Please note the first cat fails as well, because it's stdout gets closed on it. The order of the failed commands in the log is correct in this example, but don't rely on it.
This method allows for capturing stdout and stderr for the individual commands so you can then dump that as well into a log file if an error occurs, or just delete it if no error (like the output of dd).
If you assume what you are sorting are just numbers and only their values identify/distinguish them (e.g. elements with same value are identicle), then the stability-issue of sorting is meaningless.
However, objects with same priority in sorting may be distinct, and sometime their relative order is meaningful information. In this case, unstable sort generates problems.
For example, you have a list of data which contains the time cost [T] of all players to clean a maze with Level [L] in a game. Suppose we need to rank the players by how fast they clean the maze. However, an additional rule applies: players who clean the maze with higher-level always have a higher rank, no matter how long the time cost is.
Of course you might try to map the paired value [T,L] to a real number [R] with some algorithm which follows the rules and then rank all players with [R] value.
However, if stable sorting is feasible, then you may simply sort the entire list by [T] (Faster players first) and then by [L]. In this case, the relative order of players (by time cost) will not be changed after you grouped them by level of maze they cleaned.
PS: of course the approach to sort twice is not the best solution to the particular problem but to explain the question of poster it should be enough.
Your code has two problems. One was identified and answered, but the other wasn't. The first was that your selector was missing the name of its parameter. However, even when you fix that, the line will still raise an exception, assuming your revised method signature still includes more than one argument. Let's say your revised method is declared as:
-(void)myTestWithString:(NSString *)sourceString comparedTo:(NSString *)testString ;
Creating selectors for methods that take multiple arguments is perfectly valid (e.g. @selector(myTestWithString:comparedTo:) ). However, the performSelector method only allows you to pass one value to myTest, which unfortunately has more than one parameter. It will error out and tell you that you didn't supply enough values.
You could always redefine your method to take a collection as it's only parameter:
-(void)myTestWithObjects:(NSDictionary *)testObjects ;
However, there is a more elegant solution (that doesn't require refactoring). The answer is to use NSInvocation, along with its setArgument:atIndex:
and invoke
methods.
I've written up an article, including a code example, if you want more details. The focus is on threading, but the basics still apply.
Good luck!
It sounds like you are talking about aggregation. Each instance of your player
class can contain zero or more instances of Airplane
, which, in turn, can contain zero or more instances of Flight
. You can implement this in Python using the built-in list
type to save you naming variables with numbers.
class Flight(object):
def __init__(self, duration):
self.duration = duration
class Airplane(object):
def __init__(self):
self.flights = []
def add_flight(self, duration):
self.flights.append(Flight(duration))
class Player(object):
def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
self.stock = stock
self.bank = bank
self.fuel = fuel
self.total_pax = total_pax
self.airplanes = []
def add_planes(self):
self.airplanes.append(Airplane())
if __name__ == '__main__':
player = Player()
player.add_planes()
player.airplanes[0].add_flight(5)
CSS Flexbox is well supported these days. Go here for a good tutorial on flexbox.
This works fine in all newer browsers:
#container {_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.block {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
background-color: #cccccc;_x000D_
margin: 10px; _x000D_
}
_x000D_
<div id="container">_x000D_
<div class="block">1</div> _x000D_
<div class="block">2</div> _x000D_
<div class="block">3</div> _x000D_
<div class="block">4</div> _x000D_
<div class="block">5</div> _x000D_
</div>
_x000D_
Some may ask why not use display: inline-block? For simple things it is fine, but if you got complex code within the blocks, the layout may not be correctly centered anymore. Flexbox is more stable than float left.
I noticed that Map should require special treatment, thus with all suggestions in this thread, code will be:
function deepClone( obj ) {
if( !obj || true == obj ) //this also handles boolean as true and false
return obj;
var objType = typeof( obj );
if( "number" == objType || "string" == objType ) // add your immutables here
return obj;
var result = Array.isArray( obj ) ? [] : !obj.constructor ? {} : new obj.constructor();
if( obj instanceof Map )
for( var key of obj.keys() )
result.set( key, deepClone( obj.get( key ) ) );
for( var key in obj )
if( obj.hasOwnProperty( key ) )
result[key] = deepClone( obj[ key ] );
return result;
}
As noted in this answer, you can check the value of document.activeElement
. document
is a global variable, so you don't have to do any magic to use it in your onBlur handler:
function myOnBlur(e) {
if(document.activeElement ===
document.getElementById('elementToCheckForFocus')) {
// Focus went where we expected!
// ...
}
}
just simple way
CREATE TRIGGER [dbo].[WO_EXECUTION_TRIU_RECORD] ON [dbo].[WO_EXECUTION]
WITH EXECUTE AS CALLER
FOR INSERT, UPDATE
AS
BEGIN
select @vars = [column] from inserted
IF UPDATE([column]) BEGIN
-- do update action base on @vars
END ELSE BEGIN
-- do insert action base on @vars
END
END
As many said - this version
int maxAge = context.Persons.Max(p => p.Age);
throws an exception when table is empty.
Use
int maxAge = context.Persons.Max(x => (int?)x.Age) ?? 0;
or
int maxAge = context.Persons.Select(x => x.Age).DefaultIfEmpty(0).Max()
echo "{$test}y";
You can use braces to remove ambiguity when interpolating variables directly in strings.
Also, this doesn't work with single quotes. So:
echo '{$test}y';
will output
{$test}y
add layout_gravity and gravity with center value on TextView
<TextView
android:text="welcome text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
/>
There is no need to write your own function to do this! Python has a built in clear function.
Type the following in the command prompt:
shell.clear()
If using IPython
for Windows, it's
cls()
You could do something like this:
Point newLoc = new Point(5,5); // Set whatever you want for initial location
for(int i=0; i < 10; ++i)
{
Button b = new Button();
b.Size = new Size(10, 50);
b.Location = newLoc;
newLoc.Offset(0, b.Height + 5);
Controls.Add(b);
}
If you want them to layout in any sort of reasonable fashion it would be better to add them to one of the layout panels (i.e. FlowLayoutPanel) or to align them yourself.
I have use mkcert to create infinites *.dev.net subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)
I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):
mkcert -install
mkcert localhost "*.dev.net"
This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)
localhost+1.pem
localhost+1-key.pem
Overwrite the XAMPP default certs:
copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem" C:\xampp\apache\conf\ssl.key\server.key
Now, in Apache2 for Debian 10, activate SSL & vhost_alias
a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2
For vhost_alias add this Apache2 config:
nano /etc/apache2/sites-available/999-vhosts_alias.conf
With this content:
<VirtualHost *:80>
UseCanonicalName Off
ServerAlias *.dev.net
VirtualDocumentRoot "/var/www/html/%0/"
</VirtualHost>
Add the site:
a2ensite 999-vhosts_alias
Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:
systemctl stop apache2
mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak
cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key
chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key
systemctl start apache2
Edit the SSL config
nano /etc/apache2/sites-enabled/default-ssl.conf
At the start edit the file with this content:
<IfModule mod_ssl.c>
<VirtualHost *:443>
UseCanonicalName Off
ServerAlias *.dev.net
ServerAdmin webmaster@localhost
# DocumentRoot /var/www/html/
VirtualDocumentRoot /var/www/html/%0/
...
Last restart:
systemctl restart apache2
NOTE: don´t forget to create the folders for your subdomains in /var/www/html/
/var/www/html/subdomain1.dev.net
/var/www/html/subdomain2.dev.net
/var/www/html/subdomain3.dev.net
Save the commands in a .SQL
file, ex: ClearTables.sql
, say in your C:\temp
folder.
Contents of C:\Temp\ClearTables.sql
Delete from TableA;
Delete from TableB;
Delete from TableC;
Delete from TableD;
Delete from TableE;
Then use sqlcmd
to execute it as follows. Since you said the database is remote, use the following syntax (after updating for your server and database instance name).
sqlcmd -S <ComputerName>\<InstanceName> -i C:\Temp\ClearTables.sql
For example, if your remote computer name is SQLSVRBOSTON1 and Database instance name is MyDB1, then the command would be.
sqlcmd -E -S SQLSVRBOSTON1\MyDB1 -i C:\Temp\ClearTables.sql
Also note that -E
specifies default authentication. If you have a user name and password to connect, use -U
and -P
switches.
You will execute all this by opening a CMD
command window.
Using a Batch File.
If you want to save it in a batch file and double-click to run it, do it as follows.
Create, and save the ClearTables.bat
like so.
echo off
sqlcmd -E -S SQLSVRBOSTON1\MyDB1 -i C:\Temp\ClearTables.sql
set /p delExit=Press the ENTER key to exit...:
Then double-click it to run it. It will execute the commands and wait until you press a key to exit, so you can see the command output.
This is a list of what String.format
can do. The same goes for printf
int i = 123;
o.printf( "|%d|%d|%n" , i, -i ); // |123|-123|
o.printf( "|%5d|%5d|%n" , i, -i ); // | 123| –123|
o.printf( "|%-5d|%-5d|%n" , i, -i ); // |123 |-123 |
o.printf( "|%+-5d|%+-5d|%n" , i, -i ); // |+123 |-123 |
o.printf( "|%05d|%05d|%n%n", i, -i ); // |00123|-0123|
o.printf( "|%X|%x|%n", 0xabc, 0xabc ); // |ABC|abc|
o.printf( "|%04x|%#x|%n%n", 0xabc, 0xabc ); // |0abc|0xabc|
double d = 12345.678;
o.printf( "|%f|%f|%n" , d, -d ); // |12345,678000| |-12345,678000|
o.printf( "|%+f|%+f|%n" , d, -d ); // |+12345,678000| |-12345,678000|
o.printf( "|% f|% f|%n" , d, -d ); // | 12345,678000| |-12345,678000|
o.printf( "|%.2f|%.2f|%n" , d, -d ); // |12345,68| |-12345,68|
o.printf( "|%,.2f|%,.2f|%n" , d, -d ); // |12.345,68| |-12.345,68|
o.printf( "|%.2f|%(.2f|%n", d, -d ); // |12345,68| |(12345,68)|
o.printf( "|%10.2f|%10.2f|%n" , d, -d ); // | 12345,68| | –12345,68|
o.printf( "|%010.2f|%010.2f|%n",d, -d ); // |0012345,68| |-012345,68|
String s = "Monsterbacke";
o.printf( "%n|%s|%n", s ); // |Monsterbacke|
o.printf( "|%S|%n", s ); // |MONSTERBACKE|
o.printf( "|%20s|%n", s ); // | Monsterbacke|
o.printf( "|%-20s|%n", s ); // |Monsterbacke |
o.printf( "|%7s|%n", s ); // |Monsterbacke|
o.printf( "|%.7s|%n", s ); // |Monster|
o.printf( "|%20.7s|%n", s ); // | Monster|
Date t = new Date();
o.printf( "%tT%n", t ); // 11:01:39
o.printf( "%tD%n", t ); // 04/18/08
o.printf( "%1$te. %1$tb%n", t ); // 18. Apr
It seems to be a long-running framework process for debugging (to decrease load times?). I discovered that when you start your application twice from the debugger often the same vshost.exe process will be used. It just unloads all user-loaded DLLs first. This does odd things if you are fooling around with API hooks from managed processes.
Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe
The code is simple, just type:
import pyarrow.parquet as pq
df = pq.read_table(source=your_file_path).to_pandas()
For more information, see the document from Apache pyarrow Reading and Writing Single Files
Let PowerShell analyze and decide the data type. It internally uses a 'Variant' for this.
And generally it does a good job...
param($x)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $x
}
Or if you need to pass multiple parameters:
param($x1, $x2)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $x1
$iTunes.<AnyProperty> = $x2
}
You can also cast an array to a string like...
newStr = String(aa);
I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.
I have not seen this mentioned here, so I am putting it out there in case someone needs it. If all you want to do is to make sure that your subprocess terminates successfully, you could put it in a context manager. For example, I wanted my standard printer to print an out image and using the context manager ensured that the subprocess terminated.
import subprocess
with open(filename,'rb') as f:
img=f.read()
with subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE) as lpr:
lpr.stdin.write(img)
print('Printed image...')
I believe this method is also cross-platform.
In your app delegate use bellow code
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var currentToken: String?
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
application.registerForRemoteNotifications()
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
// Enable or disable features based on authorization.
if granted == true
{
print("Allow")
UIApplication.shared.registerForRemoteNotifications()
}
else
{
print("Don't Allow")
}
}
UNUserNotificationCenter.current().delegate = self
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
currentToken = token //get device token to delegate variable
}
public class var shared: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
}
Please refer to the glossary: hash()
is used as a shortcut to comparing objects, an object is deemed hashable if it can be compared to other objects. that is why we use hash()
. It's also used to access dict
and set
elements which are implemented as resizable hash tables in CPython.
hash()
function is an order of magnitude (or several) less expensive.If you read about how dictionaries are implemented, they use hash tables, which means deriving a key from an object is a corner stone for retrieving objects in dictionaries in O(1)
. That's however very dependent on your hash function to be collision-resistant. The worst case for getting an item in a dictionary is actually O(n)
.
On that note, mutable objects are usually not hashable. The hashable property means you can use an object as a key. If the hash value is used as a key and the contents of that same object change, then what should the hash function return? Is it the same key or a different one? It depends on how you define your hash function.
Imagine we have this class:
>>> class Person(object):
... def __init__(self, name, ssn, address):
... self.name = name
... self.ssn = ssn
... self.address = address
... def __hash__(self):
... return hash(self.ssn)
... def __eq__(self, other):
... return self.ssn == other.ssn
...
Please note: this is all based on the assumption that the SSN never changes for an individual (don't even know where to actually verify that fact from authoritative source).
And we have Bob:
>>> bob = Person('bob', '1111-222-333', None)
Bob goes to see a judge to change his name:
>>> jim = Person('jim bo', '1111-222-333', 'sf bay area')
This is what we know:
>>> bob == jim
True
But these are two different objects with different memory allocated, just like two different records of the same person:
>>> bob is jim
False
Now comes the part where hash() is handy:
>>> dmv_appointments = {}
>>> dmv_appointments[bob] = 'tomorrow'
Guess what:
>>> dmv_appointments[jim] #?
'tomorrow'
From two different records you are able to access the same information. Now try this:
>>> dmv_appointments[hash(jim)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in __eq__
AttributeError: 'int' object has no attribute 'ssn'
>>> hash(jim) == hash(hash(jim))
True
What just happened? That's a collision. Because hash(jim) == hash(hash(jim))
which are both integers btw, we need to compare the input of __getitem__
with all items that collide. The builtin int
does not have an ssn
attribute so it trips.
>>> del Person.__eq__
>>> dmv_appointments[bob]
'tomorrow'
>>> dmv_appointments[jim]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: <__main__.Person object at 0x7f611bd37110>
In this last example, I show that even with a collision, the comparison is performed, the objects are no longer equal, which means it successfully raises a KeyError
.
The behaviour is not really that strange. Looking into the implementation of the classes, it is caused by:
Charset.defaultCharset()
is not caching the determined character set in Java 5.Charset.defaultCharset()
again causes a second evaluation of the system property, no character set with the name "Latin-1" is found, so Charset.defaultCharset()
defaults to "UTF-8".OutputStreamWriter
is however caching the default character set and is probably used already during VM initialization, so that its default character set diverts from Charset.defaultCharset()
if the system property "file.encoding" has been changed at runtime.As already pointed out, it is not documented how the VM must behave in such a situation. The Charset.defaultCharset()
API documentation is not very precise on how the default character set is determined, only mentioning that it is usually done on VM startup, based on factors like the OS default character set or default locale.
Additionally you can use an app like AutoStart if you dont want to modify the code, to launch an android application at startup: AutoStart - No root
The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.
You want HttpRuntime.AppDomainAppPath
.
If you're in an HTTP request, you can also call Server.MapPath("~/Whatever")
.
I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.
I have a file "cost.ini" on the root of my class path. My JAR file is named "cost.jar".
The following code:
try {
//JDK11: replace "UTF-8" with UTF_8 and remove try-catch
String rootPath = decode(getSystemResource("cost.ini").getPath()
.replaceAll("(cost\\.jar!/)?cost\\.ini$|^(file\\:)?/", ""), "UTF-8");
showMessageDialog(null, rootPath, "rootpath", WARNING_MESSAGE);
} catch(UnsupportedEncodingException e) {}
Path returned from .getPath()
has the format:
file:/C:/folder1/folder2/cost.jar!/cost.ini
/C:/folder1/folder2/cost.ini
Every use of File
, leads on exception, if the application provided in JAR format.
In the early days...like before the 90s...the processors weren't able to do multi tasks that efficiently...coz a single processor could handle just a single task...so when we used to say that my antivirus,microsoft word,vlc,etc. softwares are all running at the same time...that isn't actually true. When I said a processor could handle a single process at a time...I meant it. It actually would process a single task...then it used to pause that task...take another task...complete it if its a short one or again pause it and add it to the queue...then the next. But this 'pause' that I mentioned was so small (appx. 1ns) that you didn't understand that the task has been paused. Eg. On vlc while listening to music there are other apps running simultaneously but as I told you...one program at a time...so the vlc is actually pausing in between for ns so you dont underatand it but the music is actually stopping in between.
But this was about the old processors...
Now-a- days processors ie 3rd gen pcs have multi cored processors. Now the 'cores' can be compared to a 1st or 2nd gen processors itself...embedded onto a single chip, a single processor. So now we understood what are cores ie they are mini processors which combine to become a processor. And each core can handle a single process at a time or multi threads as designed for the OS. And they folloq the same steps as I mentioned above about the single processor.
Eg. A i7 6gen processor has 8 cores...ie 8 mini processors in 1 i7...ie its speed is 8x times the old processors. And this is how multi tasking can be done.
There could be hundreds of cores in a single processor Eg. Intel i128.
I hope I explaned this well.
If you want to see only fatal runtime errors:
php_value display_errors on
php_value error_reporting 4
You could use stat() or the File::Stat module.
perldoc -f stat
Run ---> Debug Configuration ---> YourConfiguration ---> Arguments tab
If you have the database named archiedb
, use this:
mysql -p <password for the database> --databases archiedb > /home/database_backup.sql
Assuming this is Linux, choose where the backup file will be saved.
If you need to download only text file into String
you can use this simple way, Swift 5:
let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)
In case you want non optional result or error handling:
do {
let list = try String(contentsOf: URL(string: "https://example.com/file.txt")!)
}
catch {
// Handle error here
}
You should know that network operations may take some time, to prevent it from running in main thread and locking your UI, you may want to execute the code asynchronously, for example:
DispatchQueue.global().async {
let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)
}
As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
print(counter)
break
First we grab the command output, then wrap it and select one of its properties. There is only one and its "Name" which is what we want. So we select the groups property with ".name" then output it.
to text file
(Get-ADGroupMember 'Domain Admins' |Select name).name | out-file Admins1.txt
to csv
(Get-ADGroupMember 'Domain Admins' |Select name).name | export-csv -notypeinformation "Admins1.csv"
Often i reach for the abbreviation html tag in this situation.
<abbr title="Hover">Text</abbr>
https://stackoverflow.com/a/37191719/75579 answer stopped working for me in Android 7 somehow. So I have to do it the manual way, so I want to share it.
Put this snippet of code in your ~/.bash_profile
or ~/.profile
file:
snap_screen() {
if [ $# -eq 0 ]
then
name="screenshot.png"
else
name="$1.png"
fi
adb shell screencap -p /sdcard/$name
adb pull /sdcard/$name
adb shell rm /sdcard/$name
curr_dir=pwd
echo "save to `pwd`/$name"
}
Run source ~/.bash_profile
or source ~/.profile
command,
Usage without specifying filename:
$ snap_screen
11272 KB/s (256237 bytes in 0.022s)
Saved to /Users/worker8/desktop/screenshot.png
Usage with a filename:
$ snap_screen mega_screen_capture
11272 KB/s (256237 bytes in 0.022s)
Saved to /Users/worker8/desktop/mega_screen_capture.png
Hope it helps!
** This will not work if multiple devices are plugged in
These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.
jQuery.scrollTableBody (GitHub)
As long as you have a table with proper <thead>
, <tbody>
, and (optional) <tfoot>
, all you need to do is this:
$('table').scrollTableBody();
If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution
var Iframe = React.createClass({
render: function() {
return(
<div>
<iframe src={this.props.src} height={this.props.height} width={this.props.width}/>
</div>
)
}
});
ReactDOM.render(
<Iframe src="http://plnkr.co/" height="500" width="500"/>,
document.getElementById('example')
);
here live demo is available Demo
Simply add reference to P1 from P2
One possible could be like this,
HTML
<div class="box-left-mini">
<div class="front">this div is infront</div>
<div class="behind">
this div is behind
</div>
</div>
CSS
.box-left-mini{
float:left;
background-image:url(website-content/hotcampaign.png);
width:292px;
height:141px;
}
.front{
background-color:lightgreen;
}
.behind{
background-color:grey;
position:absolute;
width:100%;
height:100%;
top:0;
z-index:-1;
}
But it really depends on the layout of your div elements i.e. if they are floating, or absolute positioned etc.
ORDER BY article_rating ASC , article_time DESC
DESC
at the end will sort by both columns descending. You have to specify ASC
if you want it otherwise
You should try this command to determine pip's install location
Python 2
pip show six | grep "Location:" | cut -d " " -f2
Python 3
pip3 show six | grep "Location:" | cut -d " " -f2
Set the following CSS properties to the image:
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
They are likely still referenced by the project file. Make sure they are deleted using the Solution Explorer in Visual Studio - it should show them as being missing (with an exclamation mark).
This functions will also handle the floating numbers
$str = "Doughnuts, 4; doughnuts holes, 0.08; glue, 3.4";
$str = preg_replace('/[^0-9\.]/','-', $str);
$str = preg_replace('/(\-+)(\.\.+)/','-', $str);
$str = trim($str, '-');
$arr = explode('-', $str);
When you create the colorbar
try using the fraction and/or shrink parameters.
From the documents:
fraction 0.15; fraction of original axes to use for colorbar
shrink 1.0; fraction by which to shrink the colorbar
In java ,there is a rigorous way to convert a long to int
not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.
Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);
Windows7 FireFox/Chrome:
{
"cmd":["F:\\Program Files\\Mozilla Firefox\\firefox.exe","$file"]
}
just use your own path of firefox.exe or chrome.exe to replace mine.
Replace firefox.exe or chrome.exe with your own path.
Dictionary:
Hashtable:
JSF is a beast. I may be missing something, but I used to solve similar problems by saving the desired message to a property of the bean, and then displaying the property via an outputText:
<h:outputText
value="#{CreateNewPasswordBean.errorMessage}"
render="#{CreateNewPasswordBean.errorMessage != null}" />
FriendlyLog is another alternative. It works with Python 2 & 3 under Linux, Windows and MacOS.
var regex = /\d+/g;_x000D_
var string = "you can enter 30%-20% maximum 500 choices";_x000D_
var matches = string.match(regex); // creates array from matches_x000D_
_x000D_
document.write(matches);
_x000D_
I made it work by using -
toolbar.post(new Runnable() {
@Override
public void run() {
toolbar.setTitle("My Title");
}
});
Swift 3
Bold:
let bondFont = UIFont.boldSystemFont(ofSize:UIFont.labelFontSize)
Italic:
let italicFont = UIFont.italicSystemFont(ofSize:UIFont.labelFontSize)
I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.
import org.openqa.selenium.Keys;
String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);
element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field
I hope it helps..
The accepted answer here does not take into account the Kind of the DateTime instance. For example if your original DateTime instance was a UTC Kind then by making a new DateTime instance you will be making an Unknown Kind instance which will then be treated as local time based on server settings. Therefore the more proper way to get the first and last date of the month would be this:
var now = DateTime.UtcNow;
var first = now.Date.AddDays(-(now.Date.Day - 1));
var last = first.AddMonths(1).AddTicks(-1);
This way the original Kind of the DateTime instance is preserved.
Your inputs lack one important information of device dimension. Suppose now popular phone is 6 inch(the diagonal of the display), you will have following results
DPI: Dots per inch - number of dots(pixels) per segment(line) of 1 inch. DPI=Diagonal/Device size
Scaling Ratio= Real DPI/160. 160 is basic density (MHDPI)
DP: (Density-independent Pixel)=1/160 inch, think of it as a measurement unit
Try this instead:
var responseObject = proxy.CallService(new RequestObject
{
Data = "misc. data",
Guid = new Guid.NewGuid()
});
This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).
When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):
Guid g1; // g1 is 00000000-0000-0000-0000-000000000000
Guid g2 = new Guid(); // g2 is 00000000-0000-0000-0000-000000000000
Guid g3 = default(Guid); // g3 is 00000000-0000-0000-0000-000000000000
Guid g4 = Guid.NewGuid(); // g4 is not all zeroes
Compare this to doing the same thing with an int:
int i1; // i1 is 0
int i2 = new int(); // i2 is 0
int i3 = default(int); // i3 is 0
DataSet resembles database. DataTable resembles database table, and DataRow resembles a record in a table. If you want to add filtering or sorting options, you then do so with a DataView object, and convert it back to a separate DataTable object.
If you're using database to store your data, then you first load a database table to a DataSet object in memory. You can load multiple database tables to one DataSet, and select specific table to read from the DataSet through DataTable object. Subsequently, you read a specific row of data from your DataTable through DataRow. Following codes demonstrate the steps:
SqlCeDataAdapter da = new SqlCeDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.SelectCommand = new SqlCommand(@"SELECT * FROM FooTable", connString);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];
foreach (DataRow dr in dt.Rows)
{
MessageBox.Show(dr["Column1"].ToString());
}
To read a specific cell in a row:
int rowNum // row number
string columnName = "DepartureTime"; // database table column name
dt.Rows[rowNum][columnName].ToString();
The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
Had the same problem , restarted xcode and it found my phone again.
You may be able to use the built-in function dir()
to produce similar behavior to PHP's isset()
, something like:
if 'foo' in dir(): # returns False, foo is not defined yet.
pass
foo = 'b'
if 'foo' in dir(): # returns True, foo is now defined and in scope.
pass
dir()
returns a list of the names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir.
Although you could easily find a tutorial how to handle file uploads with php, and there are functions (manual) to handle CSVs, I will post some code because just a few days ago I worked on a project, including a bit of code you could use...
HTML:
<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>
<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>
</form>
</table>
PHP:
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
//Print file details
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
//if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "uploaded_file.txt";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}
I know there must be an easier way to do this, but I read the CSV file and store the single cells of every record in an two dimensional array.
if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {
echo "File opened.<br />";
$firstline = fgets ($file, 4096 );
//Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
$num = strlen($firstline) - strlen(str_replace(";", "", $firstline));
//save the different fields of the firstline in an array called fields
$fields = array();
$fields = explode( ";", $firstline, ($num+1) );
$line = array();
$i = 0;
//CSV: one line is one record and the cells/fields are seperated by ";"
//so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
while ( $line[$i] = fgets ($file, 4096) ) {
$dsatz[$i] = array();
$dsatz[$i] = explode( ";", $line[$i], ($num+1) );
$i++;
}
echo "<table>";
echo "<tr>";
for ( $k = 0; $k != ($num+1); $k++ ) {
echo "<td>" . $fields[$k] . "</td>";
}
echo "</tr>";
foreach ($dsatz as $key => $number) {
//new table row for every record
echo "<tr>";
foreach ($number as $k => $content) {
//new table cell for every field of the record
echo "<td>" . $content . "</td>";
}
}
echo "</table>";
}
So I hope this will help, it is just a small snippet of code and I have not tested it, because I used it slightly different. The comments should explain everything.
A bit of explaining as to what that %2520
is :
The common space character is encoded as %20
as you noted yourself.
The %
character is encoded as %25
.
The way you get %2520
is when your url already has a %20
in it, and gets urlencoded again, which transforms the %20
to %2520
.
Are you (or any framework you might be using) double encoding characters?
Edit:
Expanding a bit on this, especially for LOCAL links. Assuming you want to link to the resource C:\my path\my file.html
:
%
is a valid filename character and as such it will be encoded) when converting to a proper URL (see next point).file://
protocol, you are basically stating that you have taken all precautions and encoded what needs encoding, the rest should be treated as special characters. In the above example, you should thus provide file:///c:/my%20path/my%20file.html
. Aside from fixing slashes, clients should not encode characters here.NOTES:
/
are used in URLs, reverse slashes \
in Windows paths, but most clients will work with both by converting them to the proper forward slash. file://localhost/c:/my%20path/my%file.html
), but again most clients will work without the host part (ie two slashes only) by assuming you mean the local machine and adding the third slash.Most likely you're looking for the ToCharArray() method. However, you will need to do slightly more work if a string[]
is required, as you noted in your post.
string str = "this is a test.";
char[] charArray = str.ToCharArray();
string[] strArray = str.Select(x => x.ToString()).ToArray();
Edit: If you're worried about the conciseness of the conversion, I suggest you make it into an extension method.
public static class StringExtensions
{
public static string[] ToStringArray(this string s)
{
if (string.IsNullOrEmpty(s))
return null;
return s.Select(x => x.ToString()).ToArray();
}
}
To plot multiple graphs on the same figure you will have to do:
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plotting t, c separately
plt.show()
My case I used pyCharm 5 on mac. I also had this problem and after running this command my problem was solved
sudo pip install django --upgrade
You want to look into 'Splash' Screens.
Display another 'Splash' form and wait until the processing is done.
Here is an example on how to do it.
You can use lodash module to check value is null or undefined
_.isNil(value)
Example
country= "Abc"
_.isNil(country)
//false
state= null
_.isNil(state)
//true
city= undefined
_.isNil(state)
//true
pin= true
_.isNil(pin)
// false
Reference link: https://lodash.com/docs/#isNil
There's a function std::reverse
in the algorithm
header for this purpose.
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a;
std::reverse(a.begin(), a.end());
return 0;
}
Add to pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
first of all in onCreate Function add the following line
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and then add the following function in the code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
You need to install the package first.
npm install --save react-fontawesome
OR
npm i --save @fortawesome/react-fontawesome
Don't forget to use className
instead of class
.
Later on you need to import them in the file where you wanna use them.
import 'font-awesome/css/font-awesome.min.css'
or
import FontAwesomeIcon from '@fortawesome/react-fontawesome'
The best approach to use yum and update your devtoolset is to utilize the CentOS SCLo RH Testing repository.
yum install centos-release-scl-rh
yum --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc devtoolset-7-gcc-c++
Many additional packages are also available, to see them all
yum --enablerepo=centos-sclo-rh-testing list devtoolset-7*
You can use this method to install any dev tool version, just swap the 7 for your desired version. devtoolset-6-gcc, devtoolset-5-gcc etc.
You can use this Firefox addon to download all files in HTTP Directory.
https://addons.mozilla.org/en-US/firefox/addon/http-directory-downloader/
You can set up Maven's Surefire to run unit tests and integration tests separately. In the standard unit test phase you run everything that does not pattern match an integration test. You then create a second test phase that runs just the integration tests.
Here is an example:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>test</goal>
</goals>
<phase>integration-test</phase>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
As of rails 5
you can also use rails
instead of rake
Rails 3 - 4
# < rails-5.0
rake db:migrate:up VERSION=20160920130051
Rails 5
# >= rails-5.0
rake db:migrate:up VERSION=20160920130051
# or
rails db:migrate:up VERSION=20160920130051
Hope below Oracle query will work.
Select First_column,LISTAGG(second_column,',')
WITHIN GROUP (ORDER BY second_column) as Sec_column,
LISTAGG(third_column,',')
WITHIN GROUP (ORDER BY second_column) as thrd_column
FROM tablename
GROUP BY first_column
You can use following as well
<string name="spelatonertext3"> "-4, 5, -5, 6, -6, "> </string>
Put anything in " "
(quotation) with space, and it should work
The most simple way of changing the foreground and background colour of a progress bar is
<ProgressBar
style="@android:style/Widget.ProgressBar.Horizontal"
android:id="@+id/pb_main"
android:layout_width="match_parent"
android:layout_height="8dp"
android:progress="30"
android:progressTint="#82e9de"
android:progressBackgroundTint="#82e9de"
/>
just add
android:progressTint="#82e9de" //for foreground colour
android:progressBackgroundTint="#82e9de" //for background colour
A little late but I was having this problem too and running studio as root just created more problems (using OSX here).
I fixed it by manually installing what was failing to install using the Android SDK manager. Just run android sdk
in a terminal (probably the same on Windows but don't quote me). Let it install all the updates it wants, then if you can't make it through the setup, manually find the packages that are failing to install and install them.
Got me through a very frustrating problem and back to work.....
As far as I know, it can be done. Python has implicit line continuation (inside parentheses, brackets, and strings) for triple-quoted strings ("""like this"""
)and the indentation of continuation lines is not important. For more info, you may want to read this article on lexical analysis, from python.org.
To supplement @artfulrobot's answer, if you want to show changed files between two branches:
git diff --name-status mybranch..myotherbranch
Be careful on precedence. If you place the newer branch first then it would show files as deleted rather than added.
Adding a grep
can refine things further:
git diff --name-status mybranch..myotherbranch | grep "A\t"
That will then show only files added in myotherbranch
.
The element hasn't been appended yet, therefore it is equal to null. The Id will never = 0. When you call getElementById(id), it is null since it is not a part of the dom yet unless your static id is already on the DOM. Do a call through the console to see what it returns.
It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None
differently from is None
.
In particular the output of a == None
does not even have to be boolean !! - a frequent cause of bugs.
For a specific example take a numpy array where the ==
comparison is implemented elementwise:
import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False
I had a similar issue, where I had one div holding the image, and one div holding the text. The reason mine wasn't working, was that the div holding the image had display: inline-block
while the div holding the text had display: inline
.
I changed it to both be display: inline
and it worked.
Here's a solution for a basic header section with a logo, title and tagline:
HTML
<div class="site-branding">
<div class="site-branding-logo">
<img src="add/Your/URI/Here" alt="what Is The Image About?" />
</div>
</div>
<div class="site-branding-text">
<h1 id="site-title">Site Title</h1>
<h2 id="site-tagline">Site Tagline</h2>
</div>
CSS
div.site-branding { /* Position Logo and Text */
display: inline-block;
vertical-align: middle;
}
div.site-branding-logo { /* Position logo within site-branding */
display: inline;
vertical-align: middle;
}
div.site-branding-text { /* Position text within site-branding */
display: inline;
width: 350px;
margin: auto 0;
vertical-align: middle;
}
div.site-branding-title { /* Position title within text */
display: inline;
}
div.site-branding-tagline { /* Position tagline within text */
display: block;
}
Yes.
public class IncrementTest extends TestCase {
public void testPreIncrement() throws Exception {
int i = 0;
int j = i++;
assertEquals(0, j);
assertEquals(1, i);
}
public void testPostIncrement() throws Exception {
int i = 0;
int j = ++i;
assertEquals(1, j);
assertEquals(1, i);
}
}
export a=$(script.sh)
Hope this helps. Note there are no spaces between variable and =. To echo the output
echo $a
Hey, I have the same issue on Mac working on a Cocoa C# solution. (But I solved it !)
It always say that the root element is missing so it cannot load my C# project file.
I have the 2017 Visual Studio Mac Community Edition. I finally managed to find a solution after several hours (painful!).
My solution is because the frameworks related to the Visual Studio are old or broken. I found this because I tried to create a new Mac solution by Cocoa and it said "failed to save the solution". Then, I tried to create an Android Solution and it is working fine. Go to your "Finder" and "Go" -> "Go to a Folder" then go to the "Library/Frameworks". I have deleted mono.framework and frameworks related to Xamarin because I believe these Xamarin frameworks are broken.
Then, uninstalled the Visual Studio and reinstalled it. Now everything works fine!
Here is a simple php script for login and a page that can only be accessed by logged in users.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:index.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php ( only logged in users can access it )
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
?>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
This is admin page view able only by logged in users.
</body>
</html>
The fact that the previously accepted answer refers to php 5.3.6, while the current version of MAMP ships with 7.2.1 as the default (as of early 2018), points out that this is not a very sustainable solution. You can make your path update automatically by adding an extra line to your .bash_profile
or .zshrc
to get the latest version of PHP from /Applications/MAMP/bin/php/
and export that to your path. Here’s how I do it:
# Use MAMP version of PHP
PHP_VERSION=`command ls /Applications/MAMP/bin/php/ | sort -n | tail -1`
export PATH=/Applications/MAMP/bin/php/${PHP_VERSION}/bin:$PATH
(Use source ~/.bash_profile
after making your changes to make sure they take effect.)
As others have mentioned, you will likely also want to modify your shell to use MAMP’s mysql executable, which is located in /Applications/MAMP/Library/bin
. However, I do not recommend exporting that folder, because there are a bunch of other executables there, like libtool
, that you probably don’t want to be giving priority to over your system installed versions. This issue prevented me from installing a node package recently (libxmljs), as documented here.
My solution was to define and export mysql
and mysqladmin
as functions:
# Export MAMP MySQL executables as functions
# Makes them usable from within shell scripts (unlike an alias)
mysql() {
/Applications/MAMP/Library/bin/mysql "$@"
}
mysqladmin() {
/Applications/MAMP/Library/bin/mysqladmin "$@"
}
export -f mysql
export -f mysqladmin
I used functions instead of aliases, because aliases don’t get passed to child processes, or at least not in the context of a shell script. The only downside I’ve found is that running which mysql
and which mysqladmin
will no longer return anything, which is a bummer. If you want to check which mysql is being used and make sure everything is copacetic, use mysql --version
instead.
Note: @julianromera points out that zsh doesn’t support exporting functions, so in that case, you’re best off using an alias, like alias mysql='/Applications/MAMP/Library/bin/mysql'
. Just be aware that your aliases might not be available from subshells (like when executing a shell script).
Yes you can change the on / off button
android:textOn="Light ON"
android:textOff="Light OFF"
Refer for more
http://androidcoding.in/2016/09/11/android-tutorial-toggle-button
None of these worked for me.. they return as true, even when they aren't. The problem is, you have to test the available permission against the current process user rights, this tests for file creation rights, just change the FileSystemRights clause to 'Write' to test write access..
/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full directory path</param>
/// <returns>State [bool]</returns>
public static bool DirectoryCanCreate(string DirectoryPath)
{
if (string.IsNullOrEmpty(DirectoryPath)) return false;
try
{
AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
foreach (FileSystemAccessRule rule in rules)
{
if (identity.Groups.Contains(rule.IdentityReference))
{
if ((FileSystemRights.CreateFiles & rule.FileSystemRights) == FileSystemRights.CreateFiles)
{
if (rule.AccessControlType == AccessControlType.Allow)
return true;
}
}
}
}
catch {}
return false;
}
Please be aware that if you are running the tsc command with a file name ie:
tsc testfile.ts
then the tsconfig.json compiler configuration file is ignored. The solution is to run either the tsc command on its own, in which case all .ts files in the directory will be compiled, unless you have edited the tsconfig.json to include a set of files.
see 'using the files property'... https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
You need to set the path for the preprocessor to search for these include files, if they are not in the project folder.
You can set the path in VC++ Directories, or in Additional Include Directories. Both are found in project settings.
Here's a macro that allows you to shuffle selected cells in a column:
Option Explicit
Sub ShuffleSelectedCells()
'Do nothing if selecting only one cell
If Selection.Cells.Count = 1 Then Exit Sub
'Save selected cells to array
Dim CellData() As Variant
CellData = Selection.Value
'Shuffle the array
ShuffleArrayInPlace CellData
'Output array to spreadsheet
Selection.Value = CellData
End Sub
Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim J As Long, _
N As Long, _
Temp As Variant
'Randomize
For N = LBound(InArray) To UBound(InArray)
J = CLng(((UBound(InArray) - N) * Rnd) + N)
If J <> N Then
Temp = InArray(N, 1)
InArray(N, 1) = InArray(J, 1)
InArray(J, 1) = Temp
End If
Next N
End Sub
You can read the comments to see what the macro is doing. Here's how to install the macro:
Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).
Your JSON should look like this:
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
You can loop over the Array like this:
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.id);
}
Or like this (suggested from Eric) be careful with IE support
json.forEach(function(obj) { console.log(obj.id); });
I had the same problem because .htaccess
has incorrect settings:
RewriteEngine on
RewriteRule !.(js|gif|jpg|png|css)$ index.php
I solved this by modifying the file:
RewriteEngine on
RewriteRule !.(js|gif|jpg|png|css|eot|svg|ttf|woff|woff2|map)$ index.php
I recently started using VMWare Octant https://github.com/vmware-tanzu/octant. This is a better UI than the Kubernetes Dashboard. You can view the Kubernetes cluster and look at the details of the cluster and the PODS. This will allow you to check the logs and open a terminal into the POD(s).
Just for anyone who still has an issue, I also had an issue where I typed ngif
rather than ngIf
(notice the capital 'I').
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
If it concerns just one (or a few) specific vars you want to change, I think the easiest way is a workaround: just set in in your environment AND in your current console session
I have this simple batch script to change my Maven from Java7 to Java8 (which are both env. vars) The batch-folder is in my PATH var so I can always call 'j8' and within my console and in the environment my JAVA_HOME var gets changed:
j8.bat:
@echo off
set JAVA_HOME=%JAVA_HOME_8%
setx JAVA_HOME "%JAVA_HOME_8%"
Till now I find this working best and easiest. You probably want this to be in one command, but it simply isn't there in Windows...
On Mac you can do Press 'Command' and '+' buttons to zoom in. press 'Command' and '-' buttons to zoom out.