Actually there are 3 places where gradle.properties
can be placed:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradlemyProject2
in your case)myProject
)Gradle looks for gradle.properties
in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).
You can find more details about it in gradle documentation here.
If you are using Eclipse then go to Windows -> Preferences -> Maven and uncheck the "Do not automatically update dependencies from remote repositories" checkbox.
This works with Maven 3 as well.
I use Nexus and this code works for me—can retrive both release and last snaphsot, depending on repository type:
server="http://example.com/nexus/content/repositories"
repo="snapshots"
name="com.exmple.server"
artifact="com/example/$name"
path=$server/$repo/$artifact
mvnMetadata=$(curl -s "$path/maven-metadata.xml")
echo "Metadata: $mvnMetadata"
jar=""
version=$( echo "$mvnMetadata" | xpath -e "//versioning/release/text()" 2> /dev/null)
if [[ $version = *[!\ ]* ]]; then
jar=$name-$version.jar
else
version=$(echo "$mvnMetadata" | xpath -e "//versioning/versions/version[last()]/text()")
snapshotMetadata=$(curl -s "$path/$version/maven-metadata.xml")
timestamp=$(echo "$snapshotMetadata" | xpath -e "//snapshot/timestamp/text()")
buildNumber=$(echo "$snapshotMetadata" | xpath -e "//snapshot/buildNumber/text()")
snapshotVersion=$(echo "$version" | sed 's/\(-SNAPSHOT\)*$//g')
jar=$name-$snapshotVersion-$timestamp-$buildNumber.jar
fi
jarUrl=$path/$version/$jar
echo $jarUrl
mkdir -p /opt/server/
wget -O /opt/server/server.jar -q -N $jarUrl
I had the same problem with Eclipse v3.7 (Indigo) and m2eclipse as my Maven plugin. The error was easily solved by explicitly stating the execution phase within the plugin definition. So my pom looks like this:
<project>
...
<build>
...
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<version>1.0</version>
<configuration>
<timestampFormat>yyyy-MM-dd_HH-mm-ss</timestampFormat>
</configuration>
<executions>
<execution>
*<phase>post-clean</phase>*
<goals>
<goal>create-timestamp</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
...
@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :
<h:inputHidden value="#{loginBean.loginStatus}"/>
and in your bean code:
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public String getLoginStatus() {
// Do your stuff here.
return loginStatus;
}
Posting here as I think it may be useful for people using Flask
with pymongo
. This is my current "best practice" setup for allowing flask to marshall pymongo bson data types.
mongoflask.py
from datetime import datetime, date
import isodate as iso
from bson import ObjectId
from flask.json import JSONEncoder
from werkzeug.routing import BaseConverter
class MongoJSONEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, (datetime, date)):
return iso.datetime_isoformat(o)
if isinstance(o, ObjectId):
return str(o)
else:
return super().default(o)
class ObjectIdConverter(BaseConverter):
def to_python(self, value):
return ObjectId(value)
def to_url(self, value):
return str(value)
app.py
from .mongoflask import MongoJSONEncoder, ObjectIdConverter
def create_app():
app = Flask(__name__)
app.json_encoder = MongoJSONEncoder
app.url_map.converters['objectid'] = ObjectIdConverter
# Client sends their string, we interpret it as an ObjectId
@app.route('/users/<objectid:user_id>')
def show_user(user_id):
# setup not shown, pretend this gets us a pymongo db object
db = get_db()
# user_id is a bson.ObjectId ready to use with pymongo!
result = db.users.find_one({'_id': user_id})
# And jsonify returns normal looking json!
# {"_id": "5b6b6959828619572d48a9da",
# "name": "Will",
# "birthday": "1990-03-17T00:00:00Z"}
return jsonify(result)
return app
Why do this instead of serving BSON or mongod extended JSON?
I think serving mongo special JSON puts a burden on client applications. Most client apps will not care using mongo objects in any complex way. If I serve extended json, now I have to use it server side, and the client side. ObjectId
and Timestamp
are easier to work with as strings and this keeps all this mongo marshalling madness quarantined to the server.
{
"_id": "5b6b6959828619572d48a9da",
"created_at": "2018-08-08T22:06:17Z"
}
I think this is less onerous to work with for most applications than.
{
"_id": {"$oid": "5b6b6959828619572d48a9da"},
"created_at": {"$date": 1533837843000}
}
The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.
Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.
https://help.github.com/articles/remove-sensitive-data/
You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.
To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.
It looked intimidating at first, but really, was easy and worked like a charm ! :-)
With date from PHP code I used something like this..
function getLocalDate(php_date) {
var dt = new Date(php_date);
var minutes = dt.getTimezoneOffset();
dt = new Date(dt.getTime() + minutes*60000);
return dt;
}
We can call it like this
var localdateObj = getLocalDate('2015-09-25T02:57:46');
From the man page for git-diff(1):
git diff [options] [<commit>] [--] [<path>…]
git diff [options] --cached [<commit>] [--] [<path>…]
git diff [options] <commit> <commit> [--] [<path>…]
git diff [options] <blob> <blob>
git diff [options] [--no-index] [--] <path> <path>
Use the 3rd one in the middle:
git diff [options] <parent-commit> <commit>
Also from the same man page, at the bottom, in the Examples section:
$ git diff HEAD^ HEAD <3>
Compare the version before the last commit and the last commit.
Admittedly it's worded a little confusingly, it would be less confusing as
Compare the most recent commit with the commit before it.
I ended up packaging this into an extension method so (1) I could generate the label and radio at once and (2) so I didn't have to fuss with specifying my own IDs:
public static class HtmlHelperExtensions
{
public static MvcHtmlString RadioButtonAndLabelFor<TModel, TProperty>(this HtmlHelper<TModel> self, Expression<Func<TModel, TProperty>> expression, bool value, string labelText)
{
// Retrieve the qualified model identifier
string name = ExpressionHelper.GetExpressionText(expression);
string fullName = self.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
// Generate the base ID
TagBuilder tagBuilder = new TagBuilder("input");
tagBuilder.GenerateId(fullName);
string idAttr = tagBuilder.Attributes["id"];
// Create an ID specific to the boolean direction
idAttr = String.Format("{0}_{1}", idAttr, value);
// Create the individual HTML elements, using the generated ID
MvcHtmlString radioButton = self.RadioButtonFor(expression, value, new { id = idAttr });
MvcHtmlString label = self.Label(idAttr, labelText);
return new MvcHtmlString(radioButton.ToHtmlString() + label.ToHtmlString());
}
}
Usage:
@Html.RadioButtonAndLabelFor(m => m.IsMarried, true, "Yes, I am married")
I suggest to place invisible(opacity = 0) button on your imageview and then handle interaction on button.
In my case, this error message was displayed when I tried downloading an app from Google Play Store using a VPN. The download only worked when I disabled the VPN. Using a VPN, downloads were only working for the apps I downloaded previously.
This looks like a censorship from Google, which is really bad for the user experience and I hope they will stop this.
Fortunately I don't use Android on my smartphone, it was on my Linux laptop using Anbox or Android x86 in VirtualBox.
My post is only relevant for SQL Server 2000 and has been tested to work in my environment.
This code accesses All possible databases of a single instance, not just a single database.
I use two temp tables to help collect the appropriate data and then dump the results into one 'Live' table.
Returned data is: DatabaseName, DatabaseTableName, Rows (in the Table), data (size of the table in KB it would seem), entry data (I find this useful for knowing when I last ran the script).
Downfall to this code is the 'data' field is not stored as an int (The chars 'KB' are kept in that field), and that would be useful (but not totally necessary) for sorting.
Hopefully this code helps someone out there and saves them some time!
CREATE PROCEDURE [dbo].[usp_getAllDBTableSizes]
AS
BEGIN
SET NOCOUNT OFF
CREATE TABLE #DatabaseTables([dbname] sysname,TableName sysname)
CREATE TABLE #AllDatabaseTableSizes(Name sysname,[rows] VARCHAR(18), reserved VARCHAR(18), data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))
DECLARE @SQL nvarchar(4000)
SET @SQL='select ''?'' AS [Database], Table_Name from [?].information_schema.tables WHERE TABLE_TYPE = ''BASE TABLE'' '
INSERT INTO #DatabaseTables(DbName, TableName)
EXECUTE sp_msforeachdb @Command1=@SQL
DECLARE AllDatabaseTables CURSOR LOCAL READ_ONLY FOR
SELECT TableName FROM #DatabaseTables
DECLARE AllDatabaseNames CURSOR LOCAL READ_ONLY FOR
SELECT DBName FROM #DatabaseTables
DECLARE @DBName sysname
OPEN AllDatabaseNames
DECLARE @TName sysname
OPEN AllDatabaseTables
WHILE 1=1 BEGIN
FETCH NEXT FROM AllDatabaseNames INTO @DBName
FETCH NEXT FROM AllDatabaseTables INTO @TName
IF @@FETCH_STATUS<>0 BREAK
INSERT INTO #AllDatabaseTableSizes
EXEC ( 'EXEC ' + @DBName + '.dbo.sp_spaceused ' + @TName)
END
--http://msdn.microsoft.com/en-us/library/aa175920(v=sql.80).aspx
INSERT INTO rsp_DatabaseTableSizes (DatabaseName, name, [rows], data)
SELECT [dbname], name, [rows], data FROM #DatabaseTables
INNER JOIN #AllDatabaseTableSizes
ON #DatabaseTables.TableName = #AllDatabaseTableSizes.Name
GROUP BY [dbname] , name, [rows], data
ORDER BY [dbname]
--To be honest, I have no idea what exact duplicates we are dropping
-- but in my case a near enough approach has been good enough.
DELETE FROM [rsp_DatabaseTableSizes]
WHERE name IN
(
SELECT name
FROM [rsp_DatabaseTableSizes]
GROUP BY name
HAVING COUNT(*) > 1
)
DROP TABLE #DatabaseTables
DROP TABLE #AllDatabaseTableSizes
CLOSE AllDatabaseTables
DEALLOCATE AllDatabaseTables
CLOSE AllDatabaseNames
DEALLOCATE AllDatabaseNames
END
--EXEC [dbo].[usp_getAllDBTableSizes]
In case you need to know, the rsp_DatabaseTableSizes table was created through:
CREATE TABLE [dbo].[rsp_DatabaseSizes](
[DatabaseName] [varchar](1000) NULL,
[dbSize] [decimal](15, 2) NULL,
[DateUpdated] [smalldatetime] NULL
) ON [PRIMARY]
GO
we may can achieve this by using schema plugin also.
In helpers/schemaPlugin.js
file
module.exports = function(schema) {
var updateDate = function(next){
var self = this;
self.updated_at = new Date();
if ( !self.created_at ) {
self.created_at = now;
}
next()
};
// update date for bellow 4 methods
schema.pre('save', updateDate)
.pre('update', updateDate)
.pre('findOneAndUpdate', updateDate)
.pre('findByIdAndUpdate', updateDate);
};
and in models/ItemSchema.js
file:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
SchemaPlugin = require('../helpers/schemaPlugin');
var ItemSchema = new Schema({
name : { type: String, required: true, trim: true },
created_at : { type: Date },
updated_at : { type: Date }
});
ItemSchema.plugin(SchemaPlugin);
module.exports = mongoose.model('Item', ItemSchema);
You can use the DataFrame method .apply()
to operate on the values in Mycol:
>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
Mycol
0 05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x:
dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
Mycol
0 2014-09-05
urllib2
is no longer available in Python 3You can try following code.
import urllib.request
res = urllib.request.urlopen('url')
output = res.read()
print(output)
You can get more idea about urllib.request
from this link.
urllib3
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'url')
print(r.status)
print( r.headers)
print(r.data)
Also if you want more details about urllib3
. follow this link.
I found in a class file outside the scope of the Page, the above way (which I always have used) didn't work.
I found a workaround in this "context" as follows:
HttpContext.Current.Session.Add("currentUser", appUser);
and
(AppUser) HttpContext.Current.Session["currentUser"]
Otherwise the compiler was expecting a string when I pointed the object at the session object.
This code on top should work:
error_reporting(E_ALL);
However, try to edit the code on the phone in the file:
error_reporting =on
You can also try to lint
with the --use-library
option, as cocoapods lint libraries as framework by default since v0.36
<input type="number" name="credit_days" pattern="[^\-]+" _x000D_
#credit_days="ngModel" class="form-control" _x000D_
placeholder="{{ 'Enter credit days' | translate }}" min="0" _x000D_
[(ngModel)]="provider.credit_days"_x000D_
onkeypress="return (event.charCode == 8 || event.charCode == 0 || _x000D_
event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= _x000D_
57" onpaste="return false">
_x000D_
map.setZoom(map.getZoom());
For some reasons, resize
trigger did not work for me, and this one worked.
This worked well for me to create a dynamic array from a class array.
var s = 0;
var songWriters = new SongWriterDetails[1];
foreach (var contributor in Contributors)
{
Array.Resize(ref songWriters, s++);
songWriters[s] = new SongWriterDetails();
songWriters[s].DisplayName = contributor.Name;
songWriters[s].PartyId = contributor.Id;
s++;
}
Here is a simple and performant solution for a cryptographically secure random string.
package main
import (
"crypto/rand"
"unsafe"
"fmt"
)
var alphabet = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func main() {
fmt.Println(generate(16))
}
func generate(size int) string {
b := make([]byte, size)
rand.Read(b)
for i := 0; i < size; i++ {
b[i] = alphabet[b[i] / 5]
}
return *(*string)(unsafe.Pointer(&b))
}
Benchmark
Benchmark 95.2 ns/op 16 B/op 1 allocs/op
Manage multiple java version in MAC using jenv
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
brew install jenv
echo 'eval "$(jenv init -)"' >> ~/.bash_profile
brew tap homebrew/cask-versions
brew search java
brew install cask java6
jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Note:- if you get error like “”ln: /Users//.jenv/versions/oracle64-1.8.0.231: No such file or directory, then run following:-
mkdir -p /Users//.jenv/versions/oracle64-1.8.0.231
jenv rehash
jenv versions
jenv global oracle64-1.8.0.231
jenv local oracle64-1.6.0.65
jenv exec bash
echo $JAVA_HOME
From the offical docs: (http://api.jquery.com/hover/)
The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.
you can use the UNION ALL
keyword for this.
Here is the MSDN doc to do it in T-SQL http://msdn.microsoft.com/en-us/library/ms180026.aspx
UNION ALL - combines the result set
UNION- Does something like a Set Union and doesnt output duplicate values
For the difference with an example: http://sql-plsql.blogspot.in/2010/05/difference-between-union-union-all.html
if (!String.prototype.hasOwnProperty('addSlashes')) {
String.prototype.addSlashes = function() {
return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
.replace(/'/g, ''') /* The 4 other predefined entities, required. */
.replace(/"/g, '"')
.replace(/\\/g, '\\\\')
.replace(/</g, '<')
.replace(/>/g, '>').replace(/\u0000/g, '\\0');
}
}
Usage: alert(str.addSlashes());
As pointed out already, most standard implementations of List
are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.
if the absolute element has a width,you can use the code below
.divtagABS{
width:300px;
positon:absolute;
left:0;
right:0;
margin:0 auto;
}
To convert a string to lower case in Python, use something like this.
list.append(sentence.lower())
I found this in the first result after searching for "python upper to lower case".
Using this attribute is definitely unsafe.
One particular thing it breaks is the ability of a union
which contains two or more structs to write one member and read another if the structs have a common initial sequence of members. Section 6.5.2.3 of the C11 standard states:
6 One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible. Tw o structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.
...
9 EXAMPLE 3 The following is a valid fragment:
union { struct { int alltypes; }n; struct { int type; int intnode; } ni; struct { int type; double doublenode; } nf; }u; u.nf.type = 1; u.nf.doublenode = 3.14; /* ... */ if (u.n.alltypes == 1) if (sin(u.nf.doublenode) == 0.0) /* ... */
When __attribute__((packed))
is introduced it breaks this. The following example was run on Ubuntu 16.04 x64 using gcc 5.4.0 with optimizations disabled:
#include <stdio.h>
#include <stdlib.h>
struct s1
{
short a;
int b;
} __attribute__((packed));
struct s2
{
short a;
int b;
};
union su {
struct s1 x;
struct s2 y;
};
int main()
{
union su s;
s.x.a = 0x1234;
s.x.b = 0x56789abc;
printf("sizeof s1 = %zu, sizeof s2 = %zu\n", sizeof(struct s1), sizeof(struct s2));
printf("s.y.a=%hx, s.y.b=%x\n", s.y.a, s.y.b);
return 0;
}
Output:
sizeof s1 = 6, sizeof s2 = 8
s.y.a=1234, s.y.b=5678
Even though struct s1
and struct s2
have a "common initial sequence", the packing applied to the former means that the corresponding members don't live at the same byte offset. The result is the value written to member x.b
is not the same as the value read from member y.b
, even though the standard says they should be the same.
Refer to example at this link. It may be help to you.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx
void Page_Load(Object sender, EventArgs e)
{
// Load data for the DropDownList control only once, when the
// page is first loaded.
if(!IsPostBack)
{
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
ColorList.DataSource = CreateDataSource();
ColorList.DataTextField = "ColorTextField";
ColorList.DataValueField = "ColorValueField";
// Bind the data to the control.
ColorList.DataBind();
// Set the default selected item, if desired.
ColorList.SelectedIndex = 0;
}
}
void Selection_Change(Object sender, EventArgs e)
{
// Set the background color for days in the Calendar control
// based on the value selected by the user from the
// DropDownList control.
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
}
Your interior <div>
elements should likely both be float:left
. Divs size to 100% the size of their container width automatically. Try using display:inline-block
instead of width:auto
on the container div. Or possibly float:left
the container and also apply overflow:auto
. Depends on what you're after exactly.
This is common greatest-n-per-group problem, which already has well tested and highly optimized solutions. Personally I prefer the left join solution by Bill Karwin (the original post with lots of other solutions).
Note that bunch of solutions to this common problem can surprisingly be found in the one of most official sources, MySQL manual! See Examples of Common Queries :: The Rows Holding the Group-wise Maximum of a Certain Column.
Try using:
@ECHO off
ECHO Hello World!
START /MAX D:\SA\pro\hello.txt
You are trying to store a Unicode codepoint \u201c
using an encoding ISO-8859-1 / Latin-1
that can't describe that codepoint. Either you might need to alter the database to use utf-8, and store the string data using an appropriate encoding, or you might want to sanitise your inputs prior to storing the content; i.e. using something like Sam Ruby's excellent i18n guide. That talks about the issues that windows-1252
can cause, and suggests how to process it, plus links to sample code!
The right way to do this is:
composer remove jenssegers/mongodb --update-with-dependencies
I must admit the flag here is not quite obvious as to what it will do.
composer remove jenssegers/mongodb
As of v1.0.0-beta2 --update-with-dependencies
is the default and is no longer required.
Dashes (-
) have no significance other than making the number more readable, so you might as well include them.
Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the +
sign is always necessary. The +
sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.
Using your example number, when calling from China, people would need to dial:
00-1-555-555-1212
And from Russia, they would dial
810-1-555-555-1212
The +
sign solves this issue by allowing you to omit the international dialing prefix.
After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.
Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:
<a href="tel:+1-555-555-1212">+1-555-555-1212</a>
Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0
), you need to omit it because the number must be in international format.
If you're needing something simple, would this fit the bill?
Map<K, V> myCache = Collections.synchronizedMap(new WeakHashMap<K, V>());
It wont save to disk, but you said you wanted simple...
Links:
(As Adam commented, synchronising a map has a performance hit. Not saying the idea doesn't have hairs on it, but would suffice as a quick and dirty solution.)
(?i)^[ \r\n]*CTR (?i) -- case insensitive -- Remove if case sensitive. [ \r\n] -- ignore space and new lines * -- 0 or more times the same CTR - your starts with string.
This can be done with something like this:
# foo.py
class Foo:
def method_1():
results = uses_some_other_method()
# testing.py
from mock import patch
@patch('Foo.uses_some_other_method', return_value="specific_value"):
def test_some_other_method(mock_some_other_method):
foo = Foo()
the_value = foo.method_1()
assert the_value == "specific_value"
Here's a source that you can read: Patching in the wrong place
To meet these criteria: modify original list in situ, no list copies, only one pass, works, a traditional solution is to iterate backwards:
for i in xrange(len(somelist) - 1, -1, -1):
element = somelist[i]
do_action(element)
if check(element):
del somelist[i]
Bonus: Doesn't do len(somelist)
on each iteration. Works on any version of Python (at least as far back as 1.5.2) ... s/xrange/range/ for 3.X.
Update: If you want to iterate forwards, it's possible, just trickier and uglier:
i = 0
n = len(somelist)
while i < n:
element = somelist[i]
do_action(element)
if check(element):
del somelist[i]
n = n - 1
else:
i = i + 1
Here is a better way for doing it. Hope this helps
protected void onPostExecute(String result) {
Log.v(TAG + " result);
if (!result.equals("")) {
// Set up variables for API Call
ArrayList<String> list = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}//end for
} catch (JSONException e) {
Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
e.printStackTrace();
}
adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText( ListViewData.this, "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
adapter.notifyDataSetChanged();
...
When you call a Linq statement like this:
// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));
You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:
var count = Enumerable.Count(x, s => s.StartsWith("x"));
So the error you are getting above is because the first parameter, source
(which would be x
in the sample above) is null.
Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:
To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.
Option Explicit
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
There are still some small thing with the code above that you should notice:
.Close
and DisplayAlerts=True
should be in a finally clause, but I don't know how to do it in VBA- 5
to - 4
when setting MyFileName.Edit: put Local:=True
to save with my locale CSV delimiter.
My first impulse was to google for "php math" and I discovered that there's a core math library function called "round()" that likely is what you want.
I think this thread was quite old. I just mention another case, that onSaveInstanceState()
will also be called, is when you call Activity.moveTaskToBack(boolean nonRootActivity)
.
I had the same problem, and it came from a wrong client_id / Facebook App ID.
Did you switch your Facebook app to "public" or "online ? When you do so, Facebook creates a new app with a new App ID.
You can compare the "client_id" parameter value in the url with the one in your Facebook dashboard.
Also Make sure your app is public. Click on + Add product Now go to products => Facebook Login Now do the following:
Valid OAuth redirect URIs : example.com/
I have added a helper da()
to Laravel which in fact works as an alias for dd($object->toArray())
Here is the Gist: https://gist.github.com/TommyZG/0505eb331f240a6324b0527bc588769c
In my case the issue was that Virtual directory was not created.
Hope you are using Python 3 ,
Str are unicode by default, so please
Replace Unicode
function with String Str
function.
if isinstance(unicode_or_str, str): ##Replaces with str
text = unicode_or_str
decoded = False
Very simple and surprisingly fast: (without numpy or pandas)
str( myDate ) == 'NaT' # True if myDate is NaT
Ok, it's a little nasty, but given the ambiguity surrounding 'NaT' it does the job nicely.
It's also useful when comparing two dates either of which might be NaT as follows:
str( date1 ) == str( date1 ) # True
str( date1 ) == str( NaT ) # False
str( NaT ) == str( date1 ) # False
wait for it...
str( NaT ) == str( Nat ) # True (hooray!)
Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR
set these variables:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
export PATH=$JAVA_HOME/bin:$PATH
Run your app and fun :)
(Minor update: put variable value in quote)
for /f "tokens=8 delims=\" %a in ('reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist" ^| find "UsrClass.dat"') do echo %a
Just to clarify, there is a big difference between these two actions, as suggested by Jean-François Corbett.
One action is to copy / load the actual data FROM the Range("A2:A9")
INTO a Variant Array called vArray
(Changed to avoid confusion between Variant Array and Sheet both called Src):
vArray = Sheets("Src").Range("A2:A9").Value
while the other simply sets up a Range variable (SrcRange) with the ADDRESS of the range Sheets("Src").Range("A2:A9")
:
Set SrcRange = Sheets("Src").Range("A2:A9")
In this case, the data is not copied, and remains where it is, but can now be accessed in much the same way as an Array. That is often perfectly adequate, but if you need to repeatedly access, test or calculate with that data, loading it into an Array first will be MUCH faster.
For example, say you want to check a "database" (large sheet) against a list of known Suburbs and Postcodes. Both sets of data are in separate sheets, but if you want it to run fast, load the suburbs and postcodes into an Array (lives in memory), then run through each line of the main database, testing against the array data. This will be much faster than if you access both from their original sheets.
Memory rotation may be an issue here, since every boxing of an int larger than or equal to 128 causes an object allocation (see Integer.valueOf(int)). Although the garbage collector very efficiently deals with short-lived objects, performance will suffer to some degree.
If you know that the number of increments made will largely outnumber the number of keys (=words in this case), consider using an int holder instead. Phax already presented code for this. Here it is again, with two changes (holder class made static and initial value set to 1):
static class MutableInt {
int value = 1;
void inc() { ++value; }
int get() { return value; }
}
...
Map<String,MutableInt> map = new HashMap<String,MutableInt>();
MutableInt value = map.get(key);
if (value == null) {
value = new MutableInt();
map.put(key, value);
} else {
value.inc();
}
If you need extreme performance, look for a Map implementation which is directly tailored towards primitive value types. jrudolph mentioned GNU Trove.
By the way, a good search term for this subject is "histogram".
Note: Use CSS counters
to create nested numbering in a modern browser. See the accepted answer. The following is for historical interest only.
If the browser supports content
and counter
,
.foo {_x000D_
counter-reset: foo;_x000D_
}_x000D_
.foo li {_x000D_
list-style-type: none;_x000D_
}_x000D_
.foo li::before {_x000D_
counter-increment: foo;_x000D_
content: "1." counter(foo) " ";_x000D_
}
_x000D_
<ol class="foo">_x000D_
<li>uno</li>_x000D_
<li>dos</li>_x000D_
<li>tres</li>_x000D_
<li>cuatro</li>_x000D_
</ol>
_x000D_
Tuples are immutable and not supposed to be changed - that is what the list type is for. You could replace each tuple by originalTuple + (newElement,)
, thus creating a new tuple. For example:
t = (1,2,3)
t = t + (1,)
print t
(1,2,3,1)
But I'd rather suggest to go with lists from the beginning, because they are faster for inserting items.
And another hint: Do not overwrite the built-in name list
in your program, rather call the variable l
or some other name. If you overwrite the built-in name, you can't use it anymore in the current scope.
is this for display purposes? if so you really should consider separating your display form your logic and use style sheets for formatting. being server side php should really allow providing and accepting data. while you could surely use php to do what you are asking I am a very firm believer in keeping display and logic with as much separation as possible. with styles you can do all of your typesetting.
give output class wrappers and style accordingly.
If you are not too worried about browser support, there is a way to rebind the 'this' reference in the function called by the event. It will normally point to the element that generated the event when the function is executed, which is not always what you want. The tricky part is to at the same time be able to remove the very same event listener, as shown in this example: http://jsfiddle.net/roenbaeck/vBYu3/
/*
Testing that the function returned from bind is rereferenceable,
such that it can be added and removed as an event listener.
*/
function MyImportantCalloutToYou(message, otherMessage) {
// the following is necessary as calling bind again does
// not return the same function, so instead we replace the
// original function with the one bound to this instance
this.swap = this.swap.bind(this);
this.element = document.createElement('div');
this.element.addEventListener('click', this.swap, false);
document.body.appendChild(this.element);
}
MyImportantCalloutToYou.prototype = {
element: null,
swap: function() {
// now this function can be properly removed
this.element.removeEventListener('click', this.swap, false);
}
}
The code above works well in Chrome, and there's probably some shim around making "bind" compatible with other browsers.
<div style="width:100%;">
<div style="margin-left:45px;">
<asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
</div>
</div>
In my opinion, the important thing about the default export is that it can be imported with any name!
If there is a file, foo.js, which exports default:
export default function foo(){}
_x000D_
it can be imported in bar.js using:
import bar from 'foo'
import Bar from 'foo' // Or ANY other name you wish to assign to this import
_x000D_
In short, functools.wraps is just a regular function. Let's consider this official example. With the help of the source code, we can see more details about the implementation and the running steps as follows:
wrapper=O1.__call__(wrapper)
Checking the implementation of __call__, we see that after this step, (the left hand side )wrapper becomes the object resulted by self.func(*self.args, *args, **newkeywords) Checking the creation of O1 in __new__, we know self.func is the function update_wrapper. It uses the parameter *args, the right hand side wrapper, as its 1st parameter. Checking the last step of update_wrapper, one can see the right hand side wrapper is returned, with some of attributes modified as needed.
how about sysdate?
SELECT field,datetime_field
FROM database
WHERE datetime_field > (sysdate-1)
You have at least these 3 issues:
display
yet in your javascript you attempt to get element myDiv
which is not even defined in your markup.You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.
I don't think you can do this in XML (at least not in Android), but I've found a good solution posted here that looks like it'd be a great help!
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient lg = new LinearGradient(0, 0, width, height,
new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);
return lg;
}
};
PaintDrawable p=new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
Basically, the int array allows you to select multiple color stops, and the following float array defines where those stops are positioned (from 0 to 1). You can then, as stated, just use this as a standard Drawable.
Edit: Here's how you could use this in your scenario. Let's say you have a Button defined in XML like so:
<Button
android:id="@+id/thebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press Me!"
/>
You'd then put something like this in your onCreate() method:
Button theButton = (Button)findViewById(R.id.thebutton);
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient lg = new LinearGradient(0, 0, 0, theButton.getHeight(),
new int[] {
Color.LIGHT_GREEN,
Color.WHITE,
Color.MID_GREEN,
Color.DARK_GREEN }, //substitute the correct colors for these
new float[] {
0, 0.45f, 0.55f, 1 },
Shader.TileMode.REPEAT);
return lg;
}
};
PaintDrawable p = new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
theButton.setBackground((Drawable)p);
I cannot test this at the moment, this is code from my head, but basically just replace, or add stops for the colors that you need. Basically, in my example, you would start with a light green, fade to white slightly before the center (to give a fade, rather than a harsh transition), fade from white to mid green between 45% and 55%, then fade from mid green to dark green from 55% to the end. This may not look exactly like your shape (Right now, I have no way of testing these colors), but you can modify this to replicate your example.
Edit: Also, the 0, 0, 0, theButton.getHeight()
refers to the x0, y0, x1, y1 coordinates of the gradient. So basically, it starts at x = 0 (left side), y = 0 (top), and stretches to x = 0 (we're wanting a vertical gradient, so no left to right angle is necessary), y = the height of the button. So the gradient goes at a 90 degree angle from the top of the button to the bottom of the button.
Edit: Okay, so I have one more idea that works, haha. Right now it works in XML, but should be doable for shapes in Java as well. It's kind of complex, and I imagine there's a way to simplify it into a single shape, but this is what I've got for now:
green_horizontal_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<corners
android:radius="3dp"
/>
<gradient
android:angle="0"
android:startColor="#FF63a34a"
android:endColor="#FF477b36"
android:type="linear"
/>
</shape>
half_overlay.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid
android:color="#40000000"
/>
</shape>
layer_list.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:drawable="@drawable/green_horizontal_gradient"
android:id="@+id/green_gradient"
/>
<item
android:drawable="@drawable/half_overlay"
android:id="@+id/half_overlay"
android:top="50dp"
/>
</layer-list>
test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<TextView
android:id="@+id/image_test"
android:background="@drawable/layer_list"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:gravity="center"
android:text="Layer List Drawable!"
android:textColor="@android:color/white"
android:textStyle="bold"
android:textSize="26sp"
/>
</RelativeLayout>
Okay, so basically I've created a shape gradient in XML for the horizontal green gradient, set at a 0 degree angle, going from the top area's left green color, to the right green color. Next, I made a shape rectangle with a half transparent gray. I'm pretty sure that could be inlined into the layer-list XML, obviating this extra file, but I'm not sure how. But okay, then the kind of hacky part comes in on the layer_list XML file. I put the green gradient as the bottom layer, then put the half overlay as the second layer, offset from the top by 50dp. Obviously you'd want this number to always be half of whatever your view size is, though, and not a fixed 50dp. I don't think you can use percentages, though. From there, I just inserted a TextView into my test.xml layout, using the layer_list.xml file as my background. I set the height to 100dp (twice the size of the offset of the overlay), resulting in the following:
Tada!
One more edit: I've realized you can just embed the shapes into the layer list drawable as items, meaning you don't need 3 separate XML files any more! You can achieve the same result combining them like so:
layer_list.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<corners
android:radius="3dp"
/>
<gradient
android:angle="0"
android:startColor="#FF63a34a"
android:endColor="#FF477b36"
android:type="linear"
/>
</shape>
</item>
<item
android:top="50dp"
>
<shape
android:shape="rectangle"
>
<solid
android:color="#40000000"
/>
</shape>
</item>
</layer-list>
You can layer as many items as you like this way! I may try to play around and see if I can get a more versatile result through Java.
I think this is the last edit...: Okay, so you can definitely fix the positioning through Java, like the following:
TextView tv = (TextView)findViewById(R.id.image_test);
LayerDrawable ld = (LayerDrawable)tv.getBackground();
int topInset = tv.getHeight() / 2 ; //does not work!
ld.setLayerInset(1, 0, topInset, 0, 0);
tv.setBackgroundDrawable(ld);
However! This leads to yet another annoying problem in that you cannot measure the TextView until after it has been drawn. I'm not quite sure yet how you can accomplish this...but manually inserting a number for topInset does work.
I lied, one more edit
Okay, found out how to manually update this layer drawable to match the height of the container, full description can be found here. This code should go in your onCreate() method:
final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LayerDrawable ld = (LayerDrawable)tv.getBackground();
ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0);
}
});
And I'm done! Whew! :)
->*
or .*
operators, it's a must.It prevents you from writing something like
void foo(Bar *p) { if (++p->*member > 0) { ... } }
which I almost did right now, and which probably doesn't do what you intend.
What I intended to say was
void foo(Bar *p) { if (++(p->*member) > 0) { ... } }
and if I had put a const
in between Bar *
and p
, the compiler would have told me that.
I'm a beginner and wrote a script to ping multiple hosts.To ping multiple host you can use ipaddress module.
import ipaddress
from subprocess import Popen, PIPE
net4 = ipaddress.ip_network('192.168.2.0/24')
for x in net4.hosts():
x = str(x)
hostup = Popen(["ping", "-c1", x], stdout=PIPE)
output = hostup.communicate()[0]
val1 = hostup.returncode
if val1 == 0:
print(x, "is pinging")
else:
print(x, "is not responding")
When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.
Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.
static final String STATE_USER = "user";
private String mUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mUser = savedInstanceState.getString(STATE_USER);
} else {
// Probably initialize members with default values for a new instance
mUser = "NewUser";
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
In my case the problem was with hostname/public DNS.I associated Elastice IP with my instance and then my DNS got changed. I was trying to connect with old DNS. Changing it to new solved the problem. You can check the detail by going to your instance and then clicking view details.
you can use the following line of code as well
per_page = parseInt(req.query.per_page) || 10
page_no = parseInt(req.query.page_no) || 1
var pagination = {
limit: per_page ,
skip:per_page * (page_no - 1)
}
users = await User.find({<CONDITION>}).limit(pagination.limit).skip(pagination.skip).exec()
this code will work in latest version of mongo
Here i have designed the list by the following design image. My listitem filename is Propertylistitem.xml and cellborder.xml is used drawable shape for the cellborder output, are show in this image. necessary code i added here.
FileName:propertylistitem.xml
<TableLayout... >
<TableRow... >
<TextView ...
android:background="@drawable/cellborder"
android:text="Amount"/>
</TableRow>
<TableRow... >
<TextView...
android:background="@drawable/cellborder"
android:text="5000"/>
</TableRow>
</TableLayout>
filename:cellborder.xml Here i just want only border in my design, so i put comment the solid color tag.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<!-- <solid android:color="#dc6888"/> -->
<stroke android:width="0.1dp" android:color="#ffffff"
/>
<padding android:left="0dp" android:top="0dp"
android:right="0dp" android:bottom="0dp" />
</shape>
If you want to try it without the try catch block, can use the following method, Create a intent and set the package of the app which you want to verify
val intent = Intent(Intent.ACTION_VIEW)
intent.data = uri
intent.setPackage("com.example.packageofapp")
and the call the following method to check if the app is installed
fun isInstalled(intent:Intent) :Boolean{
val list = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return list.isNotEmpty()
}
RatingBar mRating=(RatingBar)findViewById(R.id.rating);
LayerDrawable layerDrawable=(LayerDrawable)mRating.getProgressDrawable();
layerDrawable.getDrawable(2).setColorFilter(Color.parseColor
("#32CD32"), PorterDuff.Mode.SRC_ATOP);
for me its working....
To answer the question posted in the comment above - try something like this:
unsigned short int x = 65529U;
short int y = (short int)x;
printf("%d\n", y);
or
unsigned short int x = 65529U;
short int y = 0;
memcpy(&y, &x, sizeof(short int);
printf("%d\n", y);
You can get visitors country and city using ipstack geo API.You need to get your own ipstack API and then use the code below:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$api_key = "YOUR_API_KEY";
$freegeoipjson = file_get_contents("http://api.ipstack.com/".$ip."?access_key=".$api_key."");
$jsondata = json_decode($freegeoipjson);
$countryfromip = $jsondata->country_name;
echo "Country: ". $countryfromip ."";
?>
Source: Get visitors country and city in PHP using ipstack API
employees.ToList().Foreach(u=> { u.SomeProperty = null; u.OtherProperty = null; });
Notice that I used semicolons after each set statement
that is -->
u.SomeProperty = null;
u.OtherProperty = null;
I hope this will definitely solve your problem.
This code will print an asterisk instead of every letter.
import sys
import msvcrt
passwor = ''
while True:
x = msvcrt.getch()
if x == '\r':
break
sys.stdout.write('*')
passwor +=x
print '\n'+passwor
Set the application pool to 2.0, I did it and worked.
ValueError: cannot convert float NaN to integer
From v0.24, you actually can. Pandas introduces Nullable Integer Data Types which allows integers to coexist with NaNs.
Given a series of whole float numbers with missing data,
s = pd.Series([1.0, 2.0, np.nan, 4.0])
s
0 1.0
1 2.0
2 NaN
3 4.0
dtype: float64
s.dtype
# dtype('float64')
You can convert it to a nullable int type (choose from one of Int16
, Int32
, or Int64
) with,
s2 = s.astype('Int32') # note the 'I' is uppercase
s2
0 1
1 2
2 NaN
3 4
dtype: Int32
s2.dtype
# Int32Dtype()
Your column needs to have whole numbers for the cast to happen. Anything else will raise a TypeError:
s = pd.Series([1.1, 2.0, np.nan, 4.0])
s.astype('Int32')
# TypeError: cannot safely cast non-equivalent float64 to int32
For some reason
if (strictBounds.contains(map.getCenter())) return;
didnt work for me (maybe a southern hemisphere issue). I had to change it to:
function checkBounds() {
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if(x < minX || x > maxX || y < minY || y > maxY) {
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
}
}
Hope it will help someone.
Use the ToDictionary
method directly.
var result =
// as Jon Skeet pointed out, OrderBy is useless here, I just leave it
// show how to use OrderBy in a LINQ query
myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
.ToDictionary(mc => mc.KeyProp.ToString(),
mc => mc.ValueProp.ToString(),
StringComparer.OrdinalIgnoreCase);
Use toArray(T[] a) method:
String[] array = set.toArray(new String[0]);
It worked to me:
String javaHome = System.getProperty("java.home");
File f = new File(javaHome);
f = new File(f, "bin");
f = new File(f, "javaw.exe"); //or f = new File(f, "javaws.exe"); //work too
System.out.println(f + " exists: " + f.exists());
Check this out.
using the android
command to create avd
you can specify where to place files.
-p --path Location path of the directory where the new AVD will be created
Generally, string concatenation should be prefered over String.format
. The latter has two main disadvantages:
By point 1, I mean that it is not possible to understand what a String.format()
call is doing in a single sequential pass. One is forced to go back and forth between the format string and the arguments, while counting the position of the arguments. For short concatenations, this is not much of an issue. In these cases however, string concatenation is less verbose.
By point 2, I mean that the important part of the building process is encoded in the format string (using a DSL). Using strings to represent code has many disadvantages. It is not inherently type-safe, and complicates syntax-highlighting, code analysis, optimization, etc.
Of course, when using tools or frameworks external to the Java language, new factors can come into play.
I got this error with my own code. My problem was that I had duplicate keys in the config file.
just put the autoplay="false" on source tag.. :)
If you are using AngularJS you need to pass the body params as string:
factory.getToken = function(person_username) {
console.log('Getting DI Token');
var url = diUrl + "/token";
return $http({
method: 'POST',
url: url,
data: 'grant_type=password&[email protected]&password=mypass',
responseType:'json',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
};
It is often required to move both body and html objects together.
$('html,body').animate({
scrollTop: $("#divToBeScrolledTo").offset().top
});
ShiftyThomas is right:
$("#divToBeScrolledTo").offset().top + 10 // +10 (pixels) reduces the margin.
So to increase the margin use:
$("#divToBeScrolledTo").offset().top - 10 // -10 (pixels) would increase the margin between the top of your window and your element.
This is most efficient way i can think of as doesn't include Array.indexOf()
or Array.lastIndexOf()
which have complexity of O(n) and using inside any loop of complexity O(n) will make complete complexity O(n^2).
My first loop have complexity of O(n/2) or O((n/2) + 1), as complexity of search in hash is O(1). The second loop worst complexity when there's no duplicate in array is O(n) and best complexity when every element have a duplicate is O(n/2).
function duplicates(arr) {
let duplicates = [],
d = {},
i = 0,
j = arr.length - 1;
// Complexity O(n/2)
while (i <= j) {
if (i === j)
d[arr[i]] ? d[arr[i]] += 1 : d[arr[i]] = 1; // Complexity O(1)
else {
d[arr[i]] ? d[arr[i]] += 1 : d[arr[i]] = 1; // Complexity O(1)
d[arr[j]] ? d[arr[j]] += 1 : d[arr[j]] = 1; // Complexity O(1)
}
++i;
--j;
}
// Worst complexity O(n), best complexity O(n/2)
for (let k in d) {
if (d[k] > 1)
duplicates.push(k);
}
return duplicates;
}
console.log(duplicates([5,6,4,9,2,3,5,3,4,1,5,4,9]));
console.log(duplicates([2,3,4,5,4,3,4]));
console.log(duplicates([4,5,2,9]));
console.log(duplicates([4,5,2,9,2,5,9,4]));
I had this problem and I was able to fix this by updating npm
sudo npm update -g npm
Before the update, the result of npm info graceful-fs | grep 'version:'
was:
version: '3.3.12'
After the update the result is:
version: '3.9.3'
The outfile should be in binary mode.
outFile = open('output.xml', 'wb')
TL:DR version:
//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)
Either you didn't set your picker to select the row (which you say you seem to have done but anyhow):
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated
OR you didn't use the the following method to get the selected item from your picker
- (NSInteger)selectedRowInComponent:(NSInteger)component
This will get the selected row as Integer from your picker and do as you please with it. This should do the trick for yah. Good luck.
Anyhow read the ref: https://developer.apple.com/documentation/uikit/uipickerview
EDIT:
An example of manually setting and getting of a selected row in a UIPickerView:
the .h file:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
UIPickerView *picker;
NSMutableArray *source;
}
@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;
-(void)pressed;
@end
the .m file:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize picker;
@synthesize source;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.view.backgroundColor = [UIColor yellowColor];
self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];
UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
[pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
pressme.backgroundColor = [UIColor lightGrayColor];
[pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pressme];
self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
self.picker.delegate = self;
self.picker.dataSource = self;
[self.view addSubview:self.picker];
//This is how you manually SET(!!) a selection!
[self.picker selectRow:2 inComponent:0 animated:YES];
}
//logs the current selection of the picker manually
-(void)pressed
{
//This is how you manually GET(!!) a selection
int row = [self.picker selectedRowInComponent:0];
NSLog(@"%@", [source objectAtIndex:row]);
}
- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return [source count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
return [source objectAtIndex:row];
}
#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
// NSLog(@"%@", [source objectAtIndex:row]);
}
@end
EDIT for Swift solution (Source: Dan Beaulieu's answer)
Define an Outlet:
@IBOutlet weak var pickerView: UIPickerView! // for example
Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:
pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)
If you inspect the Swift 2.0 framework you'll see .selectRow defined as:
func selectRow(row: Int, inComponent component: Int, animated: Bool)
option clicking .selectRow in Xcode displays the following:
I wanto to display the count of rows in the excel sheet after the filter option has been applied.
So I declared the count of last rows as a variable that can be added to the Msgbox
Sub lastrowcall()
Dim hm As Worksheet
Dim dm As Worksheet
Set dm = ActiveWorkbook.Sheets("datecopy")
Set hm = ActiveWorkbook.Sheets("Home")
Dim lngStart As String, lngEnd As String
lngStart = hm.Range("E23").Value
lngEnd = hm.Range("E25").Value
Dim last_row As String
last_row = dm.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox ("Number of test results between the selected dates " + lngStart + "
and " + lngEnd + " are " + last_row + ". Please Select Yes to continue
Analysis")
End Sub
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. The basic method to create a Series is to call:
s = pd.Series(data, index=index)
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
Your function prototype states your function will return a char. Thus, you can't return a string in your function.
I would just create a separate CSS class:
.ButtonClicked {
background-color:red;
}
And then add the class on click:
$('#ButtonId').on('click',function(){
!$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
});
This should do what you're looking for, showing by this jsFiddle. If you're curious about the logic with the ?
and such, its called ternary (or conditional) operators, and its just a concise way to do the simple if logic to check if the class has already been added.
You can also create the ability to have an "on/off" switch feel by toggling the class:
$('#ButtonId').on('click',function(){
$(this).toggleClass('ButtonClicked');
});
Shown by this jsFiddle. Just food for thought.
I like this example, which for now, leaves out the check which you could add inside the while block:
ifstream iFile("input.txt"); // input.txt has integers, one per line
int x;
while (iFile >> x)
{
cerr << x << endl;
}
Not sure how safe it is...
A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).
Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl
) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).
As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.
CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.
Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.
The usual recommendation is to use many processes rather than many threads.
No need to use .each
. click
already binds to all div
occurrences.
$('div').click(function(e) {
..
});
Note: use hard binding such as .click
to make sure dynamically loaded elements don't get bound.
According to this site add
CONFIG += c++11
to your .pro file (see at the bottom of that web page). It requires Qt 5.
The other answers, suggesting
QMAKE_CXXFLAGS += -std=c++11
(or QMAKE_CXXFLAGS += -std=c++0x
)
also work with Qt 4.8 and gcc / clang.
Assuming you already know lists are of equal size, the following will guarantee True if and only if two vectors are exactly the same (including order)
functools.reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, listA, ListB), True)
Example:
>>> from functools import reduce
>>> def compvecs(a,b):
... return reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, a, b), True)
...
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compvecs(a=[1,2,3,4], b=[1,2,3,4])
True
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compare_vectors(a=[1,2,3,4], b=[1,2,2,4])
False
>>>
I had the same problem but I was confused with @Vladislav's answer and couldn't seem to find the solution from that. Of course, my problem may not be exactly the same as I encountered the problem when trying to upgrade XAMPP, but it also gave the same Error 1067 message.
With further search I found this:
The answer from that is straightforward, that is, to completely clean up the folder, which doesn't always happen. As in regards to XAMPP, I guess I backed up the necessary files first (data folder from mysql folder and the htdocs folder). Uninstall XAMPP. Check the xampp folder for any content that remains and delete everything. You may want to reboot afterwards, just in case. Then reinstall XAMPP. Copy the backed-up folders back to their respective places, and hopefully, mySql will work again in XAMPP.
This should solve the issue.
Chaining is cool, why dismiss it?
Anyway, here is another option in one replace:
string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
The replace will choose "" if match=="#", " " if not.
[Update] For a more generic solution, you could store your replacement strings in an object:
var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
Use the new viewWillTransitionToSize(_:withTransitionCoordinator:)
If it is possible to change the sequence of the lines you could do:
^(.*\r?\n)\1+
How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n)
and captures the line in \1
then it continues and tries to find \1
one or more times (+
) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.
The \r?\n
should deal nicely with Windows and Unix lineendings.
So, something like
DECLARE @i AS FLOAT = 2
SELECT @i / 3
SELECT CAST(@i / 3 AS DECIMAL(18,2))
I would however recomend that this be done in the UI/Report layer, as this will cuase loss of precision.
For those using Gradle (instead of Maven), referencing here:
The main class can also be configured explicitly using the task’s mainClassName property:
bootJar {
mainClassName = 'com.example.ExampleApplication'
}
Alternatively, the main class name can be configured project-wide using the mainClassName property of the Spring Boot DSL:
springBoot {
mainClassName = 'com.example.ExampleApplication'
}
There is an Oracle article I found regarding Java 9 module system
By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.
As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible
for JDK8 and JDK9 are instructive. Specifically, JDK9 added
This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:
- C and D are in the same module.
- The member is public and D is public in a package that the module containing D exports to at least the module containing C.
- The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
- D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.
which highlights the significance of modules and their exports (in Java 9)
java.util.Collection#Iterator is a good example of a Factory Method. Depending on the concrete subclass of Collection you use, it will create an Iterator implementation. Because both the Factory superclass (Collection) and the Iterator created are interfaces, it is sometimes confused with AbstractFactory. Most of the examples for AbstractFactory in the the accepted answer (BalusC) are examples of Factory, a simplified version of Factory Method, which is not part of the original GoF patterns. In Facory the Factory class hierarchy is collapsed and the factory uses other means to choose the product to be returned.
An abstract factory has multiple factory methods, each creating a different product. The products produced by one factory are intended to be used together (your printer and cartridges better be from the same (abstract) factory). As mentioned in answers above the families of AWT GUI components, differing from platform to platform, are an example of this (although its implementation differs from the structure described in Gof).
Create a new file called files.txt and paste the URLs one per line. Then run the following command.
xargs -n 1 curl -O < files.txt
source: https://www.abeautifulsite.net/downloading-a-list-of-urls-automatically
you don't need to set the width of header in css, just put the background image as center using this code:
background: url("images/logo.png") no-repeat top center;
or you can just use img
tag and put align="center"
in the div
It depends mostly on how much the repository is used. With one user checking in once a day and a branch/merge/etc operation once a week you probably don't need to run it more than once a year.
With several dozen developers working on several dozen projects each checking in 2-3 times a day, you might want to run it nightly.
It won't hurt to run it more frequently than needed, though.
What I'd do is run it now, then a week from now take a measurement of disk utilization, run it again, and measure disk utilization again. If it drops 5% in size, then run it once a week. If it drops more, then run it more frequently. If it drops less, then run it less frequently.
You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T>
here - usually ArrayList<T>
, but with plenty of other alternatives available.
You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T>
to start with.
If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:
For Kotlin you can use
val myIntent = Intent(activity, your_destination_activity::class.java)
startActivity(myIntent)
You may use "Logical Partitioning" to switch data between tables:
By updating the Partition Column, data will be automatically moved to the other table:
here is the sample:
CREATE TABLE TBL_Part1
(id INT NOT NULL,
val VARCHAR(10) NULL,
PartitionColumn VARCHAR(10) CONSTRAINT CK_Part1 CHECK(PartitionColumn = 'TBL_Part1'),
CONSTRAINT TBL_Part1_PK PRIMARY KEY(PartitionColumn, id)
);
CREATE TABLE TBL_Part2
(id INT NOT NULL,
val VARCHAR(10) NULL,
PartitionColumn VARCHAR(10) CONSTRAINT CK_Part2 CHECK(PartitionColumn = 'TBL_Part2'),
CONSTRAINT TBL_Part2_PK PRIMARY KEY(PartitionColumn, id)
);
GO
CREATE VIEW TBL(id, val, PartitionColumn)
WITH SCHEMABINDING
AS
SELECT id, val, PartitionColumn FROM dbo.TBL_Part1
UNION ALL
SELECT id, val, PartitionColumn FROM dbo.TBL_Part2;
GO
--Insert sample to TBL ( will be inserted to Part1 )
INSERT INTO TBL
VALUES(1, 'rec1', 'TBL_Part1');
INSERT INTO TBL
VALUES(2, 'rec2', 'TBL_Part1');
GO
--Query sub table to verify
SELECT * FROM TBL_Part1
GO
--move the data to table TBL_Part2 by Logical Partition switching technique
UPDATE TBL
SET
PartitionColumn = 'TBL_Part2';
GO
--Query sub table to verify
SELECT * FROM TBL_Part2
The problem is that your method does NOT return a list of TestA if it contains a TestB, so what if it was correctly typed? Then this cast:
class TestA{};
class TestB extends TestA{};
List<? extends TestA> listA;
List<TestB> listB = (List<TestB>) listA;
works about as well as you could hope for (Eclipse warns you of an unchecked cast which is exactly what you are doing, so meh). So can you use this to solve your problem? Actually you can because of this:
List<TestA> badlist = null; // Actually contains TestBs, as specified
List<? extends TestA> talist = badlist; // Umm, works
List<TextB> tblist = (List<TestB>)talist; // TADA!
Exactly what you asked for, right? or to be really exact:
List<TestB> tblist = (List<TestB>)(List<? extends TestA>) badlist;
seems to compile just fine for me.
This is flask.jsonify()
def jsonify(*args, **kwargs):
if __debug__:
_assert_have_json()
return current_app.response_class(json.dumps(dict(*args, **kwargs),
indent=None if request.is_xhr else 2), mimetype='application/json')
The json
module used is either simplejson
or json
in that order. current_app
is a reference to the Flask()
object i.e. your application. response_class()
is a reference to the Response()
class.
To get the menu to automatically drop on hover then this can achieved using basic CSS. You need to work out the selector to the hidden menu option and then set it to display as block when the appropriate li
tag is hovered over. Taking the example from the twitter bootstrap page, the selector would be as follows:
ul.nav li.dropdown:hover > ul.dropdown-menu {
display: block;
}
However, if you are using Bootstrap's responsive features, you will not want this functionality on a collapsed navbar (on smaller screens). To avoid this, wrap the code above in a media query:
@media (min-width: 979px) {
ul.nav li.dropdown:hover > ul.dropdown-menu {
display: block;
}
}
To hide the arrow (caret) this is done in different ways depending on whether you are using Twitter Bootstrap version 2 and lower or version 3:
Bootstrap 3
To remove the caret in version 3 you just need to remove the HTML <b class="caret"></b>
from the .dropdown-toggle
anchor element:
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
Dropdown
<b class="caret"></b> <-- remove this line
</a>
Bootstrap 2 & lower
To remove the caret in version 2 you need a little more insight into CSS and I suggest looking at how the :after
pseudo element works in more detail. To get you started on your way to understanding, to target and remove the arrows in the twitter bootstrap example, you would use the following CSS selector and code:
a.menu:after, .dropdown-toggle:after {
content: none;
}
It will work in your favour if you look further into how these work and not just use the answers that I have given you.
Thanks to @CocaAkat for pointing out that we were missing the ">" child combinator to prevent sub menus being shown on the parent hover
Try this query here:
SELECT * FROM sys.schemas
This will give you the name and schema_id for all defines schemas in the database you execute this in.
I don't really know what you mean by querying the "schema API" - these sys.
catalog views (in the sys
schema) are your best bet for any system information about databases and objects in those databases.
EDIT: Simply "ls -m" If you want your delimiter to be a comma
Ah, the power and simplicity !
ls -1 | tr '\n' ','
Change the comma "," to whatever you want. Note that this includes a "trailing comma"
My problem ended up being that I was using Gas Mask (a hosts file manager for Mac), and I didn't have an entry for localhost in the hosts file I was using.
I added:
127.0.0.1 localhost
And that resolved my problem.
You can simply write your own code by using the mapping table here: http://www.timeanddate.com/time/zones/
or, use moment-timezone library: http://momentjs.com/timezone/docs/
See zone.name; // America/Los_Angeles
or, this library: https://github.com/Canop/tzdetect.js
>> strs = {'HA' 'KU' 'LA' 'MA' 'TATA'};
>> tic; ind=find(ismember(strs,'KU')); toc
Elapsed time is 0.001976 seconds.
>> tic; find(strcmp('KU', strs)); toc
Elapsed time is 0.000014 seconds.
SO, clearly strcmp('KU', strs)
takes much lesser time than ismember(strs,'KU')
You can open the file again using vi helloworld.txt
and then use cat /path/your_file
to view it.
LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");
list.sort(String::compareToIgnoreCase);
Another option would be using lambda expressions:
list.sort((o1, o2) -> o1.compareToIgnoreCase(o2));
Same Object Not Found problem here - both in Xampp as well as in Wamp. It turns out the root name of "phpmyadmin" was "PhpMyAdmin". I got rid of all the capitals, renaming the folder to "phpmyadmin", and after a couple of reloads phpmyadmin was working.
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
If you have misused <input type="date" />
you can probably use:
$('input[type="date"]').attr('type','text');
after they have loaded to turn them into text inputs. You'll need to attach your custom datepicker first:
$('input[type="date"]').datepicker().attr('type','text');
Or you could give them a class:
$('input[type="date"]').addClass('date').attr('type','text');
I think the best practice is to have single primary constructor to which the overloaded constructors refer to by calling this()
with the relevant parameter defaults. The reason for this is that it makes it much clearer what is the constructed state of the object is - really you can think of the primary constructor as the only real constructor, the others just delegate to it
One example of this might be JTable
- the primary constructor takes a TableModel
(plus column and selection models) and the other constructors call this primary constructor.
For subclasses where the superclass already has overloaded constructors, I would tend to assume that it is reasonable to treat any of the parent class's constructors as primary and think it is perfectly legitimate not to have a single primary constructor. For example,when extending Exception
, I often provide 3 constructors, one taking just a String
message, one taking a Throwable
cause and the other taking both. Each of these constructors calls super
directly.
Here is a javascript class that detects IE10, IE11 and Edge.
Navigator object is injected for testing purposes.
var DeviceHelper = function (_navigator) {
this.navigator = _navigator || navigator;
};
DeviceHelper.prototype.isIE = function() {
if(!this.navigator.userAgent) {
return false;
}
var IE10 = Boolean(this.navigator.userAgent.match(/(MSIE)/i)),
IE11 = Boolean(this.navigator.userAgent.match(/(Trident)/i));
return IE10 || IE11;
};
DeviceHelper.prototype.isEdge = function() {
return !!this.navigator.userAgent && this.navigator.userAgent.indexOf("Edge") > -1;
};
DeviceHelper.prototype.isMicrosoftBrowser = function() {
return this.isEdge() || this.isIE();
};
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
The concept of leading zero is meaningless for an int, which is what you have. It is only meaningful, when printed out or otherwise rendered as a string.
Console.WriteLine("{0:0000000}", FileRecordCount);
Forgot to end the double quotes!
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
You will also get this error if you are on Windows and your project path has parenthesis in it. eg. "cordova(something)".
(At least until this issue is fixed.)
file = open("filename.txt", newline='')
for row in self.data:
print(row)
Save data to a variable(file
), so you need a with
.
One possible cause of this is an incorrect JRE selected in the Ant build options. After right-clicking the build.xml and choosing 'Run As...' and then 'Ant Build...', make sure the correct JRE is chosen under the JRE Tab of the configuration options dialogue box. You will see a 'Separate JRE' option; make sure the appropriate jdk is chosen from the drop down before clicking 'Run'.
It's complicated.
First of all, in this code
const p = new Promise((resolve) => {
resolve(4);
});
the type of p
is inferred as Promise<{}>
. There is open issue about this on typescript github, so arguably this is a bug, because obviously (for a human), p
should be Promise<number>
.
Then, Promise<{}>
is compatible with Promise<number>
, because basically the only property a promise has is then
method, and then
is compatible in these two promise types in accordance with typescript rules for function types compatibility. That's why there is no error in whatever1
.
But the purpose of async
is to pretend that you are dealing with actual values, not promises, and then you get the error in whatever2
because {}
is obvioulsy not compatible with number
.
So the async
behavior is the same, but currently some workaround is necessary to make typescript compile it. You could simply provide explicit generic argument when creating a promise like this:
const whatever2 = async (): Promise<number> => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
Demo : http://jsfiddle.net/NbGBj/
$("document").ready(function(){
$("#upload").change(function() {
alert('changed!');
});
});
If you open an editor and jump to the exact line shown in the error message (within the file httpd.conf
), this is what you'd see:
#LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule auth_form_module modules/mod_auth_form.so
The paths to the modules, e.g. modules/mod_actions.so
, are all stated relatively, and they are relative to the value set by ServerRoot
. ServerRoot
is defined at the top of httpd.conf
(ctrl-F for ServerRoot "
).
ServerRoot is usually set absolutely, which would be K:/../../../xampp/apache/
in your post.
But it can also be set relatively, relative to the working directory (cf.). If the working directory is the Apache bin
folder, then use this line in your httpd.conf
:
ServerRoot ../
If the working directory is the Apache folder, then this would suffice:
ServerRoot .
If the working directory is the C: folder (one folder above the Apache folder), then use this:
ServerRoot Apache
For apache services, the working directory would be C:\Windows\System32
, so use this:
ServerRoot ../../Apache
Java does not support multi-value returns. Return an array of values.
// Function code
public static int[] something(){
int number1 = 1;
int number2 = 2;
return new int[] {number1, number2};
}
// Main class code
public static void main(String[] args) {
int result[] = something();
System.out.println(result[0] + result[1]);
}
Above you'll find all differents ways to iterate over a LIST.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class test1 {
public static void main(String[] args) {
//******* Exercise 1 : Write a Java program to create a new array list, add some colors (string) and print out the collection.
List<String> colors = new ArrayList<String>();
colors.add("Black");
colors.add("Red");
colors.add("Green");
colors.add("Blue");
System.out.println(colors);
//******* Exercise 2 : Write a Java program to iterate through all elements in a array list.
System.out.println("//******* Exercise 2");
List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
// iteration type 1 : using FOR loop
System.out.println("// iteration type 1");
for(Integer nb : list2) {
System.out.print(nb + ", ");
}
System.out.println("\n");
// iteration type 2 : using FOR loop
System.out.println("// iteration type 2");
for(int i=0; i < list2.size(); i++) {
System.out.print(list2.get(i) + ", ");
}System.out.println("\n");
// iteration type 3 : using Do-While loop
System.out.println("// iteration type 3");
int index21 = 0;
do {
System.out.print(list2.get(index21) + ", ");
index21++;
}while(index21<list2.size());
System.out.println("\n");
// iteration type 4 : using While loop
System.out.println("// iteration type 4");
int index22 = 0;
while(index22<list2.size()) {
System.out.print(list2.get(index22) + ", ");
index22++;
}
System.out.println("\n");
// iteration type 5 : using Iterable forEach loop
System.out.println("// iteration type 5");
list2.forEach(elt -> {
System.out.print(elt + ", ");
});
System.out.println("\n");
// iteration type 6 : using Iterator
System.out.println("// iteration type 6");
Iterator<Integer> listIterator = list2.iterator();
while(listIterator.hasNext()) {
System.out.print( listIterator.next() + ", ");
}
System.out.println("\n");
// iteration type 7 : using Iterator (From the beginning)
System.out.println("// iteration type 7");
ListIterator<Integer> listIterator21 = list2.listIterator(list2.size());
while(listIterator21.hasPrevious()) {
System.out.print( listIterator21.previous() + ", ");
}
System.out.println("\n");
// iteration type 8 : using Iterator (From the End)
System.out.println("// iteration type 8");
ListIterator<Integer> listIterator22 = list2.listIterator();
while(listIterator22.hasNext()) {
System.out.print( listIterator22.next() + ", ");
}
System.out.println("\n");
}
}
Got this error in Android while doing something like this:
roleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getItemAtPosition(position)) {
case ADMIN_CONSTANT: //Threw the error
}
despite declaring a constant:
public static final String ADMIN_CONSTANT= "Admin";
I resolved the issue by changing my code to this:
roleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = String.valueOf(parent.getItemAtPosition(position));
switch (selectedItem) {
case ADMIN_CONSTANT:
}
use the following commands instead:
ALTER TABLE table_name DISABLE TRIGGER tr_name
ALTER TABLE table_name ENABLE TRIGGER tr_name
You could use dplyr
:
df %>% group_by("Amount") %>% slice(which.min(x))
Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):
{{ var1 + '-' + var2 + '-' + var3 }}
If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:
e.g. To concatenate our 3 vars, and get a sha512 hash:
{{ (var1 + var2 + var3) | hash('sha512') }}
Note: this works on Ansible 2.3. I haven't tested it on earlier versions.
It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.
exec
executes a command and passes output to the caller (or returns it in an optional variable).
passthru
is similar to the exec()
function in that it executes a command . This function should be used in place of exec()
or system()
when the output from the Unix command is binary data which needs to be passed directly back to the browser.
system
executes an external program and displays the output, but only the last line.
If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru()
function.
You can use Cell.Interior.Color
, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).
public class MyFirebaseMessagingServices extends FirebaseMessagingService {
private NotificationChannel mChannel;
private NotificationManager notifManager;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
try {
JSONObject jsonObject = new JSONObject(remoteMessage.getData());
displayCustomNotificationForOrders(jsonObject.getString("title"), jsonObject.getString("description"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void displayCustomNotificationForOrders(String title, String description) {
if (notifManager == null) {
notifManager = (NotificationManager) getSystemService
(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder;
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent;
int importance = NotificationManager.IMPORTANCE_HIGH;
if (mChannel == null) {
mChannel = new NotificationChannel
("0", title, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(this, "0");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
builder.setContentTitle(title)
.setSmallIcon(getNotificationIcon()) // required
.setContentText(description) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource
(getResources(), R.mipmap.logo))
.setBadgeIconType(R.mipmap.logo)
.setContentIntent(pendingIntent)
.setSound(RingtoneManager.getDefaultUri
(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = builder.build();
notifManager.notify(0, notification);
} else {
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = null;
pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(description)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary))
.setSound(defaultSoundUri)
.setSmallIcon(getNotificationIcon())
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(description));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1251, notificationBuilder.build());
}
}
private int getNotificationIcon() {
boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.mipmap.logo : R.mipmap.logo;
}
}
On an Arm7 (armhf) device running Debian Stretch, I had to issue either of the following:
$ nodejs -v
$ nodejs -h
The following did not work:
$ node -v
$ node -h
$ apm -v
Hope this helps someone else.
Assuming you want the full object, but only want to deal with distinctness by typeID
, there's nothing built into LINQ to make this easy. (If you just want the typeID
values, it's easy - project to that with Select
and then use the normal Distinct
call.)
In MoreLINQ we have the DistinctBy
operator which you could use:
var distinct = list.DistinctBy(x => x.typeID);
This only works for LINQ to Objects though.
You can use a grouping or a lookup, it's just somewhat annoying and inefficient:
var distinct = list.GroupBy(x => x.typeID, (key, group) => group.First());
After reading Charlie Martin's post, I was curious about whether the heap size makes any difference in the number of threads you can create, and I was totally dumbfounded by the result.
Using JDK 1.6.0_11 on Vista Home Premium SP1, I executed Charlie's test application with different heap sizes, between 2 MB and 1024 MB.
For example, to create a 2 MB heap, I'd invoke the JVM with the arguments -Xms2m -Xmx2m.
Here are my results:
2 mb --> 5744 threads
4 mb --> 5743 threads
8 mb --> 5735 threads
12 mb --> 5724 threads
16 mb --> 5712 threads
24 mb --> 5687 threads
32 mb --> 5662 threads
48 mb --> 5610 threads
64 mb --> 5561 threads
96 mb --> 5457 threads
128 mb --> 5357 threads
192 mb --> 5190 threads
256 mb --> 5014 threads
384 mb --> 4606 threads
512 mb --> 4202 threads
768 mb --> 3388 threads
1024 mb --> 2583 threads
So, yeah, the heap size definitely matters. But the relationship between heap size and maximum thread count is INVERSELY proportional.
Which is weird.
If u r using SQLite3 beware:
It takes only 't' or 'f'. Not 1 or 0. Not TRUE OR FALSE.
Just learned the hard way.
The other people made very nice answers, but I would like to complete their work with an extra development tool. It is called Live HTTP Headers and you can install it into your Firefox, and in Chrome we have the same plug in like this.
Working with it is queit easy.
Using your Firefox, navigate to the website which you want to get your post request to it.
In your Firefox menu Tools->Live Http Headers
A new window pop ups for you, and all the http method details would be saved in this window for you. You don't need to do anything in this step.
In the website, do an activity(log in, submit a form, etc.)
Look at your plug in window. It is all recorded.
Just remember you need to check the Capture.
for me, it was .md rather than .txt
packagingOptions {
exclude 'META-INF/LICENSE.md'
exclude 'META-INF/NOTICE.md'
}
You can use the sprintf
method, however the arg
method is preferred as it supports unicode.
QString str;
str.sprintf("%s %d", "string", 213);
git push
can push all branches or a single one dependent on this configuration:
Push all branches
git config --global push.default matching
It will push all the branches to the remote branch and would merge them.
If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default
.
Push only the current branch if its named upstream is identical
git config --global push.default simple
So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.
I think the best thing to do, if you're really concerned about the efficiency of concatenating all of these files, is to copy them all into the same bytes buffer.
buf := bytes.NewBuffer(nil)
for _, filename := range filenames {
f, _ := os.Open(filename) // Error handling elided for brevity.
io.Copy(buf, f) // Error handling elided for brevity.
f.Close()
}
s := string(buf.Bytes())
This opens each file, copies its contents into buf, then closes the file. Depending on your situation you may not actually need to convert it, the last line is just to show that buf.Bytes() has the data you're looking for.
The book seems to indicate that those commands yield the same effect:
The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]. If you have Git version 1.6.2 or later, you can also use the --track shorthand:
$ git checkout --track origin/serverfix
Branch serverfix set up to track remote branch serverfix from origin.
Switched to a new branch 'serverfix'
To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:
$ git checkout -b sf origin/serverfix
That's particularly handy when your bash or oh-my-zsh git completions are able to pull the origin/serverfix
name for you - just append --track
(or -t
) and you are on your way.
Both do the same on all browsers, AFAIK. Checked on Chrome and Firefox, both append display:none
to the style
attribute of the element.
Semantically, you're probably looking for the one-liner
new Date().toLocaleString()
which formats the date in the locale of the user.
If you're really looking for a specific way to format dates, I recommend the moment.js library.
Work out what specific properties of a list
you want the items to have. Do they need to be indexable? Sliceable? Do they need an .append()
method?
Look up the abstract base class which describes that particular type in the collections
module.
Use isinstance
:
isinstance(x, collections.MutableSequence)
You might ask "why not just use type(x) == list
?" You shouldn't do that, because then you won't support things that look like lists. And part of the Python mentality is duck typing:
I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck
In other words, you shouldn't require that the objects are list
s, just that they have the methods you will need. The collections
module provides a bunch of abstract base classes, which are a bit like Java interfaces. Any type that is an instance of collections.Sequence
, for example, will support indexing.
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
If you just want to know the mean, you can use
summary(results)
It will give you more information than expected.
ex) Mininum value, 1st Qu., Median, Mean, 3rd Qu. Maxinum value, number of NAs.
Furthermore, If you want to get mean values of each column, you can simply use the method below.
mean(results$columnName, na.rm = TRUE)
That will return mean value. (you have to change 'columnName' to your variable name
MRalwasser, I'd give you a hint, cast the URL.getConnection()
to JarURLConnection
.
Then use JarURLConnection.getJarFile() and voila! You have the JarFile and you are free to access the resources inside.
The rest I leave to you.
Hope this helps!
Take note, with full paths the line: [MethodImpl(MethodImplOptions.Synchronized)]
should look like
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
It depends.
When you commit to sending output to stdout
, you're basically leaving it up to the user to decide where that output should go.
If you use printf(...)
(or the equivalent fprintf(stdout, ...)
), you're sending the output to stdout
, but where that actually ends up can depend on how I invoke your program.
If I launch your program from my console like this, I'll see output on my console:
$ prog
Hello, World! # <-- output is here on my console
However, I might launch the program like this, producing no output on the console:
$ prog > hello.txt
but I would now have a file "hello.txt" with the text "Hello, World!" inside, thanks to the shell's redirection feature.
Who knows – I might even hook up some other device and the output could go there. The point is that when you decide to print to stdout
(e.g. by using printf()
), then you won't exactly know where it will go until you see how the process is launched or used.
In the most shared hosts you can't set it.
On a VPS or dedicated server, you can set it, but everything has its price.
On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)
If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.
If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
In case anyone is having this issue but none of the above answers solve their problems, I was having this same issue and had the hardest time tracking it down since my config files were correct, my ngnix and php-fpm jobs were running fine, and there were no errors coming through any error logs.
Dumb mistake but I never checked the Short Open Tag variable in my php.ini file which was set to short_open_tag = Off
. Since my php files were using <?
instead of <?php
, the pages were showing up blank. Short Open Tag should have been set to On
in my case.
Hope this helps someone.
For default tooltip behavior simply add the title
attribute. This can't contain images though.
<div title="regular tooltip">Hover me</div>
Before you clarified the question I did this up in pure JavaScript, hope you find it useful. The image will pop up and follow the mouse.
JavaScript
var tooltipSpan = document.getElementById('tooltip-span');
window.onmousemove = function (e) {
var x = e.clientX,
y = e.clientY;
tooltipSpan.style.top = (y + 20) + 'px';
tooltipSpan.style.left = (x + 20) + 'px';
};
CSS
.tooltip span {
display:none;
}
.tooltip:hover span {
display:block;
position:fixed;
overflow:hidden;
}
One solution for multiple elements is to update all tooltip span
's and setting them under the cursor on mouse move.
var tooltips = document.querySelectorAll('.tooltip span');
window.onmousemove = function (e) {
var x = (e.clientX + 20) + 'px',
y = (e.clientY + 20) + 'px';
for (var i = 0; i < tooltips.length; i++) {
tooltips[i].style.top = y;
tooltips[i].style.left = x;
}
};
You only need to add text-align: center
to your <div>
In your case also remove both styles that you added to your <p>
.
Check out the demo here: http://jsfiddle.net/76uGE/3/
Good Luck
You can open the PDF file and extract its contents using the Adobe library (which I believe you can download from Adobe as part of the SDK, but it comes with certain versions of Acrobat as well)
Make sure to add the Library to your references too (On my machine it is the Adobe Acrobat 10.0 Type Library, but not sure if that is the newest version)
Even with the Adobe library it is not trivial (you'll need to add your own error-trapping etc):
Function getTextFromPDF(ByVal strFilename As String) As String
Dim objAVDoc As New AcroAVDoc
Dim objPDDoc As New AcroPDDoc
Dim objPage As AcroPDPage
Dim objSelection As AcroPDTextSelect
Dim objHighlight As AcroHiliteList
Dim pageNum As Long
Dim strText As String
strText = ""
If (objAvDoc.Open(strFilename, "") Then
Set objPDDoc = objAVDoc.GetPDDoc
For pageNum = 0 To objPDDoc.GetNumPages() - 1
Set objPage = objPDDoc.AcquirePage(pageNum)
Set objHighlight = New AcroHiliteList
objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
Set objSelection = objPage.CreatePageHilite(objHighlight)
If Not objSelection Is Nothing Then
For tCount = 0 To objSelection.GetNumText - 1
strText = strText & objSelection.GetText(tCount)
Next tCount
End If
Next pageNum
objAVDoc.Close 1
End If
getTextFromPDF = strText
End Function
What this does is essentially the same thing you are trying to do - only using Adobe's own library. It's going through the PDF one page at a time, highlighting all of the text on the page, then dropping it (one text element at a time) into a string.
Keep in mind what you get from this could be full of all kinds of non-printing characters (line feeds, newlines, etc) that could even end up in the middle of what look like contiguous blocks of text, so you may need additional code to clean it up before you can use it.
Hope that helps!
As other answers have pointed, on UNIX systems the numbers represent CPU load averages over 1/5/15 minute periods. But on Linux (and consequently Android), what it represents is something different.
After a kernel patch dating back to 1993 (a great in-depth article on the subject), in Linux the load average numbers no longer strictly represent the CPU load: as the calculation accounts not only for CPU bound processes, but also for processes in uninterruptible wait state - the original goal was to account for I/O bound processes this way, to represent more of a "system load" than just CPU load. The issue is that since 1993 the usage of uninterruptible state has grown in Linux kernel, and it no longer typically represents an I/O bound process. The problem is further exacerbated by some Linux devs using uninterruptible waits as an easy wait to avoid accommodating signals in their implementations. As a result, in Linux (and Android) we can see skewed high load average numbers that do not objectively represent the real load. There are Android user reports about unreasonable high load averages contrasting low CPU utilization. For example, my old Android phone (with 2 CPU cores) normally shown average load of ~12 even when the system and CPUs were idle. Hence, average load numbers in Linux (Android) does not turn out to be a reliable performance metric.
You can do like this:
Sub Get_Environmental_Variable()
Dim sHostName As String
Dim sUserName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
' Get Current User Name
sUserName = Environ$("username")
End Sub
Please keep in mind that the answers here assume that the length of the file is less than or equal to Integer.MAX_VALUE
(2147483647).
If you are reading in from a file, you can do something like this:
File file = new File("myFile");
byte[] fileData = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData);
dis.close();
Java 7 adds some new features in the java.nio.file package that can be used to make this example a few lines shorter. See the readAllBytes() method in the java.nio.file.Files class. Here is a short example:
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
// ...
Path p = FileSystems.getDefault().getPath("", "myFile");
byte [] fileData = Files.readAllBytes(p);
Android has support for this starting in Api level 26 (8.0.0, Oreo).
Look at the picture, it's a result set of a query select * from employee
and the next() method of ResultSet class help to move the cursor to the next row of a returned result set which is rs in your example.
:)
This will give the correct (custom) filter when the file dialog is showing:
<input type="file" accept=".jpg, .png, .jpeg, .gif, .bmp, .tif, .tiff|image/*">
Since dplyr 1.0.0
, the slice_max()
/slice_min()
functions were implemented:
mtcars %>%
group_by(cyl) %>%
slice_max(mpg, n = 2, with_ties = FALSE)
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 33.9 4 71.1 65 4.22 1.84 19.9 1 1 4 1
2 32.4 4 78.7 66 4.08 2.2 19.5 1 1 4 1
3 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
4 21 6 160 110 3.9 2.62 16.5 0 1 4 4
5 19.2 8 400 175 3.08 3.84 17.0 0 0 3 2
6 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2
The documentation on with_ties
parameter:
Should ties be kept together? The default, TRUE, may return more rows than you request. Use FALSE to ignore ties, and return the first n rows.
I had the same problem. Starting Android Studio as Administrator fixed it.
I think this is a simple and intuitive method:
data = np.array([[0, 0], [0, 1] , [1, 0] , [1, 1]])
reward = np.array([1,0,1,0])
dataset = pd.DataFrame()
dataset['StateAttributes'] = data.tolist()
dataset['reward'] = reward.tolist()
dataset
returns:
But there are performance implications detailed here:
From a quick google search it seems that the problem is a file or url couldn't be found be the HTTPservice.
Here are the links where I found this information:
http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/
Another way that works with the YAML parser used in Jekyll:
title: My Life: A Memoir
Colons not followed by spaces don't seem to bother Jekyll's YAML parser, on the other hand. Neither do dashes.
It's because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" must be strings.
For example:
'_'.join(['welcome', 'to', 'stack', 'overflow'])
'_'.join(('welcome', 'to', 'stack', 'overflow'))
'welcome_to_stack_overflow'
Using something other than strings will raise the following error:
TypeError: sequence item 0: expected str instance, int found
Thanks, i just need to use:
SETLOCAL EnableExtensions
And put a:
2^>nul
Into the REG QUERY called in the FOR command. Thanks a lot again! :)
Coming in a bit late...
There's an important difference between your question and the one you mention (which I asked ;-):
You put the enum definition out of the class, which allows you to have the same name for the enum and the property:
public enum EntityType {
Type1, Type2
}
public class SomeClass {
public EntityType EntityType {get; set;} // This is legal
}
In this case, I'd follow the MS guidelins and use a singular name for the enum (plural for flags). It's probaby the easiest solution.
My problem (in the other question) is when the enum is defined in the scope of the class, preventing the use of a property named exactly after the enum.
I know this is an old question, but here's an alternative. I'd store that image data in an array, then, on mouse move event over the canvas:
var index = (Math.floor(y) * canvasWidth + Math.floor(x)) * 4
var r = data[index]
var g = data[index + 1]
var b = data[index + 2]
var a = data[index + 3]
A lot easier than getting the imageData everytime.
I implemented it in the following way. I wanted a generic MakeRequest
method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string>
object to house the content to be submitted, and then set the HttpRequestMessage
Content
property with it:
Generic method to call the API:
private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
{
using (var client = new HttpClient())
{
HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");
if (postParams != null)
requestMessage.Content = new FormUrlEncodedContent(postParams); // This is where your content gets added to the request body
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
string apiResponse = response.Content.ReadAsStringAsync().Result;
try
{
// Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
if (apiResponse != "")
return JsonConvert.DeserializeObject<T>(apiResponse);
else
throw new Exception();
}
catch (Exception ex)
{
throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
}
}
}
Call the method:
public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
{
// Here you create your parameters to be added to the request content
var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
// make a POST request to the "cards" endpoint and pass in the parameters
return MakeRequest<CardInformation>("POST", "cards", postParams);
}
This thread really helped me developing my own project. Here are some further illustrations showing the result of a simple 2-layer feed forward neural network with and without bias units on a two-variable regression problem. Weights are initialized randomly and standard ReLU activation is used. As the answers before me concluded, without the bias the ReLU-network is not able to deviate from zero at (0,0).
This is because project names are not suppose to have blank spaces in between them
import numpy as np
a = [2 ,3, 4]
np.square(a)
You should initialize yours recordings. You are passing to adapter null
ArrayList<String> recordings = null; //You are passing this null
Temporary solve this issue by a chrome plugin called CORS. Btw backend server have to send proper header to front end requests.