Slightly more "Angular way" would be to use the straightforward limitTo
filter, as natively provided by Angular:
<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp | limitTo:quantity">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
app.controller('PhoneListCtrl', function($scope, $http) {
$http.get('phones.json').then(
function(phones){
$scope.phones = phones.data;
}
);
$scope.orderProp = 'age';
$scope.quantity = 5;
}
);
You should probably use the ngHref directive along with the ngClick:
<a ng-href='#here' ng-click='go()' >click me</a>
Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
{{msg}}
<a ng-href='#here' ng-click='go()' >click me</a>
<div style='height:1000px'>
<a id='here'></a>
</div>
<h1>here</h1>
</body>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.go = function() {
$scope.msg = 'clicked';
}
});
I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.
** Update **
Here is a demo of the set and get working fine with a service.
http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, sharedProperties) {
$scope.name = 'World';
$scope.go = function(item) {
sharedProperties.setListName(item);
}
$scope.getItem = function() {
$scope.msg = sharedProperties.getListName();
}
});
app.service('sharedProperties', function () {
var list_name = '';
return {
getListName: function() {
return list_name;
},
setListName: function(name) {
list_name = name;
}
};
});
* Edit *
Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.
I had the same issue. The problem was because 'ng-controller' was defined twice (in routing and also in the HTML).
Start from index.html remove all #
from <a href="#/aboutus">About Us</a>
so it must look like <a href="/aboutus">About Us</a>
.Now in head tag of index.html write <base href="/">
just after last meta tag.
Now in your routing js inject $locationProvider
and write $locatonProvider.html5Mode(true);
Something Like This:-
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when("/home", {
templateUrl: "Templates/home.html",
controller: "homeController"
})
.when("/aboutus",{templateUrl:"Templates/aboutus.html"})
.when("/courses", {
templateUrl: "Templates/courses.html",
controller: "coursesController"
})
.when("/students", {
templateUrl: "Templates/students.html",
controller: "studentsController"
})
$locationProvider.html5Mode(true);
});
For more Details watch this video https://www.youtube.com/watch?v=XsRugDQaGOo
You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:
function PersonListCtrl($scope, $http) {
$scope.loadData = function () {
$http.get('/persons').success(function(data) {
$scope.persons = data;
});
};
//initial load
$scope.loadData();
}
then in your markup
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="loadData()">Refresh</button>
</div>
As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:
for example (just puedo code) in your controller:
$scope.addPerson = function() {
$scope.persons.push({ name: 'Test Monkey' });
};
Then you could use that in your view or whatever you'd want to do.
Since this is the top result for "angularjs unknown provider" on Google right now, here's another gotcha. When doing unit testing with Jasmine, make sure you have this statement in your beforeEach()
function:
module('moduleName');
Otherwise you'll get this same error in your tests.
I know this thread is old now but I am answering it to keep things a bit updated.
With Angular 1.4 and above you can directly use limitTo filter which apart from accepting the limit
parameter also accepts a begin
parameter.
Usage: {{ limitTo_expression | limitTo : limit : begin}}
So now you may not need to use any third party library to achieve something like pagination. I have created a fiddle to illustrate the same.
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
If your Manifest.xml
has the default android:theme="@style/AppTheme"
Go to res/values/styles.xml and change
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
And the ActionBar
is disappeared!
For the select tag, angular provides the ng-options directive. It gives you the specific framework to set up options and set a default. Here is the updated fiddle using ng-options that works as expected: http://jsfiddle.net/FxM3B/4/
Updated HTML (code stays the same)
<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.value as operator.displayName for operator in operators">
</select>
</body>
If don't like to add time picker, we can use just javascript for time part.
var dateObj=new Date();
var date = $.datepicker.formatDate('dd M yy', dateObj);
var time = dateObj.getHours()+":"+dateObj.getMinutes()+":"+dateObj.getSeconds();
console.log(date," ",time);
TL;DR Use Cmd/Ctrl+Shift+P
then Package Control: Install Package
, then Print to HTML
and install it. Use Alt+Shift+P
to print.
My favorite tool for printing from Sublime Text is Print to HTML package. You can "print" a selection or a whole file - via the web browser.
This opens your browser print dialog (Chrome for me) with the selected text neatly in the print dialog window and syntax highlighting intact. There you can choose a printer or export to PDF, and print.
Install the "Print to HTML" package using the package manager.
Ctrl + Shift + P
=> Gives a list of commands.install
"Package Control: Install Package
"print to
"Print to HTML
". Select that, and it is being installed.Alt+Shift+P
Note that -p
is an argument to the mkdir
command specifically, not the whole of Unix. Every command can have whatever arguments it needs.
In this case it means "parents", meaning mkdir
will create a directory and any parents that don't already exist.
Maybe my function can explain better how to do this in a simple way without loop, calculations and/or libs
function checkYearsDifference(birthDayDate){_x000D_
var todayDate = new Date();_x000D_
var thisMonth = todayDate.getMonth();_x000D_
var thisYear = todayDate.getFullYear();_x000D_
var thisDay = todayDate.getDate();_x000D_
var monthBirthday = birthDayDate.getMonth(); _x000D_
var yearBirthday = birthDayDate.getFullYear();_x000D_
var dayBirthday = birthDayDate.getDate();_x000D_
//first just make the difference between years_x000D_
var yearDifference = thisYear - yearBirthday;_x000D_
//then check months_x000D_
if (thisMonth == monthBirthday){_x000D_
//if months are the same then check days_x000D_
if (thisDay<dayBirthday){_x000D_
//if today day is before birthday day_x000D_
//then I have to remove 1 year_x000D_
//(no birthday yet)_x000D_
yearDifference = yearDifference -1;_x000D_
}_x000D_
//if not no action because year difference is ok_x000D_
}_x000D_
else {_x000D_
if (thisMonth < monthBirthday) {_x000D_
//if actual month is before birthday one_x000D_
//then I have to remove 1 year_x000D_
yearDifference = yearDifference -1;_x000D_
}_x000D_
//if not no action because year difference is ok_x000D_
}_x000D_
return yearDifference;_x000D_
}
_x000D_
Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df
def add5(x):
return x+5
df[['a', 'b']].apply(add5)
scanf()
and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:
#include <stdio.h>
#include <errno.h>
#include <stdbool.h>
int main(void)
{
char item[9], status;
FILE *fp;
if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
printf("No such file\n");
exit(1);
}
while (true) {
int ret = fscanf(fp, "%s %c", item, &status);
if(ret == 2)
printf("\n%s \t %c", item, status);
else if(errno != 0) {
perror("scanf:");
break;
} else if(ret == EOF) {
break;
} else {
printf("No match.\n");
}
}
printf("\n");
if(feof(fp)) {
puts("EOF");
}
return 0;
}
SOAP web service always make a POST operation whereas using REST you can choose specific HTTP methods like GET, POST, PUT, and DELETE.
Example: to get an item using SOAP you should create a request XML, but in the case of REST you can just specify the item id in the URL itself.
Requires Newtonsoft Json.Net
A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:
public List<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
{
JObject attributesAsJObject = dynamicToGetPropertiesFor;
Dictionary<string, object> values = attributesAsJObject.ToObject<Dictionary<string, object>>();
List<string> toReturn = new List<string>();
foreach (string key in values.Keys)
{
toReturn.Add(key);
}
return toReturn;
}
Then you simply foreach like this:
foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
{
dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
// And
dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
}
Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.
You need to install mysql server for your machine first. Once done, you will be able to add local db details to it.
For e.g. IP: 127.0.0.1
port: 3306
user: root
pass: pass of root which you have set
Here is the link on step by step guide for linux.
https://support.rackspace.com/how-to/install-mysql-server-on-the-ubuntu-operating-system/
It just needs to be in the classpath (aka make sure it ends up under /WEB-INF/classes in the .war as part of the build).
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
You can use the strtotime
and date
functions like this:
echo date('Y', strtotime('2068-06-15'));
Note however that PHP can handle year upto 2038
If your date is always in that format, you can also get the year like this:
$parts = explode('-', '2068-06-15');
echo $parts[0];
You can combine the check and cast into one statement:
let touch = object.anyObject() as UITouch
if let picker = touch.view as? UIPickerView {
...
}
Then you can use picker
within the if
block.
There is also a simple answer for defining specific styles that are only going to be applied to that specific button and you can have Jquery declare element style when declaring the dialog:
id: "button-delete",
text: "Delete",
style: "display: none;",
click: function () {}
after doing that here is what the html shows:
doing this allows you to set it, but it is not necessarily easy to change using jquery later.
You might want to try and set the supports-screens attribute:
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" >
</supports-screens>
The Wildfire has a small screen, and according to the documentation this attribute should default to "true" in all cases, but there are known issues with the supports-screens settings on different phones, so I would try this anyway.
Also - as David suggests - always compile and target against the most current version of the Android API, unless you have strong reasons not to. Pretty much every SDK prior to 2.2 has some serious issue or weird behavior; the latter SDK's help to resolve or cover up a lot (although not all) of them. You can (and should) use the Lint tool to check that your app remains compatible with API 4 when preparing a release.
You can get the maximum like this:
>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]]
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]].max(axis=1)
0 1
1 8
2 3
and so:
>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If you know that "A" and "B" are the only columns, you could even get away with
>>> df["C"] = df.max(axis=1)
And you could use .apply(max, axis=1)
too, I guess.
Here is a python solution using the pip install PyGithub
package
from github import Github
g = Github("youroauth key") #create token from settings page
for repo in g.get_user().get_repos():
if repo.name == "yourreponame":
releases = repo.get_releases()
for i in releases:
if i.tag_name == "yourtagname":
for j in i.get_assets():
print("{} date: {} download count: {}".format(j.name, j.updated_at, j._download_count.value))
class MyComponent extends Component {
constructor(props){
super(props)
this.myInput = React.createRef()
}
componentDidMount () {
console.log(this.myInput.current.offsetWidth)
}
render () {
return (
// new way - as of [email protected]
<div ref={this.myInput}>some elem</div>
// legacy way
// <div ref={(ref) => this.myInput = ref}>some elem</div>
)
}
}
An add-on to the previous answers since I came across this concern:
If you really want to insert something like 24-May-2005
to your DATE column, you could do something like this:
INSERT INTO someTable(Empid,Date_Joined)
VALUES
('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));
In the above query please note that if it's May
(ie: the month in letters) the format should be %M
.
NOTE: I tried this with the latest MySQL version 8.0 and it works!
Perhaps the pandas interface has changed since @Rutger answered, but in the version I'm using (0.15.2), the date_parser
function receives a list of dates instead of a single value. In this case, his code should be updated like so:
dateparse = lambda dates: [pd.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in dates]
df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)
try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b
jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
jQuery('#main').animate('opacity') = '0.6';
If you don't see the "Browse With..." option stop debugging first. =)
Use:
$filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd")
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat
A probable cause could be that you do not pass the command line parameters into the applications main method. I made the same mistake some weeks ago.
public static final void main(String... args) {
SpringApplication.run(Application.class, args);
}
Following works with MongoDB 3.6.0
Make sure you have these folders:
- C:\mongodb\data
- C:\mongodb\data\db
Then all you need are these commands:
- mongod --directoryperdb -dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongo.log --logappend --service --install
- net start MongoDB
- mongo
Add a third group by adding parens around .*
, then replace the subsequence with "number" + m.group(2) + "1"
. e.g.:
String output = m.replaceFirst("number" + m.group(2) + "1");
The more recent tidyverse
way is to use the mutate_at
function:
library(tidyverse)
library(magrittr)
set.seed(88)
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
cols <- c("A", "C", "D", "H")
data %<>% mutate_at(cols, funs(factor(.)))
str(data)
$ A: Factor w/ 4 levels "5","17","18",..: 2 1 4 3
$ B: int 36 35 2 26
$ C: Factor w/ 4 levels "22","31","32",..: 1 2 4 3
$ D: Factor w/ 4 levels "1","9","16","39": 3 4 1 2
$ E: int 3 14 30 38
$ F: int 27 15 28 37
$ G: int 19 11 6 21
$ H: Factor w/ 4 levels "7","12","20",..: 1 3 4 2
$ I: int 23 24 13 8
$ J: int 10 25 4 33
Android does not yet support full justification. We can use Webview and justify HTML instead of using textview. It works so fine. If you guys not clear, feel free to ask me :)
If you want to use reflection and set columns order/ include only some columns/ Exclude some columns try this:
private static DataTable ConvertToDataTable<T>(IList<T> data, string[] fieldsToInclude = null,
string[] fieldsToExclude = null)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
{
if ((fieldsToInclude != null && !fieldsToInclude.Contains(prop.Name)) ||
(fieldsToExclude != null && fieldsToExclude.Contains(prop.Name)))
continue;
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in data)
{
var atLeastOnePropertyExists = false;
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
if ((fieldsToInclude != null && !fieldsToInclude.Contains(prop.Name)) ||
(fieldsToExclude != null && fieldsToExclude.Contains(prop.Name)))
continue;
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
atLeastOnePropertyExists = true;
}
if(atLeastOnePropertyExists) table.Rows.Add(row);
}
if (fieldsToInclude != null)
SetColumnsOrder(table, fieldsToInclude);
return table;
}
private static void SetColumnsOrder(DataTable table, params String[] columnNames)
{
int columnIndex = 0;
foreach (var columnName in columnNames)
{
table.Columns[columnName].SetOrdinal(columnIndex);
columnIndex++;
}
}
If you need to display your variable unescaped, use this format:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[(${message})]*/ 'default';
/*]]>*/
</script>
Note the [(
brackets which wrap the variable.
Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();
You can use string.Split
and string.Join
:
string theString = "Some Very Large String Here";
var array = theString.Split(' ');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));
If you know you always only want to split off the first element, you can use:
var array = theString.Split(' ', 2);
This makes it so you don't have to join:
string restOfArray = array[1];
I think that all the answers missed a crucial point:
If you use the Ajax form so that it needs to update itself (and NOT another div outside of the form) then you need to put the containing div OUTSIDE of the form. For example:
<div id="target">
@using (Ajax.BeginForm("MyAction", "MyController",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target"
}))
{
<!-- whatever -->
}
</div>
Otherwise you will end like @David where the result is displayed in a new page.
In my case, I was getting this error when I serve the app, not when testing. I didn't realise I had a different configuration setting in my tsconfig.app.json file.
I previously had this:
{
...
"include": [
"src/**/*.ts"
]
}
It was including all my .spec.ts
files when serving the app. I changed the include property to
exclude` and added a regex to exclude all test files like this:
{
...
"exclude": [
"**/*.spec.ts",
"**/__mocks__"
]
}
Now it works as expected.
If you need more than 1 class
You can do this:
<i id="icon"
v-bind:class="{ 'fa fa-star': showStar }"
v-on:click="showStar = !showStar"
>
</i>
data: {
showStar: true
}
Notice the single quotes ' around the classes!
Thanks to everyone else's solutions.
From Business Intelligence Studio:
File->New Project->Integration Services Project
Now in solution explorer there is a SSIS Packages folder, right click it and select "Add Existing Package", and there will be a drop down that can be changed to File System, and the very bottom box allows you to browse to the file. Note that this will copy the file from where ever it is into the project's directory structure.
You can do the following. Add your ggplot code after the first line of code and end with dev.off()
.
tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()
res=300
specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.
Change width
and height
in the code above depending on the desired output.
Note that this also works for other R
plots including plot
, image
, and pheatmap
.
Other file formats
In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.
In my case it happen after excluding the resource folder from the pom
using the following code.
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>*/*.properties</exclude>
</excludes>
</resource>
</resources>
Commenting this code started my code.
Well in my case the data which I wanted to render contained an Object inside that of the array so due to this it was giving error, so for other people out there please check your data also once and if it contains an object, you need to convert it to array to print all of its values or if you need a specific value then use.
My data :
body: " d fvsdv"
photo: "http://res.cloudinary.com/imvr7/image/upload/v1591563988/hhanfhiyalwnv231oweg.png"
postedby: {_id: "5edbf948cdfafc4e38e74081", name: "vit"} //this is the object I am talking about.
title: "c sx "
__v: 0
_id: "5edd56d7e64a9e58acfd499f"
proto: Object
To Print only a single value
<h5>{item.postedby.name}</h5>
Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid
parts.
If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray()
and encode it. You'll need to Array.Reverse
the first three parts (Data1-3).
I do it this way:
var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);
See this answer for the specific .NET implementation details.
Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray()
.
The Java heap size limits for Windows are:
This doesn't help you getting a bigger Java heap, but now you know you can't go beyond these values.
Adding you a quick example using git plugin GitSCM:
checkout([
$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'CleanCheckout']],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: '<gitCredentials>', url: '<gitRepoURL>']]
])
in your pipeline
stage('checkout'){
steps{
script{
checkout
}
}
}
I am posting all at one place, all works for me to pad with 4 leading zero :)
declare @number int = 1;
print right('0000' + cast(@number as varchar(4)) , 4)
print right('0000' + convert(varchar(4), @number) , 4)
print right(replicate('0',4) + convert(varchar(4), @number) , 4)
print cast(replace(str(@number,4),' ','0')as char(4))
print format(@number,'0000')
You might be interested by https://github.com/pandas-ml/pandas-ml/
which implements a Python Pandas implementation of Confusion Matrix.
Some features:
Here is an example:
In [1]: from pandas_ml import ConfusionMatrix
In [2]: import matplotlib.pyplot as plt
In [3]: y_test = ['business', 'business', 'business', 'business', 'business',
'business', 'business', 'business', 'business', 'business',
'business', 'business', 'business', 'business', 'business',
'business', 'business', 'business', 'business', 'business']
In [4]: y_pred = ['health', 'business', 'business', 'business', 'business',
'business', 'health', 'health', 'business', 'business', 'business',
'business', 'business', 'business', 'business', 'business',
'health', 'health', 'business', 'health']
In [5]: cm = ConfusionMatrix(y_test, y_pred)
In [6]: cm
Out[6]:
Predicted business health __all__
Actual
business 14 6 20
health 0 0 0
__all__ 14 6 20
In [7]: cm.plot()
Out[7]: <matplotlib.axes._subplots.AxesSubplot at 0x1093cf9b0>
In [8]: plt.show()
In [9]: cm.print_stats()
Confusion Matrix:
Predicted business health __all__
Actual
business 14 6 20
health 0 0 0
__all__ 14 6 20
Overall Statistics:
Accuracy: 0.7
95% CI: (0.45721081772371086, 0.88106840959427235)
No Information Rate: ToDo
P-Value [Acc > NIR]: 0.608009812201
Kappa: 0.0
Mcnemar's Test P-Value: ToDo
Class Statistics:
Classes business health
Population 20 20
P: Condition positive 20 0
N: Condition negative 0 20
Test outcome positive 14 6
Test outcome negative 6 14
TP: True Positive 14 0
TN: True Negative 0 14
FP: False Positive 0 6
FN: False Negative 6 0
TPR: (Sensitivity, hit rate, recall) 0.7 NaN
TNR=SPC: (Specificity) NaN 0.7
PPV: Pos Pred Value (Precision) 1 0
NPV: Neg Pred Value 0 1
FPR: False-out NaN 0.3
FDR: False Discovery Rate 0 1
FNR: Miss Rate 0.3 NaN
ACC: Accuracy 0.7 0.7
F1 score 0.8235294 0
MCC: Matthews correlation coefficient NaN NaN
Informedness NaN NaN
Markedness 0 0
Prevalence 1 0
LR+: Positive likelihood ratio NaN NaN
LR-: Negative likelihood ratio NaN NaN
DOR: Diagnostic odds ratio NaN NaN
FOR: False omission rate 1 0
For Windows, it is quite easy to stop/kill flask server -
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
I had this problem too and for me, the problem was that I moved to a new server and the database I was trying to connect to with my PHP code changed from "my_Database" to "my_database".
Thank you Guys to give me many suggestions. Finally I got a solution. That is i have started the NetErrorPage intent two times. One time, i have checked the net connection availability and started the intent in page started event. second time, if the page has error, then i have started the intent in OnReceivedError event. So the first time dialog is not closed, before that the second dialog is called. So that i got a error.
Reason for the Error: I have called the showInfoMessageDialog method two times before closing the first one.
Now I have removed the second call and Cleared error :-).
You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.
Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.
In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.)
You can format the x-axis options with this menu. (Chart->Design->Layout)
Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"
Set up the options you wish. (Fix the starting and ending points.)
And you will get a graph such as the one below.
You can then tweak many of the options, label the axes better etc, but this should get you started.
Hope this helps you move forward.
In addition to the above explanations, what I experience:
app.use('/book', handler);
will match all requests beginning with '/book' as URL. so it also matches '/book/1' or '/book/2'
app.get('/book')
matches only GET request with exact match. It will not handle URLs like '/book/1' or '/book/2'
So, if you want a global handler that handles all of your routes, then app.use('/')
is the option. app.get('/')
will handle only the root URL.
This is how I make forms full screen.
private void button1_Click(object sender, EventArgs e)
{
int minx, miny, maxx, maxy;
inx = miny = int.MaxValue;
maxx = maxy = int.MinValue;
foreach (Screen screen in Screen.AllScreens)
{
var bounds = screen.Bounds;
minx = Math.Min(minx, bounds.X);
miny = Math.Min(miny, bounds.Y);
maxx = Math.Max(maxx, bounds.Right);
maxy = Math.Max(maxy, bounds.Bottom);
}
Form3 fs = new Form3();
fs.Activate();
Rectangle tempRect = new Rectangle(1, 0, maxx, maxy);
this.DesktopBounds = tempRect;
}
Since stop
is boolean you can change that part to:
//...
if(stop) // Or to: if (stop == true)
{
sb.append("y");
getWhoozitYs();
}
return sb.toString();
//...
Here is my experience:-
(Does not require any third-party library)
(Copy/paste of an answer I provided elsewhere)
Falling through switch
-case
s can be achieved by having no code in a case
(see case 0
), or using the special goto case
(see case 1
) or goto default
(see case 2
) forms:
switch (/*...*/) {
case 0: // shares the exact same code as case 1
case 1:
// do something
goto case 2;
case 2:
// do something else
goto default;
default:
// do something entirely different
break;
}
>>> import arrow
>>> now = arrow.utcnow().format('YYYY-MM-DDTHH:mm:ss.SSS')
>>> now
'2018-11-28T21:34:59.235'
>>> zulu = "{}Z".format(now)
>>> zulu
'2018-11-28T21:34:59.235Z'
Or, to get it in one fell swoop:
>>> zulu = "{}Z".format(arrow.utcnow().format('YYYY-MM-DDTHH:mm:ss.SSS'))
>>> zulu
'2018-11-28T21:54:49.639Z'
Why to annoy the user with three different Dialog Boxes to enter things, why not do all this in one go in a single Dialog and save time, instead of testing the patience of the USER ?
You can add everything in a single Dialog, by putting all the fields on your JPanel
and then adding this JPanel
to your JOptionPane
. Below code can clarify a bit more :
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class AverageExample
{
private double[] marks;
private JTextField[] marksField;
private JLabel resultLabel;
public AverageExample()
{
marks = new double[3];
marksField = new JTextField[3];
marksField[0] = new JTextField(10);
marksField[1] = new JTextField(10);
marksField[2] = new JTextField(10);
}
private void displayGUI()
{
int selection = JOptionPane.showConfirmDialog(
null, getPanel(), "Input Form : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.PLAIN_MESSAGE);
if (selection == JOptionPane.OK_OPTION)
{
for ( int i = 0; i < 3; i++)
{
marks[i] = Double.valueOf(marksField[i].getText());
}
Arrays.sort(marks);
double average = (marks[1] + marks[2]) / 2.0;
JOptionPane.showMessageDialog(null
, "Average is : " + Double.toString(average)
, "Average : "
, JOptionPane.PLAIN_MESSAGE);
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
// Do something here.
}
}
private JPanel getPanel()
{
JPanel basePanel = new JPanel();
//basePanel.setLayout(new BorderLayout(5, 5));
basePanel.setOpaque(true);
basePanel.setBackground(Color.BLUE.darker());
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
centerPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
JLabel mLabel1 = new JLabel("Enter Marks 1 : ");
JLabel mLabel2 = new JLabel("Enter Marks 2 : ");
JLabel mLabel3 = new JLabel("Enter Marks 3 : ");
centerPanel.add(mLabel1);
centerPanel.add(marksField[0]);
centerPanel.add(mLabel2);
centerPanel.add(marksField[1]);
centerPanel.add(mLabel3);
centerPanel.add(marksField[2]);
basePanel.add(centerPanel);
return basePanel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new AverageExample().displayGUI();
}
});
}
}
The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/"
(as I'm sure you know) means the replacement string is \/
, and (as you probably don't know) the replacement string \/
actually just inserts /
, because Java is weird, and gives \
a special meaning in the replacement string. (It's supposedly so that \$
will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:
"Hello/You/There".replaceAll("/", "\\\\/");
or:
"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));
is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):
It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.
A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.
{<interpolatedExpression>[,<alignment>][:<formatString>]}
Where:
The following code example concatenates a string where an object, author as a part of the string interpolation.
string author = "Mohit";
string hello = $"Hello {author} !";
Console.WriteLine(hello); // Hello Mohit !
Read more on C#/.NET Little Wonders: String Interpolation in C# 6
As of MySQL 8.0.18 This works fine for me
mysql> SET PASSWORD FOR 'user'@'localhost' = 'userpassword';
_x000D_
%Started Program or Command% | taskkill /F /IM cmd.exe
Example:
notepad.exe | taskkill /F /IM cmd.exe
I run into the same problem today, but unfortunately Andy's solution didn't work for me. In Spring Boot 1.2.1.RELEASE it's even easier, but you have to be aware of a few things.
Here is the interesting part from my application.yml
:
oauth:
providers:
google:
api: org.scribe.builder.api.Google2Api
key: api_key
secret: api_secret
callback: http://callback.your.host/oauth/google
providers
map contains only one map entry, my goal is to provide dynamic configuration for other OAuth providers. I want to inject this map into a service that will initialize services based on the configuration provided in this yaml file. My initial implementation was:
@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {
private Map<String, Map<String, String>> providers = [:]
@Override
void afterPropertiesSet() throws Exception {
initialize()
}
private void initialize() {
//....
}
}
After starting the application, providers
map in OAuth2ProvidersService
was not initialized. I tried the solution suggested by Andy, but it didn't work as well. I use Groovy in that application, so I decided to remove private
and let Groovy generates getter and setter. So my code looked like this:
@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {
Map<String, Map<String, String>> providers = [:]
@Override
void afterPropertiesSet() throws Exception {
initialize()
}
private void initialize() {
//....
}
}
After that small change everything worked.
Although there is one thing that might be worth mentioning. After I make it working I decided to make this field private
and provide setter with straight argument type in the setter method. Unfortunately it wont work that. It causes org.springframework.beans.NotWritablePropertyException
with message:
Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Cannot access indexed value in property referenced in indexed property path 'providers[google]'; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Bean property 'providers[google]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Keep it in mind if you're using Groovy in your Spring Boot application.
Use innerText if you can't assume structure - Use Text#data to update existing text Performance Test
It depends what you mean by "merging" -- do they have the same columns? Do they have headers? For example, if they all have the same columns, and no headers, simple concatenation is sufficient (open the destination file for writing, loop over the sources opening each for reading, use shutil.copyfileobj from the open-for-reading source into the open-for-writing destination, close the source, keep looping -- use the with
statement to do the closing on your behalf). If they have the same columns, but also headers, you'll need a readline
on each source file except the first, after you open it for reading before you copy it into the destination, to skip the headers line.
If the CSV files don't all have the same columns then you need to define in what sense you're "merging" them (like a SQL JOIN? or "horizontally" if they all have the same number of lines? etc, etc) -- it's hard for us to guess what you mean in that case.
For me, it didn't work without enctype: 'multipart/form-data'
field in the Ajax request. I hope it helps someone who is stuck in a similar problem.
Even though the enctype
was already set in the form attribute, for some reason, the Ajax request didn't automatically identify the enctype
without explicit declaration (jQuery 3.3.1).
// Tested, this works for me (jQuery 3.3.1)
fileUploadForm.submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log('Thank God it worked!');
}
}
);
});
// enctype field was set in the form but Ajax request didn't set it by default.
<form action="process/file-upload" enctype="multipart/form-data" method="post" >
<input type="file" name="input-file" accept="text/plain" required>
...
</form>
As others mentioned above, please also pay special attention to the contentType
and processData
fields.
I find accepted answer (Serj-Tm) most robust, but I'd like to suggest a generic version.
public static List<List<T>> splitList<T>(List<T> locations, int nSize = 30)
{
var list = new List<List<T>>();
for (int i = 0; i < locations.Count; i += nSize)
{
list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i)));
}
return list;
}
you can use @see
to do that:
sample:
interface View {
/**
* @return true: have read contact and call log permissions, else otherwise
* @see #requestReadContactAndCallLogPermissions()
*/
boolean haveReadContactAndCallLogPermissions();
/**
* if not have permissions, request to user for allow
* @see #haveReadContactAndCallLogPermissions()
*/
void requestReadContactAndCallLogPermissions();
}
Divide and Conquer involves three steps at each level of recursion:
Dynamic Programming involves the following four steps:
1. Characterise the structure of optimal solutions.
2. Recursively define the values of optimal solutions.
3. Compute the value of optimal solutions.
4. Construct an Optimal Solution from computed information.
For easier understanding, lets see divide and conquer as a brute force solution and its optimisation as dynamic programming.
N.B. divide and conquer algorithms with overlapping subproblems can only be optimised with dp.
The built-in submodule os.path has a function for that very task.
import os
os.path.dirname('T:\Data\DBDesign\DBDesign_93_v141b.mdb')
First, bootstrap-theme.css
is nothing else but equivalent of Bootstrap 2.x style in Bootstrap 3. If you really want to use it, just add it ALONG with bootstrap.css
(minified version will work too).
sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"your subject" );
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "your text");
startActivity(Intent.createChooser(sharingIntent, ""));
feof()
indicates if one has tried to read past the end of file. That means it has little predictive effect: if it is true, you are sure that the next input operation will fail (you aren't sure the previous one failed BTW), but if it is false, you aren't sure the next input operation will succeed. More over, input operations may fail for other reasons than the end of file (a format error for formatted input, a pure IO failure -- disk failure, network timeout -- for all input kinds), so even if you could be predictive about the end of file (and anybody who has tried to implement Ada one, which is predictive, will tell you it can complex if you need to skip spaces, and that it has undesirable effects on interactive devices -- sometimes forcing the input of the next line before starting the handling of the previous one), you would have to be able to handle a failure.
So the correct idiom in C is to loop with the IO operation success as loop condition, and then test the cause of the failure. For instance:
while (fgets(line, sizeof(line), file)) {
/* note that fgets don't strip the terminating \n, checking its
presence allow to handle lines longer that sizeof(line), not showed here */
...
}
if (ferror(file)) {
/* IO failure */
} else if (feof(file)) {
/* format error (not possible with fgets, but would be with fscanf) or end of file */
} else {
/* format error (not possible with fgets, but would be with fscanf) */
}
Why do you need a console application if you want to hide console itself? =)
I recommend setting Project Output type to Windows Application instead of Console application. It will not show you console window, but execute all actions, like Console application do.
Credential dumping on Windows, even with "Credential Manager" is still an issue, and I don't think there is any way to prevent it outside of special hardware. MacOS keychain doesn't have this problem and so I don't think there is an exact equivalent.
Depending on the Tkinter activity, and especially when using Tkinter.after, stopping this activity with destroy()
-- even by using protocol(), a button, etc. -- will disturb this activity ("while executing" error) rather than just terminate it. The best solution in almost every case is to use a flag. Here is a simple, silly example of how to use it (although I am certain that most of you don't need it! :)
from Tkinter import *
def close_window():
global running
running = False # turn off while loop
print( "Window closed")
root = Tk()
root.protocol("WM_DELETE_WINDOW", close_window)
cv = Canvas(root, width=200, height=200)
cv.pack()
running = True;
# This is an endless loop stopped only by setting 'running' to 'False'
while running:
for i in range(200):
if not running:
break
cv.create_oval(i, i, i+1, i+1)
root.update()
This terminates graphics activity nicely. You only need to check running
at the right place(s).
If we are very sure that List<Object>
will contain collection of String
, then probably try this.
List<Object> lst = new ArrayList<Object>();
lst.add("sample");
lst.add("simple");
String[] arr = lst.toArray(new String[] {});
System.out.println(Arrays.deepToString(arr));
Dim found As Integer
found = 0
Dim vTest As Variant
vTest = Application.VLookup(TextBox1.Value, _
Worksheets("Sheet3").Range("A2:A55"), 1, False)
If IsError(vTest) Then
found = 0
MsgBox ("Type Mismatch")
TextBox1.SetFocus
Cancel = True
Exit Sub
Else
TextBox2.Value = Application.VLookup(TextBox1.Value, _
Worksheets("Sheet3").Range("A2:B55"), 2, False)
found = 1
End If
Just in case somebody still lands here looking for an answer. It can be done using plain PHP. An easier way is to reverse-json the object.
function objectToArray(&$object)
{
return @json_decode(json_encode($object), true);
}
On most UNIX-like systems, you can also run:
expand -t4 oldfilename.py > newfilename.py
from the command line, changing the number if you want to replace tabs with a number of spaces other than 4. You can easily write a shell script to do this with a bunch of files at once, retaining the original file names.
For me the issue was that the maven sonar plugin was using proxy servers defined in the maven settings.xml. I was trying to access the sonarque on another (not localhost alias) and so it was trying to use the proxy server to access it. Just added my alias to nonProxyHosts in settings.xml and it is working now. I did not face this issue in maven sonar plugin 3.2, only after i upgraded it.
<proxy>
<id>proxy_id</id>
<active>true</active>
<protocol>http</protocol>
<host>your-proxy-host/host>
<port>your-proxy-host</port>
<nonProxyHosts>localhost|127.0.*|other-non-proxy-hosts</nonProxyHosts>
</proxy>enter code here
<span>
will allow you to style text, but it adds no semantic content.
As you're emphasizing some text, it sounds like you'd be better served by wrapping the text in <em></em>
and using CSS to change the color of the <em>
element. For example:
.description {
color: #fff;
}
.description em {
color: #ffa500;
}
<p class="description">Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat
massa, <em>eget vulputate tellus fermentum.</em></p>
In fact, I'd go to great pains to avoid the <span>
element, as it's completely meaningless to everything that doesn't render your style sheet (bots, screen readers, luddites who disable styles, parsers, etc.) or renders it in unexpected ways (personal style sheets). In many ways, it's no better than using the <font>
element.
.description {_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.description em {_x000D_
color: #ffa500;_x000D_
}
_x000D_
<p class="description">Lorem ipsum dolor sit amet, consectetur _x000D_
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat _x000D_
massa, <em>eget vulputate tellus fermentum.</em></p>
_x000D_
No, you should be using !=
. If data
is actually null then your program will just crash with a NullReferenceException
as a result of attempting to call the Equals
method on null
. Also realize that, if you specifically want to check for reference equality, you should use the Object.ReferenceEquals
method as you never know how Equals
has been implemented.
Your program is crashing because dataList
is null as you never initialize it.
You can change the port mapping by directly editing the hostconfig.json
file at
/var/lib/docker/containers/[hash_of_the_container]/hostconfig.json
or /var/snap/docker/common/var-lib-docker/containers/[hash_of_the_container]/hostconfig.json
, I believe, if You installed Docker as a snap.
You can determine the [hash_of_the_container] via the docker inspect <container_name>
command and the value of the "Id" field is the hash.
docker stop <container_name>
).docker start <container_name>
).So you don't need to create an image with this approach. You can also change the restart flag here.
P.S. You may visit https://docs.docker.com/engine/admin/ to learn how to correctly restart your docker engine as per your host machine. I used sudo systemctl restart docker
to restart my docker engine that is running on Ubuntu 16.04.
Or you can make a simple function like this:
// Provided 'c' is only a numeric character
int parseInt (char c) {
return c - '0';
}
My solution is similar to ATom's one, but easier to implement. You don't need to create a class that shadows FirebaseMessagingService completely, you can just override the method that receives the Intent (which is public, at least in version 9.6.1) and take the information to be displayed from the extras. The "hacky" part is that the method name is indeed obfuscated and is gonna change every time you update the Firebase sdk to a new version, but you can look it up quickly by inspecting FirebaseMessagingService with Android Studio and looking for a public method that takes an Intent as the only parameter. In version 9.6.1 it's called zzm. Here's how my service looks like:
public class MyNotificationService extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage) {
// do nothing
}
@Override
public void zzm(Intent intent) {
Intent launchIntent = new Intent(this, SplashScreenActivity.class);
launchIntent.setAction(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R equest code */, launchIntent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setLargeIcon(rawBitmap)
.setContentTitle(intent.getStringExtra("gcm.notification.title"))
.setContentText(intent.getStringExtra("gcm.notification.body"))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
Very common problem in android
It can be broken down into 3 Pieces
1 ) start Activity B (Happens in Activity A)
2 ) Set requested data (Happens in activity B)
3 ) Receive requested data (Happens in activity A)
1) startActivity B
Intent i = new Intent(A.this, B.class);
startActivity(i);
2) Set requested data
In this part, you decide whether you want to send data back or not when a particular event occurs.
Eg: In activity B there is an EditText and two buttons b1, b2.
Clicking on Button b1 sends data back to activity A
Clicking on Button b2 does not send any data.
Sending data
b1......clickListener
{
Intent resultIntent = new Intent();
resultIntent.putExtra("Your_key","Your_value");
setResult(RES_CODE_A,resultIntent);
finish();
}
Not sending data
b2......clickListener
{
setResult(RES_CODE_B,new Intent());
finish();
}
user clicks back button
By default, the result is set with Activity.RESULT_CANCEL response code
3) Retrieve result
For that override onActivityResult method
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RES_CODE_A) {
// b1 was clicked
String x = data.getStringExtra("RES_CODE_A");
}
else if(resultCode == RES_CODE_B){
// b2 was clicked
}
else{
// back button clicked
}
}
The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.
To display Immediate Window, choose Debug >Windows >Immediate or press Ctrl-Alt-I
Here is an example with Immediate Window:
int Sum(int x, int y) { return (x + y);}
void main(){
int a, b, c;
a = 5;
b = 7;
c = Sum(a, b);
char temp = getchar();}
add breakpoint
call commands
I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:
inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
int curRow = r * sectors;
int nextRow = (r+1) * sectors;
indices.push_back(curRow + s);
indices.push_back(nextRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + (s+1));
}
void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
float radius, unsigned int rings, unsigned int sectors)
{
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
for(int r = 0; r < rings; ++r) {
for(int s = 0; s < sectors; ++s) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
texcoords.push_back(vec2(s*S, r*R));
vertices.push_back(vec3(x,y,z) * radius);
push_indices(indices, sectors, r, s);
}
}
}
Return true if all checbox are checked in a div
function all_checked (id_div){
all_checked = true;
$(id_div+' input[type="checkbox"]').each(function() {
all_checked = all_checked && $('this').prop('checked');
}
return all_checked;
}
OFFSET 10 ROWS -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows
use this in the end of your select syntax. =)
Add maven directory /bin
to System variables under the name Path
.
To check this, you can echo %PATH%
If you want the latest file in the directory and you are using only the LastWriteTime
to determine the latest file, you can do something like below:
gci path | sort LastWriteTime | select -last 1
On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar
gci path | select -last 1
Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}
It depends on what you want to do. This code swaps two elements of an array.
void swap(int i, int j, int[] arr) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
Something like this swaps the content of two int[]
of equal length.
void swap(int[] arr1, int[] arr2) {
int[] t = arr1.clone();
System.arraycopy(arr2, 0, arr1, 0, t.length);
System.arraycopy(t, 0, arr2, 0, t.length);
}
Something like this swaps the content of two BitSet
(using the XOR swap algorithm):
void swap(BitSet s1, BitSet s2) {
s1.xor(s2);
s2.xor(s1);
s1.xor(s2);
}
Something like this swaps the x
and y
fields of some Point
class:
void swapXY(Point p) {
int t = p.x;
p.x = p.y;
p.y = t;
}
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
Currently using Visual Studio Code and the command to disable tslint is
/* tslint:disable */
Something to note. The disable above disables ALL tslint rules on that page. If you want to disable a specific rule you can specify one/multiple rules.
/* tslint:disable comment-format */
/* tslint:disable:rule1 rule2 rule3 etc.. */
Or enable a rule
/* tslint:enable comment-format */
Create a WebViewClient, and override the shouldOverrideUrlLoading method.
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
view.loadUrl(url);
return false; // then it is not handled by default action
}
});
Try this .. this method works for me..!! hope it may help somebody..!!
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/my_awesome_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:singleLine="true"
android:text="Toolbar Title"
android:textColor="@android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
To display logo in toolbar try the below snippet. // Set drawable
toolbar.setLogo(ContextCompat.getDrawable(context, R.drawable.logo));
Let me know the result.
Use the function to clear cookies:
function clearCookies($clearSession = false)
{
$past = time() - 3600;
if ($clearSession === false)
$sessionId = session_id();
foreach ($_COOKIE as $key => $value)
{
if ($clearSession !== false || $value !== $sessionId)
setcookie($key, $value, $past, '/');
}
}
If you pass true
then it clears session
data, otherwise session data is preserved.
Youtube don't provide muting through url parameter (see http://code.google.com/apis/youtube/player_parameters.html).
You have to use javascript for that. see http://code.google.com/apis/youtube/js_api_reference.html for details.
However, please note the warning on the page linked above: "The deprecation of the YouTube JavaScript Player API was announced on January 27, 2015. YouTube Flash embeds have also been deprecated. See the deprecation policy for more information. Please migrate your applications to the IFrame API, which can intelligently use whichever embedded player – HTML () or Flash () – the client supports."
Html
<iframe class="youtube-player" id="player" type="text/html" src="http://www.youtube.com/embed/JW5meKfy3fY?wmode=opaque&autohide=1&autoplay=1&enablejsapi=1" frameborder="0"><br /></iframe>
please note enablejsapi=1 in the url.
Javascript
var player = iframe.getElementById('player');
player.mute();
Update
Previous code had some issues and did not work with current API (playerVars syntax was wrong). Here is the updated code. You may need to tinker with the parameters you need.
_x000D_
<div id="player"></div>_x000D_
<script>_x000D_
// 1. This code loads the IFrame Player API code asynchronously._x000D_
var tag = document.createElement('script');_x000D_
_x000D_
tag.src = "https://www.youtube.com/iframe_api";_x000D_
var firstScriptTag = document.getElementsByTagName('script')[0];_x000D_
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);_x000D_
_x000D_
// 2. This function creates an <iframe> (and YouTube player)_x000D_
// after the API code downloads._x000D_
var player;_x000D_
function onYouTubeIframeAPIReady() {_x000D_
player = new YT.Player('player', {_x000D_
height: '100%',_x000D_
width: '100%',_x000D_
playerVars: {_x000D_
autoplay: 1,_x000D_
loop: 1,_x000D_
controls: 0,_x000D_
showinfo: 0,_x000D_
autohide: 1,_x000D_
modestbranding: 1,_x000D_
vq: 'hd1080'},_x000D_
videoId: '1pzWROvY7gY',_x000D_
events: {_x000D_
'onReady': onPlayerReady,_x000D_
'onStateChange': onPlayerStateChange_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// 3. The API will call this function when the video player is ready._x000D_
function onPlayerReady(event) {_x000D_
event.target.playVideo();_x000D_
player.mute();_x000D_
}_x000D_
_x000D_
var done = false;_x000D_
function onPlayerStateChange(event) {_x000D_
_x000D_
}_x000D_
function stopVideo() {_x000D_
player.stopVideo();_x000D_
}_x000D_
</script>
_x000D_
On debian / ubuntu you only need: libjpeg62-turbo-dev
So a simple sudo apt install libjpeg62-turbo-dev
and a pip install pillow
function isMobileDev(){
if(isset($_SERVER['HTTP_USER_AGENT']) and !empty($_SERVER['HTTP_USER_AGENT'])){
$user_ag = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(Mobile|Android|Tablet|GoBrowser|[0-9]x[0-9]*|uZardWeb\/|Mini|Doris\/|Skyfire\/|iPhone|Fennec\/|Maemo|Iris\/|CLDC\-|Mobi\/)/uis',$user_ag)){
return true;
};
};
return false;
}
To add into every ajax request, I have answered it here: https://stackoverflow.com/a/58964440/1909708
To add into particular ajax requests, this' how I implemented:
var token_value = $("meta[name='_csrf']").attr("content");
var token_header = $("meta[name='_csrf_header']").attr("content");
$.ajax("some-endpoint.do", {
method: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader(token_header, token_value);
},
data: {form_field: $("#form_field").val()},
success: doSomethingFunction,
dataType: "json"
});
You must add the meta
elements in the JSP, e.g.
<html>
<head>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<meta name="_csrf" content="${_csrf.token}"/>
To add to a form submission (synchronous) request, I have answered it here: https://stackoverflow.com/a/58965526/1909708
Type
chcp
to see your current code page (as Dewfy already said).
Use
nlsinfo
to see all installed code pages and find out what your code page number means.
You need to have Windows Server 2003 Resource kit installed (works on Windows XP) to use nlsinfo
.
You need to print
to get that output.
You should do
>>> x = "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
>>> x # this is the value, returned by the join() function
'I\nwould\nexpect\nmultiple\nlines'
>>> print x # this prints your string (the type of output you want)
I
would
expect
multiple
lines
From PEP 8 -- Style Guide for Python Code:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:
with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read())
Another such case is with assert statements.
Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:
class Rectangle(Blob): def __init__(self, width, height, color='black', emphasis=None, highlight=0): if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") if width == 0 and height == 0 and (color == 'red' or emphasis is None): raise ValueError("I don't think so -- values are %s, %s" % (width, height)) Blob.__init__(self, width, height, color, emphasis, highlight)
PEP8 now recommends the opposite convention (for breaking at binary operations) used by mathematicians and their publishers to improve readability.
Donald Knuth's style of breaking before a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted.
From PEP8: Should a line break before or after a binary operator?:
Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].
Following the tradition from mathematics usually results in more readable code:
# Yes: easy to match operators with operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest)
In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.
[3]: Donald Knuth's The TeXBook, pages 195 and 196
You can customize material styles by setting different color properties. For example custom application theme
<style name="CustomAppTheme" parent="Theme.AppCompat">
<item name="android:textColorPrimaryDisableOnly">#00838f</item>
<item name="colorAccent">#e91e63</item>
</style>
Custom switch theme
<style name="MySwitch" parent="@style/Widget.AppCompat.CompoundButton.Switch">
<item name="android:textColorPrimaryDisableOnly">#b71c1c</item>
<item name="android:colorControlActivated">#1b5e20</item>
<item name="android:colorForeground">#f57f17</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
</style>
You can customize switch track and switch thumb like below image by defining xml drawables. For more information http://www.zoftino.com/android-switch-button-and-custom-switch-examples
Sadly due to Opera's latest update !!window.chrome
(and other tests on the window object) when testing in Opera returns true.
Conditionizr takes care of this for you and solves the Opera issue:
conditionizr.add('chrome', [], function () {
return !!window.chrome && !/opera|opr/i.test(navigator.userAgent);
});
I'd highly suggest using it as none of the above are now valid.
This allows you to do:
if (conditionizr.chrome) {...}
Conditionizr takes care of other browser detects and is much faster and reliable than jQuery hacks.
If you are not into Cygwin, you can use native Windows builds. Some are here: curl Download Wizard.
You have to do some encoding before using fit. As it was told fit() does not accept Strings but you solve this.
There are several classes that can be used :
Personally I have post almost the same question on StackOverflow some time ago. I wanted to have a scalable solution but didn't get any answer. I selected OneHotEncoder that binarize all the strings. It is quite effective but if you have a lot different strings the matrix will grow very quickly and memory will be required.
I think you are confused with the printf(String format, Object... args)
method. The first argument is the format string, which is mandatory, rest you can pass an arbitrary number of Object
s.
There is no such overload for both the print()
and println()
methods.
Here is an alternative way if the data frame just contains numbers.
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
but the most reliable way of converting a data frame to a matrix is using data.matrix()
function.
Just a note for people who may have found this later (and want java way of achieving this); FirefoxOptions
is also capable of enabling the headless mode:
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);
The API's will provide full access to LIVE data, and developers can thus provide applications and develop against the API without paying licencing fees. Consumers will pay for any data received from the apps provided by third party developers, and so BB will grow their audience and revenue in that way.
NOTE: Bloomberg is offering this programming interface (BLPAPI) under a free-use license. This license does not include nor provide access to any Bloomberg data or content.
For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:
CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
$blog is an object not an array
try using $blog->id
instead of $blog['id']
rm -Force -Recurse -Confirm:$false $directory2Delete
didn't work in the PowerShell ISE, but it worked through the regular PowerShell CLI.
I hope this helps. It was driving me bannanas.
How about this: (or is it ok to use like this?)
var test = "Hello";
new Thread(new ThreadStart(() =>
{
try
{
//Staff to do
Console.WriteLine(test);
}
catch (Exception ex)
{
throw;
}
})).Start();
Its as simple as this:
CREATE FUNCTION InlineMax
(
@p1 sql_variant,
@p2 sql_variant
) RETURNS sql_variant
AS
BEGIN
RETURN CASE
WHEN @p1 IS NULL AND @p2 IS NOT NULL THEN @p2
WHEN @p2 IS NULL AND @p1 IS NOT NULL THEN @p1
WHEN @p1 > @p2 THEN @p1
ELSE @p2 END
END;
I had the same issue... I was using maven building tool with JUnit dependency scope as 'test' and my @Test method was in main module.
To resolve, I've: 1. Commented the scope tag of JUnit dependency in the pom.xml 2. Rebuilt the package 3. Made sure the Test class has only one constructor
The issue can be two-folded: 1. The JUnit dependency is limited to test scope and the @Test method is in main scope 2. The test class has more than one constructor
You do cls.isFilled = True
. That overwrites the method called isFilled
and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.
The solution is use a different name for the variable than you do for the method.
echo
No return value
e.g. echo "String 1", "String 2"
Returns 1
, so it can be used in an expression
e.g. print "Hello"
or, if ($expr && print "foo")
print_r()
var_dump()
print_r()
, for example it also prints the type of valuesvar_export()
print_r()
and var_dump()
- resulting output is valid PHP code!Notes:
print
can be used in an expression, I recommend people avoid doing so, because it is bad for code readability (and because it's unlikely to ever be useful). The precedence rules when it interacts with other operators can also be confusing. Because of this, I personally don't ever have a reason to use it over echo
.echo
and print
are language constructs, print_r()
and var_dump()
/var_export()
are regular functions. You don't need parentheses to enclose the arguments to echo
or print
(and if you do use them, they'll be treated as they would in an expression).var_export()
returns valid PHP code allowing values to be read back later, relying on this for production code may make it easier to introduce security vulnerabilities due to the need to use eval()
. It would be better to use a format like JSON instead to store and read back values. The speed will be comparable.try this ,hope it helps
select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
CASE
WHEN invitee_status=1 THEN "attending"
WHEN invitee_status=2 THEN "unsure"
WHEN invitee_status=3 THEN "declined"
WHEN invitee_status=0 THEN "notreviwed" END
) AS invitee_status
FROM your_tbl
I have used wire shark tool for monitoring service calls from silver light app in browser to service. try the link gives clear info
It enables you to monitor the whole request and response contents.
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(new ParameterizedThreadStart(ThreadMethod));
t.Start("My Parameter");
}
static void ThreadMethod(object parameter)
{
// parameter equals to "My Parameter"
}
}
This is regular problem I've solved like this
http://jsfiddle.net/ipeshev/d1dfr0jz/
Try to set delay of closed state to some negative number and play a little bit with the value. You will see the difference.It can be made almost to lie the human eye ;).
It works in major browsers, but good enough for me. It is strange but give some results.
.expandable {
max-height: 0px;
overflow: hidden;
transition: all 1s linear -0.8s;
}
button:hover ~ .expandable {
max-height: 9000px;
transition: all 1s ease-in-out;
}
Although this has been answered sufficiently, you could also explicitly delete the property in question before stringification using the delete
operator.
delete obj.b;
const jsonObject = JSON.stringify(obj);
this will remove the need to build or maintain complex logic to remove circular references.
The library PCAmixdata has functon splitmix that splits quantitative(Numerical data) and qualitative (Categorical data) of a given dataframe "YourDataframe" as shown below:
install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset)
X2 <- split$X.quali (Gives categorical columns in the dataset)
ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...
If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...
HTH
you could write an extension method
public static void Fill<T>(this T[] array, T value)
{
for(int i = 0; i < array.Length; i++)
{
array[i] = value;
}
}
Just use the following sql, you are done:
SELECT replace(CustomerName,' ', '') FROM Customers;
you can test this sample over here: W3School
Since vars passed through url are $_GET vars, you can use filter_input()
function:
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$othervar = filter_input(INPUT_GET, 'othervar', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
It would store the values of each var and sanitize/validate them too.
Add config/secrets.yml
to version control and deploy again. You might need to remove a line from .gitignore
so that you can commit the file.
I had this exact same issue and it just turned out that the boilerplate .gitignore
Github created for my Rails application included config/secrets.yml
.
I liked @mate64's answer so I am going to reuse that with slight modifications to create a slide down and up animations below:
var $slider = document.getElementById('slider');_x000D_
var $toggle = document.getElementById('toggle');_x000D_
_x000D_
$toggle.addEventListener('click', function() {_x000D_
var isOpen = $slider.classList.contains('slide-in');_x000D_
_x000D_
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');_x000D_
});
_x000D_
#slider {_x000D_
position: absolute;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: blue;_x000D_
transform: translateY(-100%);_x000D_
-webkit-transform: translateY(-100%);_x000D_
}_x000D_
_x000D_
.slide-in {_x000D_
animation: slide-in 0.5s forwards;_x000D_
-webkit-animation: slide-in 0.5s forwards;_x000D_
}_x000D_
_x000D_
.slide-out {_x000D_
animation: slide-out 0.5s forwards;_x000D_
-webkit-animation: slide-out 0.5s forwards;_x000D_
}_x000D_
_x000D_
@keyframes slide-in {_x000D_
100% { transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-in {_x000D_
100% { -webkit-transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@keyframes slide-out {_x000D_
0% { transform: translateY(0%); }_x000D_
100% { transform: translateY(-100%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-out {_x000D_
0% { -webkit-transform: translateY(0%); }_x000D_
100% { -webkit-transform: translateY(-100%); }_x000D_
}
_x000D_
<div id="slider" class="slide-in">_x000D_
<ul>_x000D_
<li>Lorem</li>_x000D_
<li>Ipsum</li>_x000D_
<li>Dolor</li>_x000D_
</ul>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
Depending on your use case, instead of using a case statement, you can use the union of multiple select statements, one for each condition.
My goal when I found this question was to select multiple columns conditionally. I didn't necessarily need the case statement, so this is what I did.
For example:
SELECT
a1,
a2,
a3,
...
WHERE <condition 1>
AND (<other conditions>)
UNION
SELECT
b1,
b2,
b3,
...
WHERE <condition 2>
AND (<other conditions>)
UNION
SELECT
...
-- and so on
Be sure that exactly one condition evaluates to true at a time.
I'm using Postgresql, and the query planner was smart enough to not run a select statement at all if the condition in the where clause evaluated to false (i.e. only one of the select statement actually runs), so this was also performant for me.
In python3.6+
you can use the secrets
module:
The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.
In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.
In testing generation of 768bit
security tokens I found:
random.choices()
- 0.000246
secssecrets.choice()
- 0.003529
secsThe secrets
modules is slower but outside of testing it is what you should be using for cryptographic purposes:
import string, secrets
def random_string(size):
letters = string.ascii_lowercase+string.ascii_uppercase+string.digits
return ''.join(secrets.choice(letters) for i in range(size))
print(random_string(768))
You can also search with -- option which basically ignores all the special characters and it won't be interpreted by grep.
$ cat foo |grep -- "0\.49"
Create a new class MyView, Which extends View
. Override the onDraw(Canvas canvas)
method to draw rectangle on Canvas
.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
Paint paint;
Path path;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawRect(30, 50, 200, 350, paint);
canvas.drawRect(100, 100, 300, 400, paint);
//drawRect(left, top, right, bottom, paint)
}
}
Then Move your Java activity to setContentView()
using our custom View, MyView.Call this way.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
For more details you can visit here
http://developer.android.com/reference/android/graphics/Canvas.html
I'm using UBUNTU and I got this same error. I restarted the set up using sudo and did a custom install. This solved my problem!
--More Specific--
re-installed using # sudo ./studio.sh
then I made sure to click "Custom Install"
then I made sure all packages were selected.
And I got this message Android virtual device Nexus_5_API_22_x86 was successfully created
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
Request timed out means that the local host did not receive a response from the destination host, but it was able to reach it. Destination host unreachable means that there was no valid route to the requested host.
@Jacob already showed you how to use the Gaussian filter in Matlab, so I won't repeat that.
I would choose filter size to be about 3*sigma in each direction (round to odd integer). Thus, the filter decays to nearly zero at the edges, and you won't get discontinuities in the filtered image.
The choice of sigma depends a lot on what you want to do. Gaussian smoothing is low-pass filtering, which means that it suppresses high-frequency detail (noise, but also edges), while preserving the low-frequency parts of the image (i.e. those that don't vary so much). In other words, the filter blurs everything that is smaller than the filter.
If you're looking to suppress noise in an image in order to enhance the detection of small features, for example, I suggest to choose a sigma that makes the Gaussian just slightly smaller than the feature.
You can use time.strftime()
:
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
It sounds like you might want just a bar graph:
Alternatively, you can use subplots.
Super late to the party but if someone finds this out.
You can call IConfiguration from Microsoft.Extensions.Configuration;
public static IConfiguration Configuration { get; }
public static string MyAwesomeString = Configuration.GetSection("appSettings")["MyAwesomeString"].ToString();
Just in case, here is what I did to get partial arguments, kind of. I’ve created a little helper that takes a partial name and a hash of parameters that will be passed to the partial:
Handlebars.registerHelper('render', function(partialId, options) {
var selector = 'script[type="text/x-handlebars-template"]#' + partialId,
source = $(selector).html(),
html = Handlebars.compile(source)(options.hash);
return new Handlebars.SafeString(html);
});
The key thing here is that Handlebars helpers accept a Ruby-like hash of arguments. In the helper code they come as part of the function’s last argument—options
— in its hash
member. This way you can receive the first argument—the partial name—and get the data after that.
Then, you probably want to return a Handlebars.SafeString
from the helper or use “triple-stash”—{{{
— to prevent it from double escaping.
Here is a more or less complete usage scenario:
<script id="text-field" type="text/x-handlebars-template">
<label for="{{id}}">{{label}}</label>
<input type="text" id="{{id}}"/>
</script>
<script id="checkbox-field" type="text/x-handlebars-template">
<label for="{{id}}">{{label}}</label>
<input type="checkbox" id="{{id}}"/>
</script>
<script id="form-template" type="text/x-handlebars-template">
<form>
<h1>{{title}}</h1>
{{ render 'text-field' label="First name" id="author-first-name" }}
{{ render 'text-field' label="Last name" id="author-last-name" }}
{{ render 'text-field' label="Email" id="author-email" }}
{{ render 'checkbox-field' label="Private?" id="private-question" }}
</form>
</script>
Hope this helps …someone. :)
I guess there are so many ways to make what you want. Here's a way that I use. With the commons.io
library you can iterate over the files in a directory. You must use the FileUtils.iterateFiles
method and you can process each file.
You can find the information here: http://commons.apache.org/proper/commons-io/download_io.cgi
Here's an example:
Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);
while(it.hasNext()){
System.out.println(((File) it.next()).getName());
}
You can change null
and put a list of extentions if you wanna filter. Example: {".xml",".java"}
The warning is telling you what is wrong. The problem is that brew
is kept in /usr/local/bin
So, you can try /usr/local/bin/brew doctor
To fix it permanently alter your bash profile (.bashrc or .profile in your home directory) and add the following line:
export PATH=/usr/local/bin:$PATH
Square brackets are lists while parentheses are tuples.
A list is mutable, meaning you can change its contents:
>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
while tuples are not:
>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:
>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Note that, as many people have pointed out, you can add tuples together. For example:
>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:
>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
Whereas, if you were to construct this same example with a list, y
would also be updated:
>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
For accessing the elements of a list you need to use the square brackets ([]
) and not the parenthesis (()
).
Instead of:
print wordlists(len(words))
you need to use:
print worldlists[len(words)]
And instead of:
(wordlists(len(words))).append(words)
you need to use:
worldlists[len(words)].append(words)
var cars = [
manufacturer: [
{
color: 'gray',
model: '1',
nOfDoors: 4
},
{
color: 'yellow',
model: '2',
nOfDoors: 4
}
]
]
If I remember correctly from my own use of bootstrap, the .spanN
classes are floated, which automatically makes them behave as display: block
. To make display: table-cell
work, you need to remove the float.
For the sake of completeness, there's md5deep(1); it's not directly applicable due to *.py filter requirement but should do fine together with find(1).
begin
for i in (select 'drop table '||table_name||' cascade constraints' tbl from user_tables)
loop
execute immediate i.tbl;
end loop;
end;
I have experienced that if kill -9 PID
doesn't work and you own the process, you can use kill -s kill PID
which is kind of surprising as the man page says you can kill -signal_number PID
.
Since you say you want to access by position once your data is read in, you should know about R's subsetting/ indexing functions.
The easiest is
df[row,column]
#example
df[1:5,] #rows 1:5, all columns
df[,5] #all rows, column 5.
Other methods are here. I personally use the dplyr package for intuitive data manipulation (not by position).
docker container list -f "status=exited"
or
docker container ls -f "status=exited"
or
docker ps -f "status=exited"
If you using windows, you can fix it via install SVN Tool. If you using Linux/MacOS, you can fix it via install subversion. After that, just select using svn command. Your problems is resolve.
You can use the static
from()
method from the LayoutInflater
class:
LayoutInflater li = LayoutInflater.from(context);
NOTE: While my advice was true many years ago, Oracle's optimizer has improved so that the location of the where definitely no longer matters here. However preferring UNION ALL
vs UNION
will always be true, and portable SQL should avoid depending on optimizations that may not be in all databases.
Short answer, you want the WHERE
before the UNION
and you want to use UNION ALL
if at all possible. If you are using UNION ALL
then check the EXPLAIN output, Oracle might be smart enough to optimize the WHERE
condition if it is left after.
The reason is the following. The definition of a UNION
says that if there are duplicates in the two data sets, they have to be removed. Therefore there is an implicit GROUP BY
in that operation, which tends to be slow. Worse yet, Oracle's optimizer (at least as of 3 years ago, and I don't think it has changed) doesn't try to push conditions through a GROUP BY
(implicit or explicit). Therefore Oracle has to construct larger data sets than necessary, group them, and only then gets to filter. Thus prefiltering wherever possible is officially a Good Idea. (This is, incidentally, why it is important to put conditions in the WHERE
whenever possible instead of leaving them in a HAVING
clause.)
Furthermore if you happen to know that there won't be duplicates between the two data sets, then use UNION ALL
. That is like UNION
in that it concatenates datasets, but it doesn't try to deduplicate data. This saves an expensive grouping operation. In my experience it is quite common to be able to take advantage of this operation.
Since UNION ALL
does not have an implicit GROUP BY
in it, it is possible that Oracle's optimizer knows how to push conditions through it. I don't have Oracle sitting around to test, so you will need to test that yourself.
this method also encounter a deprecate warning:
org.junit.Assert.assertEquals(float expected,float actual) //deprecated
It is because currently junit prefer a third parameter rather than just two float variables input.
The third parameter is delta:
public static void assertEquals(double expected,double actual,double delta) //replacement
this is mostly used to deal with inaccurate Floating point calculations
for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values
In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.
Replace below line with new updated working code:
@Html.DropDownList("NewsCategoriesID", (SelectList)ViewBag.NewsCategoriesID)
Now Implement new updated working code:
@Html.DropDownListFor(model => model.NewsCategoriesID, ViewBag.NewsCategoriesID as List<SelectListItem>, new {name = "NewsCategoriesID", id = "NewsCategoriesID" })
Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:
<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>
In case of the error:
"Internal compiler error: java.lang.OutOfMemoryError: GC overhead limit exceeded at java.lang.AbstractStringBuilder"
increase the java heap space to 2GB i.e., -Xmx2g.
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
TabLayout tab_layout = (TabLayout)findViewById(R.id.tab_Layout_);
private void changeTabsFont() {
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/"+ Constants.FontStyle);
ViewGroup vg = (ViewGroup) tab_layout.getChildAt(0);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(font);
((TextView) tabViewChild).setTextSize(15);
}
}
}
}
This code is works for me using tablayout. It will change size of fonts and also change font style.
This will also help you guys please check this link
https://stackoverflow.com/a/43156384/5973946
This code works for Tablayout change text color,type face (font style) and also text size.
I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.
So, I had to generate the SSL certificate again and it started working...
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt
It is simply possible with childElementCount
in pure javascript
var countItems = document.getElementsByTagName("ul")[0].childElementCount;_x000D_
console.log(countItems);
_x000D_
<div id="selected">_x000D_
<ul>_x000D_
<li>29</li>_x000D_
<li>16</li>_x000D_
<li>5</li>_x000D_
<li>8</li>_x000D_
<li>10</li>_x000D_
<li>7</li>_x000D_
</ul>_x000D_
</div>
_x000D_
I think the response from W5ALIVE is closest to what I use to find the last row of data in a column. Assuming I am looking for the last row with data in Column A, though, I would use the following for the more generic lookup:
=MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0))
The first MATCH will find the last text cell and the second MATCH finds the last numeric cell. The IFERROR function returns zero if the first MATCH finds all numeric cells or if the second match finds all text cells.
Basically this is a slight variation of W5ALIVE's mixed text and number solution.
In testing the timing, this was significantly quicker than the equivalent LOOKUP variations.
To return the actual value of that last cell, I prefer to use indirect cell referencing like this:
=INDIRECT("A"&MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0)))
The method offered by sancho.s is perhaps a cleaner option, but I would modify the portion that finds the row number to this:
=INDEX(MAX((A:A<>"")*(ROW(A:A))),1)
the only difference being that the ",1" returns the first value while the ",0" returns the entire array of values (all but one of which are not needed). I still tend to prefer addressing the cell to the index function there, in other words, returning the cell value with:
=INDIRECT("A"&INDEX(MAX((A:A<>"")*(ROW(A:A))),1))
Great thread!
Within your app in the Android Emulator press Command + M on macOS or Ctrl + M on Linux and Windows.
Try This
Write code in your service
import {Observable, of} from 'rxjs';
import json file
import Product from "./database/product.json";
getProduct(): Observable<any> {
return of(Product).pipe(delay(1000));
}
In component
get_products(){
this.sharedService.getProduct().subscribe(res=>{
console.log(res);
})
}
You can use loop for.
var items = {1, 2, 3}
for(var i = 0; i < items.length; i++) {
if(i == items.length - 1) {
res.ok(i);
}
}
data=pd.read_csv('/your file name', delim_whitespace=True)
data.Number
now you can run this code with no error.
I answered this question on SuperUser but only after the OP disregarded the unhelpful answer that was at the time the only answer to the question.
Here is the proper way to elevate permissions in Cygwin, copied from my own answer on SuperUser:
I found the answer on the Cygwin mailing list. To run command
with elevated privileges in Cygwin, precede the command with cygstart --action=runas
like this:
$ cygstart --action=runas command
This will open a Windows dialogue box asking for the Admin password and run the command if the proper password is entered.
This is easily scripted, so long as ~/bin
is in your path. Create a file ~/bin/sudo
with the following content:
#!/usr/bin/bash
cygstart --action=runas "$@"
Now make the file executable:
$ chmod +x ~/bin/sudo
Now you can run commands with real elevated privileges:
$ sudo elevatedCommand
You may need to add ~/bin
to your path. You can run the following command on the Cygwin CLI, or add it to ~/.bashrc
:
$ PATH=$HOME/bin:$PATH
Tested on 64-bit Windows 8.
You could also instead of above steps add an alias for this command to ~/.bashrc
:
# alias to simulate sudo
alias sudo='cygstart --action=runas'
An ObservableCollection
works essentially like a regular collection except that it implements
the interfaces:
As such it is very useful when you want to know when the collection has changed. An event is triggered that will tell the user what entries have been added/removed or moved.
More importantly they are very useful when using databinding on a form.
Not easily done I am afraid. The problem is Css cannot replace the arrow in a select as this is rendered by the browser. But you can build a new control from div and input elements and Javascript to perform the same function as the select.
Try looking at some of the autocomplete plugins for Jquery for example.
Otherwise there is some info on the select element here:
http://www.devarticles.com/c/a/Web-Style-Sheets/Taming-the-Select/
This expands on the answer by Denis Bubnov.
I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.
{% set count = 0 %}
{% for anchor in items %}
{% if anchor.content['#paragraph'].field_anchor_link.0.value %}
{% set count = count + 1 %}
{% endif %}
{% endfor %}
{% if count > 0 %}
--- build the toc here --
{% endif %}
I've used ZetaHtmlTidy in the past to load random websites and then hit against various parts of the content with xpath (eg /html/body//p[@class='textblock']). It worked well but there were some exceptional sites that it had problems with, so I don't know if it's the absolute best solution.
$("input[@name='<%=test2.ClientID%>']:checked");
use this and here ClientID fetch random id created by .net.
As you've already noticed, you can control most of these settings in .csproj.
If you'd rather keep these in AssemblyInfo.cs, you can turn off auto-generated assembly attributes.
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
If you want to see what's going on under the hood, checkout Microsoft.NET.GenerateAssemblyInfo.targets inside of Microsoft.NET.Sdk.
Take a look at the InstallHelper method of the ManagedInstaller class. You can install a service using:
string[] args;
ManagedInstallerClass.InstallHelper(args);
This is exactly what InstallUtil does. The arguments are the same as for InstallUtil.
The benefits of this method are that it involves no messing in the registry, and it uses the same mechanism as InstallUtil.
Guava provides MoreCollectors.onlyElement()
which does the right thing here. But if you have to do it yourself, you could roll your own Collector
for this:
<E> Collector<E, ?, Optional<E>> getOnly() {
return Collector.of(
AtomicReference::new,
(ref, e) -> {
if (!ref.compareAndSet(null, e)) {
throw new IllegalArgumentException("Multiple values");
}
},
(ref1, ref2) -> {
if (ref1.get() == null) {
return ref2;
} else if (ref2.get() != null) {
throw new IllegalArgumentException("Multiple values");
} else {
return ref1;
}
},
ref -> Optional.ofNullable(ref.get()),
Collector.Characteristics.UNORDERED);
}
...or using your own Holder
type instead of AtomicReference
. You can reuse that Collector
as much as you like.
The other answers are great for things like cron jobs, but if you're running a daemon you should monitor it with something like daemontools.
@sfussenegger's answer explains how to make this work. But I'd say don't do it!
Experienced Java programmers use, and expect to see
System.out.println(...);
and not
out.println(...);
A static import of System.out or System.err is (IMO) bad style because:
If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.
I ended up making my own, I find that it works better the other solutions that were around.
I did not test this with LINQ to Entities:
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !dc.Orders.Any(o => o.CustomerID == c.CustomerID)
select c;
Alternatively:
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where dc.Orders.All(o => o.CustomerID != c.CustomerID)
select c;
foreach (var c in query)
Console.WriteLine( c );
You can actually put anything inside a toolbar. See the below code.
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:background="@color/colorPrimary">
</android.support.v7.widget.Toolbar>
Between the above toolbar tag you can put almost anything. That is the benefit of using a Toolbar.
Source: Android Toolbar Example
Here is slightly modified version. Changes are noted as code commentary.
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
You could hide controls using CSS Pseudo Selectors like Demo: https://jsfiddle.net/g1rsasa3
//For Firefox we have to handle it in JavaScript _x000D_
var vids = $("video"); _x000D_
$.each(vids, function(){_x000D_
this.controls = false; _x000D_
}); _x000D_
//Loop though all Video tags and set Controls as false_x000D_
_x000D_
$("video").click(function() {_x000D_
//console.log(this); _x000D_
if (this.paused) {_x000D_
this.play();_x000D_
} else {_x000D_
this.pause();_x000D_
}_x000D_
});
_x000D_
video::-webkit-media-controls {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
/* Could Use thise as well for Individual Controls */_x000D_
video::-webkit-media-controls-play-button {}_x000D_
_x000D_
video::-webkit-media-controls-volume-slider {}_x000D_
_x000D_
video::-webkit-media-controls-mute-button {}_x000D_
_x000D_
video::-webkit-media-controls-timeline {}_x000D_
_x000D_
video::-webkit-media-controls-current-time-display {}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>_x000D_
<!-- Hiding HTML5 Video Controls using CSS Pseudo selectors -->_x000D_
_x000D_
<video width="800" autoplay controls="false">_x000D_
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4">_x000D_
</video>
_x000D_
well, char *
means a pointer point to char, it is different from char array.
char amessage[] = "this is an array"; /* define an array*/
char *pmessage = "this is a pointer"; /* define a pointer*/
And, char **
means a pointer point to a char pointer.
You can look some books about details about pointer and array.
for jQuery
we can use below:
by input name:
$('input[name="textboxname"]').val('some value');
by input class:
$('input[type=text].textboxclass').val('some value');
by input id:
$('#textboxid').val('some value');
Here's a PCRE regular expression for XML/XHTML, built from a simplified EBNF syntax definition:
/
(?(DEFINE)
(?<tag> (?&tagempty) | (?&tagopen) ((?&textnode) | (?&tag) | (?&comment))* (?&tagclose))
(?<tagunnested> (?&tagempty) | (?&tagopen) ((?&textnode) | (?&comment))* (?&tagclose))
(?<textnode> [^<>]+)
(?<comment> <!--([\s\S]*?)-->)
(?<tagopen> < (?&tagname) (?&attrlist)? (?&ws)* >)
(?<tagempty> < (?&tagname) (?&ws)* (?&attrlist)? (?&ws)* \/>)
(?<tagclose> <\/ (?&tagname) (?&ws)* >)
(?<attrlist> ((?&ws)+ (?&attr))+)
(?<attr> (?&attrunquoted) | (?&attrsinglequoted) | (?&attrdoublequoted) | (?&attrempty))
(?<attrempty> (?&attrname))
(?<attrunquoted> (?&attrname) (?&ws)* = (?&ws)* (?&attrunquotedvalue))
(?<attrsinglequoted> (?&attrname) (?&ws)* = (?&ws)* ' (?&attrsinglequotedvalue) ')
(?<attrdoublequoted> (?&attrname) (?&ws)* = (?&ws)* " (?&attrdoublequotedvalue) ")
(?<tagname> (?&alphabets) ((?&alphabets) | (?&digits))*)
(?<attrname>(?&alphabets)+((?&alphabets)|(?&digits)|[:-]) )
(?<attrunquotedvalue> [^\s"'=<>`]+)
(?<attrsinglequotedvalue> [^']+)
(?<attrdoublequotedvalue> [^"]+)
(?<alphabets> [a-zA-Z])
(?<digits> [0-9])
(?<ws> \s)
)
(?&tagopen)
/x
This illustrates how to build regular expressions for context-free grammars. You can match other parts of the definition by changing the match on the last line from (?&tagopen)
to e.g. (?&tagunnested)
For XML/XHTML the consensus is no!
Credits to nikic for supplying the idea.
While @simon's answer is most helpful in Python 2, raw_input
is not present in Python 3. I'd suggest doing the following to make sure your code works equally well in Python 2 and Python 3:
First, pip install future:
$ pip install future
Second: import input from future.builtins
# my_file.py
from future.builtins import input
str_value = input('Type something in: ')
And for the specific example listed above:
# example.py
from future.builtins import input
my_date = input("Example: March 21 | What is the date? ")
If you want to apply to all columns you can use:
df.apply(pd.value_counts)
This will apply a column based aggregation function (in this case value_counts) to each of the columns.
This is a javascript version according to Graham's code
function (columnNumber) {
var dividend = columnNumber;
var columnName = "";
var modulo;
while (dividend > 0) {
modulo = (dividend - 1) % 26;
columnName = String.fromCharCode(65 + modulo) + columnName;
dividend = parseInt((dividend - modulo) / 26);
}
return columnName;
};