This occurs when you specify the different name for repository table name and database table name. Please check your table name with database and repository.
private fun setImage(view: ImageView, uri: Uri) {
val stream = contentResolver.openInputStream(uri)
val bitmap = BitmapFactory.decodeStream(stream)
view.setImageBitmap(bitmap)
}
val = -3.1234
fraction = abs(val - as.integer(val) )
Unfortunately, this is not possible. Per the spec:
Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).
In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.
As an example, using the given CSS with the following HTML:
<h1 class="header">Title</h1>
... will result in the following output:
Here's an example I needed for conditionally rendering json or html depending on the Request's Accept
header
# myapp/views.py
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render
from .models import Event
def event_index(request):
event_list = Event.objects.all()
if request.META['HTTP_ACCEPT'] == 'application/json':
response = serializers.serialize('json', event_list)
return HttpResponse(response, content_type='application/json')
else:
context = {'event_list': event_list}
return render(request, 'polls/event_list.html', context)
you can test this with curl or httpie
$ http localhost:8000/event/
$ http localhost:8000/event/ Accept:application/json
note I opted not to use JsonReponse
as that would reserialize the model unnecessarily.
Instead a format such as yours, use ISO 8601 standard formats for exchanging date-time values as text.
The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
Your IST
could mean Iceland Standard Time, India Standard Time, Ireland Standard Time, or others. The java.time classes are left to merely guessing, as there is no logical solution to this ambiguity.
The modern approach uses the java.time classes.
Define a formatting pattern to match your input strings.
String input = "Sat Jun 01 12:53:10 IST 2013";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
zdt.toString(): 2013-06-01T12:53:10Z[Atlantic/Reykjavik]
If your input was not intended for Iceland, you should pre-parse the string to adjust to a proper time zone name. For example, if you are certain the input was intended for India, change IST
to Asia/Kolkata
.
String input = "Sat Jun 01 12:53:10 IST 2013".replace( "IST" , "Asia/Kolkata" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
zdt.toString(): 2013-06-01T12:53:10+05:30[Asia/Kolkata]
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Date's compareTo() you're using will work for ascending order.
To do descending, just reverse the value of compareTo() coming out. You can use a single Comparator class that takes in a flag/enum in the constructor that identifies the sort order
public int compare(MyObject lhs, MyObject rhs) {
if(SortDirection.Ascending == m_sortDirection) {
return lhs.MyDateTime.compareTo(rhs.MyDateTime);
}
return rhs.MyDateTime.compareTo(lhs.MyDateTime);
}
You need to call Collections.sort() to actually sort the list.
As a side note, I'm not sure why you're defining your map inside your for loop. I'm not exactly sure what your code is trying to do, but I assume you want to populate the indexed values from your for loop in to the map.
This converts all text in columns of an Excel Workbook to numbers.
Sub ConvertTextToNumbers()
Dim wBook As Workbook
Dim LastRow As Long, LastCol As Long
Dim Rangetemp As Range
'Enter here the path of your workbook
Set wBook = Workbooks.Open("yourWorkbook")
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
For c = 1 To LastCol
Set Rangetemp = Cells(c).EntireColumn
Rangetemp.TextToColumns DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Next c
End Sub
The python-espeak package is available in Debian, Ubuntu, Redhat, and other Linux distributions. It has recent updates, and works fine.
from espeak import espeak
espeak.synth("Hello world.")
Jonathan Leaders notes that it also works on Windows, and you can install the mbrola voices as well. See the espeak website at http://espeak.sourceforge.net
They take up different amounts of space and they have different ranges of acceptable values.
Here are the sizes and ranges of values for SQL Server, other RDBMSes have similar documentation:
Turns out they all use the same specification (with a few minor exceptions noted below) but support various combinations of those types (Oracle not included because it has just a NUMBER
datatype, see the above link):
| SQL Server MySQL Postgres DB2
---------------------------------------------------
tinyint | X X
smallint | X X X X
mediumint | X
int/integer | X X X X
bigint | X X X X
And they support the same value ranges (with one exception below) and all have the same storage requirements:
| Bytes Range (signed) Range (unsigned)
--------------------------------------------------------------------------------------------
tinyint | 1 byte -128 to 127 0 to 255
smallint | 2 bytes -32768 to 32767 0 to 65535
mediumint | 3 bytes -8388608 to 8388607 0 to 16777215
int/integer | 4 bytes -2147483648 to 2147483647 0 to 4294967295
bigint | 8 bytes -9223372036854775808 to 9223372036854775807 0 to 18446744073709551615
The "unsigned" types are only available in MySQL, and the rest just use the signed ranges, with one notable exception: tinyint
in SQL Server is unsigned and has a value range of 0 to 255
Having a hidden input field leads to problems with datepicker dialog positioning (dialog is horizontally centered). You could alter the dialog's margin, but there's a better way.
Just create an input field and "hide" it by setting it's opacity to 0 and making it 1px wide. Also position it near (or under) the button, or where ever you want the datepicker to appear.
Then attach the datepicker to the "hidden" input field and show it when user presses the button.
HTML:
<button id="date-button">Show Calendar</button>
<input type="text" name="date-field" id="date-field" value="">
CSS:
#date-button {
position: absolute;
top: 0;
left: 0;
z-index: 2;
height 30px;
}
#date-field {
position: absolute;
top: 0;
left: 0;
z-index: 1;
width: 1px;
height: 32px; // height of the button + a little margin
opacity: 0;
}
JS:
$(function() {
$('#date-field').datepicker();
$('#date-button').on('click', function() {
$('#date-field').datepicker('show');
});
});
Note: not tested with all browsers.
node-cron does just what I described
No, but you should be careful when using IF...ELSE...END IF in stored procs. If your code blocks are radically different, you may suffer from poor performance because the procedure plan will need to be re-cached each time. If it's a high-performance system, you may want to compile separate stored procs for each code block, and have your application decide which proc to call at the appropriate time.
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too. .....
I believe you need to map the result before you subscribe to it. You configure it like this:
updateProfileInformation(user: User) {
var headers = new Headers();
headers.append('Content-Type', this.constants.jsonContentType);
var t = localStorage.getItem("accessToken");
headers.append("Authorization", "Bearer " + t;
var body = JSON.stringify(user);
return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
.map((response: Response) => {
var result = response.json();
return result;
})
.catch(this.handleError)
.subscribe(
status => this.statusMessage = status,
error => this.errorMessage = error,
() => this.completeUpdateUser()
);
}
pip
is designed to upgrade python packages and not to upgrade python itself. pip
shouldn't try to upgrade python when you ask it to do so.
Don't type pip install python
but use an installer instead.
Swift 2.0
You can do following thing to get hours and minute from a date :
let dateFromat = NSDateFormatter()
dateFromat.dateFormat = "hh:mm a"
let date = dateFromat.dateFromString(string1) // In your case its string1
print(date) // you will get - 11:59 AM
Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.
Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.
Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.
On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)
The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.
Jake
i wrote my own function to return list of object for populate combo box :
public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
try {
Object[] args={};
Class cl = Class.forName(kelas);
Method getName = cl.getMethod(name, null);
Method getLabel = cl.getMethod(label, null);
String json="[";
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if(i>0){
json+=",";
}
json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
//System.out.println("Object = " + i+" -> "+o.getNumber());
}
json+="]";
return json;
} catch (ClassNotFoundException ex) {
Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
System.out.println("Error in get JSON List");
ex.printStackTrace();
}
return "";
}
and call it from anywhere like :
String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");
There is obviously another process listening on the port. You might find out that process by using the following command:
$ lsof -i :8000
or change your tornado app's port. tornado's error info not Explicitly on this.
The following will extends the problem a bit by removing from the first string argument any character that occurs in the second string argument.
/*
* delete one character from a string
*/
static void
_strdelchr( char *s, size_t i, size_t *a, size_t *b)
{
size_t j;
if( *a == *b)
*a = i - 1;
else
for( j = *b + 1; j < i; j++)
s[++(*a)] = s[j];
*b = i;
}
/*
* delete all occurrences of characters in search from s
* returns nr. of deleted characters
*/
size_t
strdelstr( char *s, const char *search)
{
size_t l = strlen(s);
size_t n = strlen(search);
size_t i;
size_t a = 0;
size_t b = 0;
for( i = 0; i < l; i++)
if( memchr( search, s[i], n))
_strdelchr( s, i, &a, &b);
_strdelchr( s, l, &a, &b);
s[++a] = '\0';
return l - a;
}
One option would be to add your working directory to your Chrome "workspace" which allows Chrome to map local files to those on the page. It will then detect changes in the local files, and update the page in real-time.
This can be done from the "Sources" tab of Devtools:
Click on the "Filesystem" tab in the file browser sidebar, then click the +Plus sign button to "Add folder to workspace" - you will be prompted with a banner at the top of the screen to allow or deny local file access:
Once allowed, the folder will appear in the "Filesystem" tab on the left. Chrome will now attempt to associate each file in the filesystem tab with a file in the page. Sometimes you will need to reload the page once for this to function correctly.
Once this is done, Chrome should have no trouble picking up local changes, in fact you won't even need to reload to get the changes in many cases, and you can make edits to the local files directly from Devtools (which is extremely useful for CSS, it even comments out CSS lines when you toggle the checkboxes in the Styles tab).
Everything else you read here and elsewhere is pure conjecture. The only sure-way to fix this problem is vote for this bug report.
The problem isn't related to emulator resolution or OpenGL, nor how much memory your computer has. I've got 24GB memory in my computer and most of the time I run with hw.ramSize=1024
I get error 8. Other times it works just fine without any configuration changes. I hope you caught that: I did not alter the emulator configuration at all and yet sometimes it runs and sometimes it fails.
There is a high probability it has something to do with memory fragmentation. I recommend reducing the value of hw.ramSize
as a temporary workaround.
You can call pack_forget
to remove a widget (if you use pack
to add it to the window).
Example:
from tkinter import *
root = Tk()
b = Button(root, text="Delete me", command=lambda: b.pack_forget())
b.pack()
root.mainloop()
If you use pack_forget
, you can later show the widget again calling pack
again. If you want to permanently delete it, call destroy
on the widget (then you won't be able to re-add it).
If you use the grid
method, you can use grid_forget
or grid_remove
to hide the widget.
For Mac OS:
touch ~/.bash_profile
vi ~/.bash_profile
source ~/.nvm/nvm.sh
Shift + Esc
and type wq
and press enter
I usualy would enter the path like this ....
FileInfo fi = new FileInfo(@"C:\Program Files (x86)\test software\myapp\demo.exe");
Did you register the @ at the beginning of the string? ;-)
If you want to use Codeblocks and Graphics.h,you can use Codeblocks-EP(I used it when I was learning C in college) then you can try
Codeblocks-EP http://codeblocks.codecutter.org/
In Codeblocks-EP , [File]->[New]->[Project]->[WinBGIm Project]
It has templates for WinBGIm projects installed and all the necessary libraries pre-installed.
OR try this https://stackoverflow.com/a/20321173/5227589
If you're using C# 6 or later, you can use expression-bodied syntax for get-only indexer:
public object this[int i] => this.InnerList[i];
The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:
jobs:
- - name: A
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
- - name: B
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.
It has some interesting behaviour in some cases that is good to be aware of:
from werkzeug.datastructures import MultiDict
d = MultiDict([("ex1", ""), ("ex2", None)])
d.get("ex1", "alternive")
# returns: ''
d.get("ex2", "alternative")
# returns no visible output of any kind
# It is returning literally None, so if you do:
d.get("ex2", "alternative") is None
# it returns: True
d.get("ex3", "alternative")
# returns: 'alternative'
Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:
java -Djava.library.path="dlls" ...
(assuming Jacob.dll is in the "dlls" folder)
Also see java.lang.UnsatisfiedLinkError no *****.dll in java.library.path
Angular 4:
/* typescript */
import { Location } from '@angular/common';
// ...
@Component({
// ...
})
export class MyComponent {
constructor(private location: Location) { }
goBack() {
this.location.back(); // go back to previous location
}
}
I had the same problem for a bit. I noticed that I had:
Data Source= (localdb)\v11.0"
Simply by adding one back-slash it solved the problem for me:
Data Source= (localdb)\\v11.0"
JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.
JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.
JavaScript timers operate with this same kind of callback.
Describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.
jQuery has an option on Ajax calls to make them synchronously (with the async: false
option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.
Uninitialized non-static members will contain random data. Actually, they will just have the value of the memory location they are assigned to.
Of course for object parameters (like string
) the object's constructor could do a default initialization.
In your example:
int *ptr; // will point to a random memory location
string name; // empty string (due to string's default costructor)
string *pname; // will point to a random memory location
string &rname; // it would't compile
const string &crname; // it would't compile
int age; // random value
Code will be As below.
[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->
[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->
[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->
[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->
For Details: https://contactform7.com/text-fields/
Recently encountered this and kept getting warnings/errors about the method being void.
We're in the business of placating the compiler and this clears it up:
public async Task MyVoidAsyncMethod()
{
await Task.CompletedTask;
}
This brings together the best of all the advice here so far. No return statement is necessary unless you're actually doing something in the method.
Use an SqlDataAdapter instead, it's much easier and you don't need to define the column names yourself, it will get the column names from the query results:
using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
}
}
}
That character is the BOM or "Byte Order Mark". It is usually received as the first few bytes of a file, telling you how to interpret the encoding of the rest of the data. You can simply remove the character to continue. Although, since the error says you were trying to convert to 'ascii', you should probably pick another encoding for whatever you were trying to do.
In my case missing private static final long serialVersionUID = 1L;
line caused the same error. I added the line and it worked!
If you want to allow a user to add a bunch of new MyObjects to the list, you can do it with a for loop: Let's say I'm creating an ArrayList of Rectangle objects, and each Rectangle has two parameters- length and width.
//here I will create my ArrayList:
ArrayList <Rectangle> rectangles= new ArrayList <>(3);
int length;
int width;
for(int index =0; index <3;index++)
{JOptionPane.showMessageDialog(null, "Rectangle " + (index + 1));
length = JOptionPane.showInputDialog("Enter length");
width = JOptionPane.showInputDialog("Enter width");
//Now I will create my Rectangle and add it to my rectangles ArrayList:
rectangles.add(new Rectangle(length,width));
//This passes the length and width values to the rectangle constructor,
which will create a new Rectangle and add it to the ArrayList.
}
I had a similar issue as you, although I was trying to use start
to open Chrome and using the file path. I used only start chrome.exe
and it opened just fine. You may want to try to do the same with exe file. Using the file path may be unnecessary.
Here are some examples (using the file name you gave in a comment on another answer):
Instead of C:\Program^ Files\temp.exe
you can try temp.exe
.
Instead of start C:\Program^ Files\temp.exe
you can try start
temp.exe
I had the same problem. Solution: I edit the file with pspad editor, and give it a unix format (Menu - Format -> UNIX)
I believe you can set this format to your file with many other editors
I know three ways to swap variables, but a, b = b, a
is the simplest. There is
x = x ^ y
y = y ^ x
x = x ^ y
Or concisely,
x ^= y
y ^= x
x ^= y
w = x
x = y
y = w
del w
x, y = y, x
For my project's setup, "${pageContext.request.contextPath}"= refers to "src/main/webapp". Another way to tell is by right clicking on your project in Eclipse and then going to Properties:
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
If someone else needs a guaranteed way of STRICTLY sequential way of resolving Promises when performing CRUD operations you also can use the following code as a basis.
As long as you add 'return' before calling each function, describing a Promise, and use this example as a basis the next .then() function call will CONSISTENTLY start after the completion of the previous one:
getRidOfOlderShoutsPromise = () => {
return readShoutsPromise('BEFORE')
.then(() => {
return deleteOlderShoutsPromise();
})
.then(() => {
return readShoutsPromise('AFTER')
})
.catch(err => console.log(err.message));
}
deleteOlderShoutsPromise = () => {
return new Promise ( (resolve, reject) => {
console.log("in deleteOlderShouts");
let d = new Date();
let TwoMinuteAgo = d - 1000 * 90 ;
All_Shouts.deleteMany({ dateTime: {$lt: TwoMinuteAgo}}, function(err) {
if (err) reject();
console.log("DELETED OLDs at "+d);
resolve();
});
});
}
readShoutsPromise = (tex) => {
return new Promise( (resolve, reject) => {
console.log("in readShoutsPromise -"+tex);
All_Shouts
.find({})
.sort([['dateTime', 'ascending']])
.exec(function (err, data){
if (err) reject();
let d = new Date();
console.log("shouts "+tex+" delete PROMISE = "+data.length +"; date ="+d);
resolve(data);
});
});
}
Two entries in an array can't share a key, you'll need to change the key for the duplicate
The simplified Java 8 way:
map.put(key, map.getOrDefault(key, 0) + 1);
This uses the method of HashMap that retrieves the value for a key, but if the key can't be retrieved it returns the specified default value (in this case a '0').
This is supported within core Java: HashMap<K,V> getOrDefault(Object key, V defaultValue)
Simply use
Quoting the 'Select and activate an environment' docs
Selecting an interpreter from the list adds an entry for
python.pythonPath
with
the path to the interpreter inside your Workspace Settings.
This will work with every browser
div {
-khtml-opacity:.50;
-moz-opacity:.50;
-ms-filter:"alpha(opacity=50)";
filter:alpha(opacity=50);
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
opacity:.50;
}
If you don't want transparency to affect the entire container and its children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent.
Check demo at http://www.impressivewebs.com/css-opacity-that-doesnt-affect-child-elements/
You can also use:
var obj = {
alert: alert.bind(window)
};
obj.alert('I´m an alert!!');
Old question, but there's an easier way.
sns.pointplot(x=x_col,y=y_col,data=df_1,color='blue')
sns.pointplot(x=x_col,y=y_col,data=df_2,color='green')
sns.pointplot(x=x_col,y=y_col,data=df_3,color='red')
plt.legend(labels=['legendEntry1', 'legendEntry2', 'legendEntry3'])
This lets you add the plots sequentially, and not have to worry about any of the matplotlib crap besides defining the legend items.
if you want to display date along with time when you export to Excel then you can use this
xlWorkSheet.Cells(nRow, 3).NumberFormat = "dd/mm/yy h:mm AM/PM"
According to the definition of max-width in the CSS 2.1 spec, “the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.” So you cannot directly set max-width on a td element.
If you just want the second column to take up at most 67%, then you can set the width (which is in effect minimum width, for table cells) to 33%, e.g. in the example case
td:first-child { width: 33% ;}
Setting that for both columns won’t work that well, since it tends to make browsers give the columns equal width.
You can use include
/include_once
or require
/require_once
require_once('class.php');
Alternatively, use autoloading
by adding to page.php
<?php
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
$vars = new IUarts();
print($vars->data);
?>
It also works adding that __autoload
function in a lib that you include on every file like utils.php
.
There is also this post that has a nice and different approach.
They both are indeed synonymous, However i found the small difference between them,
1)You cannot use Int32
while creatingenum
enum Test : Int32
{ XXX = 1 // gives you compilation error
}
enum Test : int
{ XXX = 1 // Works fine
}
2) Int32
comes under System declaration. if you remove using.System
you will get compilation error but not in case for int
function getCityState($zip, $blnUSA = true) {
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";
$address_info = file_get_contents($url);
$json = json_decode($address_info);
$city = "";
$state = "";
$country = "";
if (count($json->results) > 0) {
//break up the components
$arrComponents = $json->results[0]->address_components;
foreach($arrComponents as $index=>$component) {
$type = $component->types[0];
if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
$city = trim($component->short_name);
}
if ($state == "" && $type=="administrative_area_level_1") {
$state = trim($component->short_name);
}
if ($country == "" && $type=="country") {
$country = trim($component->short_name);
if ($blnUSA && $country!="US") {
$city = "";
$state = "";
break;
}
}
if ($city != "" && $state != "" && $country != "") {
//we're done
break;
}
}
}
$arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);
die(json_encode($arrReturn));
}
Here is where you should configure in your job:
In JDK there is the combobox with the different JDK configured in your Jenkins.
Here is where you should configure in the config of your Jenkins:
Fix this by moving my jdk folder to other disk
I used jQuery .scroll() function to track the event of the toolbar scroll value using scrollTop. I then used a conditional to determine if it was greater than the value on what I wanted to replace. In the below example it was "Results". If the value was true then the results-label added a class 'fixedSimilarLabel' and the new styles were then taken into account.
$('.toolbar').scroll(function (e) {
//console.info(e.currentTarget.scrollTop);
if (e.currentTarget.scrollTop >= 130) {
$('.results-label').addClass('fixedSimilarLabel');
}
else {
$('.results-label').removeClass('fixedSimilarLabel');
}
});
You could set like this
button.setAllCaps(false);
programmatically
You extract it and then use jad against the dir.
On modern browsers you can use the built in Intl.NumberFormat to detect the browser's number formatting and normalize the input to match.
function parseNumber(value, locales = navigator.languages) {
const example = Intl.NumberFormat(locales).format('1.1');
const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
const cleaned = value.replace(cleanPattern, '');
const normalized = cleaned.replace(example.charAt(1), '.');
return parseFloat(normalized);
}
const corpus = {
'1.123': {
expected: 1.123,
locale: 'en-US'
},
'1,123': {
expected: 1123,
locale: 'en-US'
},
'2.123': {
expected: 2123,
locale: 'fr-FR'
},
'2,123': {
expected: 2.123,
locale: 'fr-FR'
},
}
for (const candidate in corpus) {
const {
locale,
expected
} = corpus[candidate];
const parsed = parseNumber(candidate, locale);
console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);
}
_x000D_
Their's obviously room for some optimization and caching but this works reliably in all languages.
In Java there is no good reason.
A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:
if (o = null)
will not compile.
The only time this could matter in Java is if the variable is boolean:
int m1(boolean x)
{
if (x = true) // oops, assignment instead of equality
Where do these values come from? The documentation for android:fontFamily does not list this information in any place
These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.
In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:
Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:
<item name="android:fontFamily">sans-serif</item>
Like the linked answer already stated, 12 variants are possible:
Regular (default):
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item>
Italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>
Bold:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
Bold-italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>
Light:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
Light-italic:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>
Thin :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>
Thin-italic :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>
Condensed regular:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>
Condensed italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>
Condensed bold:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>
Condensed bold-italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>
Medium:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>
Medium-italic:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>
Black:
<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>
For quick reference, this is how they all look like:
The pandas.DataFrame.dropna
function removes missing values (e.g. NaN
, NaT
).
For example the following code would remove any columns from your dataframe, where all of the elements of that column are missing.
df.dropna(how='all', axis='columns')
Because although the Java language doesn't use it, JVM bytecode does.
Most terse version I can think of
Len(Trim(TextBox1.Value)) = 0
If you need to do this multiple times, wrap it in a function
Public Function HasContent(text_box as Object) as Boolean
HasContent = (Len(Trim(text_box.Value)) > 0)
End Function
Usage
If HasContent(TextBox1) Then
' ...
Found one solution for WIFI (works for Android 4.3, 4.4):
Try the following statement to check for existence of a table in the database:
If not exists (select name from sysobjects where name = 'tablename')
You may create the table inside the if block.
Basically, fs.readFileSync
throws an error when a file is not found. This error is from the Error
prototype and thrown using throw
, hence the only way to catch is with a try / catch
block:
var fileContents;
try {
fileContents = fs.readFileSync('foo.bar');
} catch (err) {
// Here you get the error when the file was not found,
// but you also get any other error
}
Unfortunately you can not detect which error has been thrown just by looking at its prototype chain:
if (err instanceof Error)
is the best you can do, and this will be true for most (if not all) errors. Hence I'd suggest you go with the code
property and check its value:
if (err.code === 'ENOENT') {
console.log('File not found!');
} else {
throw err;
}
This way, you deal only with this specific error and re-throw all other errors.
Alternatively, you can also access the error's message
property to verify the detailed error message, which in this case is:
ENOENT, no such file or directory 'foo.bar'
Hope this helps.
I think this is the simplest way:
DECLARE @sql VARCHAR(MAX)='';
SELECT @sql=@sql+'drop procedure ['+name +'];' FROM sys.objects
WHERE type = 'p' AND is_ms_shipped = 0
exec(@sql);
Instead of using regex to remove those "crazy" characters, just convert them to ASCII, which will remove accents, but will keep the letters.
astr <- "Ábcdêãçoàúü"
iconv(astr, from = 'UTF-8', to = 'ASCII//TRANSLIT')
which results in
[1] "Abcdeacoauu"
HTML code
<form class="form-inline" (ngSubmit)="HelloCorp(modelName)">
<div class="select">
<select class="form-control col-lg-8" [(ngModel)]="modelName" required>
<option *ngFor="let corporation of corporations" [ngValue]="corporation">
{{corporation.corp_name}}
</option>
</select>
<button type="submit" class="btn btn-primary manage">Submit</button>
</div>
</form>
Component code
HelloCorp(corporation) {
var corporationObj = corporation.value;
}
Use divs with max height and min height around the content that needs to scroll.
<tr>
<td>
<div>content</div>
</td>
</tr>
td div{
max-height:20px;
}
I would suggest this simplest solution to use Object.entries()
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}_x000D_
var result =Object.entries(obj)_x000D_
_x000D_
console.log(result);
_x000D_
@Logan said it perfectly. but i would like to add an alternative here,
if you want to view logs from just your application then you can make a custom method that keeps saving the log to a file in
documents
directory & then you can view that log file from your application.
There is one good advantage for developers of the app after the app has been released & users are downloading it. Because your app will be able to send logs & crash reports to the developers (of course with the permissions of the device user !!!) & it'll be the way to improve your application.
Let me know (To other SO users), if there is another way of doing the same thing. (Like default Apple feature or something)
Let me know if it helps or you want some more idea.
This worked for me :
body {
font-size: calc([minimum size] + ([maximum size] - [minimum size]) * ((100vw - [minimum
viewport width]) / ([maximum viewport width] - [minimum viewport width])));
}
Explained in detail here: https://css-tricks.com/books/volume-i/scale-typography-screen-size/
Here's example with simple object exporting.
var MyScreen = {
/* ... */
width : function (percent){
return window.innerWidth / 100 * percent
}
height : function (percent){
return window.innerHeight / 100 * percent
}
};
export default MyScreen
In main file (Use when you don't want and don't need to create new instance) and it is not global you will import this only when it needed :
import MyScreen from "./module/screen";
console.log( MyScreen.width(100) );
I encountered this problem too. If you want the activity that handles permissions not in the history/recents, then you will be tempted to change your AndroidManifest.xml
entry.
If you set the activity that you call requestPermissions
or AppCompatActivity.requestPermissions
with
android:noHistory="true"
android:excludeFromRecents="true"
in your AndroidManifest.xml
then onRequestPermissionsResult()
will not be called. This is true if your Activity is derived from Activity
or AppCompatActivity
.
This can be fixed by removing both flags from 'AndroidManifest.xml' and finishing your activity with finishAndRemoveTask()
instead.
The simplest way is to convert Date to POSIXlt format. Then perform the arithmetic operation as follows:
date_1m_fwd <- as.POSIXlt("2010-01-01")
date_1m_fwd$mon <- date_1m_fwd$mon +1
Moreover, incase you want to deal with Date columns in data.table, unfortunately, POSIXlt format is not supported.
Still you can perform the add month using basic R codes as follows:
library(data.table)
dt <- as.data.table(seq(as.Date("2010-01-01"), length.out=5, by="month"))
dt[,shifted_month:=tail(seq(V1[1], length.out=length(V1)+3, by="month"),length(V1))]
Hope it helps.
There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__
.
df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
For example, to get every 2 rows, you can do
df[::2]
a b c
0 x x x
2 x x x
4 x x x
There's also GroupBy.first
/GroupBy.head
, you group on the index:
df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')
df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)
a b c
0 x x x
1 x x x
2 x x x
The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do
# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()
a b c
0 x x x
1 x x x
2 x x x
<object Margin="left,top,right,bottom"/>
- or -
<object Margin="left,top"/>
- or -
<object Margin="thicknessReference"/>
See here: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.margin.aspx
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
So you can use:
myvar = getURLParameter('myvar');
There is a len
method:
>>> a = 'a string of some length'
>>> a.__len__()
23
>>> a.__len__
<method-wrapper '__len__' of str object at 0x02005650>
In Java 7+ a few of the previous answers can be combined to allow retrieval of any path segment from a URI, rather than just the last segment. We can convert the URI to a java.nio.file.Path
object, to take advantage of its getName(int)
method.
Unfortunately, the static factory Paths.get(uri)
is not built to handle the http scheme, so we first need to separate the scheme from the URI's path.
URI uri = URI.create("http://base_path/some_segment/id");
Path path = Paths.get(uri.getPath());
String last = path.getFileName().toString();
String secondToLast = path.getName(path.getNameCount() - 2).toString();
To get the last segment in one line of code, simply nest the lines above.
Paths.get(URI.create("http://base_path/some_segment/id").getPath()).getFileName().toString()
To get the second-to-last segment while avoiding index numbers and the potential for off-by-one errors, use the getParent()
method.
String secondToLast = path.getParent().getFileName().toString();
Note the getParent()
method can be called repeatedly to retrieve segments in reverse order. In this example, the path only contains two segments, otherwise calling getParent().getParent()
would retrieve the third-to-last segment.
foreach( $codes as $code and $names as $name ) { }
That is not valid.
You probably want something like this...
foreach( $codes as $index => $code ) {
echo '<option value="' . $code . '">' . $names[$index] . '</option>';
}
Alternatively, it'd be much easier to make the codes the key of your $names
array...
$names = array(
'tn' => 'Tunisia',
'us' => 'United States',
...
);
For me Authorization on remote git server solve the problem.
There is a quite interesting way to execute script minimized by making him restart itself minimised. Here is the code to put in the beginning of your script:
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit
... script logic here ...
exit
When the script is being executed IS_MINIMIZED
is not defined (if not DEFINED IS_MINIMIZED
) so:
set IS_MINIMIZED=1
.Script starts a copy of itself using start command && start "" /min "%~dpnx0" %*
where:
""
- empty title for the window./min
- switch to run minimized."%~dpnx0"
- full path to your script.%*
- passing through all your script's parameters.Then initial script finishes its work: && exit
.
For the started copy of the script variable IS_MINIMIZED
is set by the original script so it just skips the execution of the first line and goes directly to the script logic.
exit
, otherwise the cmd window wouldn't be closed after the script execution.If your script doesn't accept arguments you could use argument as a flag instead of variable:
if "%1" == "" start "" /min "%~dpnx0" MY_FLAG && exit
or shorter
if "%1" == "" start "" /min "%~f0" MY_FLAG && exit
If you still want to specify your colors in your XML file:
<color name="errorColor">#f00</color>
Then reference it in your code with one of these two methods:
textView.setTextColor(getResources().getColor(R.color.errorColor, getResources().newTheme()));
or
textView.setTextColor(getResources().getColor(R.color.errorColor, null));
The first is probably preferable if you're compiling against Android M, however the theme you pass in can be null, so maybe that's easier for you?
And if you're using the Compat library you can do something like this
textView.setTextColor(ContextCompat.getColor(context, R.color.errorColor));
With ctypes, you can achieve the same thing with
>>> import ctypes
>>> a = (1,2,3)
>>> ctypes.addressof(a)
3077760748L
Documentation:
addressof(C instance) -> integer
Return the address of the C instance internal buffer
Note that in CPython, currently id(a) == ctypes.addressof(a)
, but ctypes.addressof
should return the real address for each Python implementation, if
Edit: added information about interpreter-independence of ctypes
I prefer using a top-level namespace for the application and sub namespaces for the components.
The way you can use classes from other namespaces is surprisingly very similar to the way in java. You can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.
I would recommend using MyBatis. It is a thin layer on top of JDBC, it is very easy to map objects to tables and still use plain SQL, everything is under your control.
This is how I was able to trigger a button click when the page loads.
<li ng-repeat="a in array">
<a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
{{a.name}}
</a>
</li>
A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.
angular
.module("myApp")
.directive('onLoadClicker', function ($timeout) {
return {
restrict: 'A',
scope: {
index: '=index'
},
link: function($scope, iElm) {
if ($scope.index == 0) {
$timeout(function() {
iElm.triggerHandler('click');
}, 0);
}
}
};
});
This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click();
Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.
$record = '123';
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get('accesslog');
then
$query->num_rows();
should go a long way towards it.
I only just found this question, which is pretty much the same I asked: How to know exactly when a UIScrollView's scrolling has stopped?
Though didEndDecelerating works when scrolling, panning with stationary release does not register.
I eventually found a solution. didEndDragging has a parameter WillDecelerate, which is false in the stationary release situation.
By checking for !decelerate in DidEndDragging, combined with didEndDecelerating, you get both situations that are the end of scrolling.
This is a simple solution that can be used when converting a string to a hex format:
private static String encryptPassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
return new BigInteger(1, crypt.digest()).toString(16);
}
I am coming here after searching google and change thing at my-end.
So I just change this sample and it will work with jquery at run-time.
$('select[name*="homepage_select"]').removeAttr('multiple')
It is a little tricky. First you can use keytool to put the private key into PKCS12 format, which is more portable/compatible than Java's various keystore formats. Here is an example taking a private key with alias 'mykey' in a Java keystore and copying it into a PKCS12 file named myp12file.p12
.
[note that on most screens this command extends beyond the right side of the box: you need to scroll right to see it all]
keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
Enter destination keystore password:
Re-enter new password:
Enter source keystore password:
[Storing myp12file.p12]
Now the file myp12file.p12
contains the private key in PKCS12 format which may be used directly by many software packages or further processed using the openssl pkcs12
command. For example,
openssl pkcs12 -in myp12file.p12 -nocerts -nodes
Enter Import Password:
MAC verified OK
Bag Attributes
friendlyName: mykey
localKeyID: 54 69 6D 65 20 31 32 37 31 32 37 38 35 37 36 32 35 37
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIIC...
.
.
.
-----END RSA PRIVATE KEY-----
Prints out the private key unencrypted.
Note that this is a private key, and you are responsible for appreciating the security implications of removing it from your Java keystore and moving it around.
I have this extension which is kind of multi-purpose:
public static bool IsNumeric(this object value)
{
if (value == null || value is DateTime)
{
return false;
}
if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean)
{
return true;
}
try
{
if (value is string)
Double.Parse(value as string);
else
Double.Parse(value.ToString());
return true;
}
catch { }
return false;
}
It works for other data types. Should work fine for what you want to do.
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=db-server;'
'Database=db;'
'Trusted_Connection=yes;')
sql = "SELECT * FROM [mytable] "
cursor.execute(sql)
for r in cursor:
print(r)
Your @Entity
class has a String
type for its @Id
field, so it can't generate ids for you.
If you change it to an auto increment in the DB and a Long
in java, and add the @GeneratedValue
annotation:
@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;
it will handle incrementing id generation for you.
Be aware if you want to execute AJAX requests inside the event handler function for the click event. For some reason Chrome (and maybe other browsers) will not open a new tab/window.
With angular4 we just need to organise routes together in hierarchy
const appRoutes: Routes = [
{
path: '',
component: MainPageComponent
},
{
path: 'car/details',
component: CarDetailsComponent
},
{
path: 'car/details/platforms-products',
component: CarProductsComponent
},
{
path: 'car/details/:id',
component: CadDetailsComponent
},
{
path: 'car/details/:id/platforms-products',
component: CarProductsComponent
}
];
This works for me . This way router know what is the next route based on option id parameters.
Why not use the s3path
package which makes it as convenient as working with pathlib
? If you must however use boto3
:
boto3.resource
This builds upon the answer by itz-azhar to apply an optional limit
. It is obviously substantially simpler to use than the boto3.client
version.
import logging
from typing import List, Optional
import boto3
from boto3_type_annotations.s3 import ObjectSummary # pip install boto3_type_annotations
log = logging.getLogger(__name__)
_S3_RESOURCE = boto3.resource("s3")
def s3_list(bucket_name: str, prefix: str, *, limit: Optional[int] = None) -> List[ObjectSummary]:
"""Return a list of S3 object summaries."""
# Ref: https://stackoverflow.com/a/57718002/
return list(_S3_RESOURCE.Bucket(bucket_name).objects.limit(count=limit).filter(Prefix=prefix))
if __name__ == "__main__":
s3_list("noaa-gefs-pds", "gefs.20190828/12/pgrb2a", limit=10_000)
boto3.client
This uses list_objects_v2
and builds upon the answer by CpILL to allow retrieving more than 1000 objects.
import logging
from typing import cast, List
import boto3
log = logging.getLogger(__name__)
_S3_CLIENT = boto3.client("s3")
def s3_list(bucket_name: str, prefix: str, *, limit: int = cast(int, float("inf"))) -> List[dict]:
"""Return a list of S3 object summaries."""
# Ref: https://stackoverflow.com/a/57718002/
contents: List[dict] = []
continuation_token = None
if limit <= 0:
return contents
while True:
max_keys = min(1000, limit - len(contents))
request_kwargs = {"Bucket": bucket_name, "Prefix": prefix, "MaxKeys": max_keys}
if continuation_token:
log.info( # type: ignore
"Listing %s objects in s3://%s/%s using continuation token ending with %s with %s objects listed thus far.",
max_keys, bucket_name, prefix, continuation_token[-6:], len(contents)) # pylint: disable=unsubscriptable-object
response = _S3_CLIENT.list_objects_v2(**request_kwargs, ContinuationToken=continuation_token)
else:
log.info("Listing %s objects in s3://%s/%s with %s objects listed thus far.", max_keys, bucket_name, prefix, len(contents))
response = _S3_CLIENT.list_objects_v2(**request_kwargs)
assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
contents.extend(response["Contents"])
is_truncated = response["IsTruncated"]
if (not is_truncated) or (len(contents) >= limit):
break
continuation_token = response["NextContinuationToken"]
assert len(contents) <= limit
log.info("Returning %s objects from s3://%s/%s.", len(contents), bucket_name, prefix)
return contents
if __name__ == "__main__":
s3_list("noaa-gefs-pds", "gefs.20190828/12/pgrb2a", limit=10_000)
My guess is that $_.Name does not exist.
If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_
Either you need
std::function<void(Foo*)> f = &Foo::doSomething;
so that you can call it on any instance, or you need to bind a specific instance, for example this
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
You can't use float
inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle
.
So if you want to position child
element to right of parent
element you can use margin-left: auto
but now child
element will also push other div
to the right as you can see here Fiddle
.
What you can do now is change order of elements and set order: 2
on child
element so it doesn't affect second div
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
margin-left: auto;_x000D_
order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">Ignore parent?</div>_x000D_
<div>another child</div>_x000D_
</div>
_x000D_
You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.
If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)
I researched on the internet and some answers includes enabling the "access for lesser app" and "unlocking gmail captcha" which sadly didn't work for me until I found the 2-step verification.
What I did the following was:
enable the 2-step verification to google HERE
Create App Password to be use by your system HERE
I selected Others (custom name) and clicked generate
Went to my env file in laravel and edited this
MAIL_PASSWORD=thepasswordgenerated
This was my solution. I created this to atleast make other people not go wasting their time researching for a possible answer.
Firebug seems to allow you to do that.
Here is a method to trim a String that has a "," or white space
private String shorterName(String s){
String[] sArr = s.split("\\,|\\s+");
String output = sArr[0];
return output;
}
After struggling with this myself, I've come to implement FileReader for browsers that support it (Chrome, Firefox and the as-yet unreleased Safari 6), and a PHP script that echos back POSTed file data as Base64-encoded data for the other browsers.
The changelog is sloppily worded. from __future__ import absolute_import
does not care about whether something is part of the standard library, and import string
will not always give you the standard-library module with absolute imports on.
from __future__ import absolute_import
means that if you import string
, Python will always look for a top-level string
module, rather than current_package.string
. However, it does not affect the logic Python uses to decide what file is the string
module. When you do
python pkg/script.py
pkg/script.py
doesn't look like part of a package to Python. Following the normal procedures, the pkg
directory is added to the path, and all .py
files in the pkg
directory look like top-level modules. import string
finds pkg/string.py
not because it's doing a relative import, but because pkg/string.py
appears to be the top-level module string
. The fact that this isn't the standard-library string
module doesn't come up.
To run the file as part of the pkg
package, you could do
python -m pkg.script
In this case, the pkg
directory will not be added to the path. However, the current directory will be added to the path.
You can also add some boilerplate to pkg/script.py
to make Python treat it as part of the pkg
package even when run as a file:
if __name__ == '__main__' and __package__ is None:
__package__ = 'pkg'
However, this won't affect sys.path
. You'll need some additional handling to remove the pkg
directory from the path, and if pkg
's parent directory isn't on the path, you'll need to stick that on the path too.
You can use @PropertySource
to externalize your configuration to a properties file. There is number of way to do get properties:
1.
Assign the property values to fields by using @Value
with PropertySourcesPlaceholderConfigurer
to resolve ${}
in @Value
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Value("${gMapReportUrl}")
private String gMapReportUrl;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
2.
Get the property values by using Environment
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Autowired
private Environment env;
public void foo() {
env.getProperty("gMapReportUrl");
}
}
Hope this can help
Just special-case it. If you see a numerator of 0 and a denominator of 0, pretend like it has the values you really want.
var EmployeeController = ["$scope", "EmployeeService",
function ($scope, EmployeeService) {
$scope.Employee = {};
$scope.Save = function (Employee) {
if ($scope.EmployeeForm.$valid) {
EmployeeService
.Save(Employee)
.then(function (response) {
if (response.HasError) {
$scope.HasError = response.HasError;
$scope.ErrorMessage = response.ResponseMessage;
} else {
}
})
.catch(function (response) {
});
}
}
}]
var EmployeeService = ["$http", "$q",
function ($http, $q) {
var self = this;
self.Save = function (employee) {
var deferred = $q.defer();
$http
.post("/api/EmployeeApi/Create", angular.toJson(employee))
.success(function (response, status, headers, config) {
deferred.resolve(response, status, headers, config);
})
.error(function (response, status, headers, config) {
deferred.reject(response, status, headers, config);
});
return deferred.promise;
};
you can use str.index
too:
>>> 'sdfasdf'.index('cc')
Traceback (most recent call last):
File "<pyshell#144>", line 1, in <module>
'sdfasdf'.index('cc')
ValueError: substring not found
>>> 'sdfasdf'.index('df')
1
I had this error
(Illuminate\Contracts\Container\BindingResolutionException Target class [App\Http\Controllers\ControllerFileName] does not exist.
Solution: just check your class Name, it should be the exact same of your file name.
The JSON format can contain only those types of value:
An image is of the type "binary" which is none of those. So you can't directly insert an image into JSON. What you can do is convert the image to a textual representation which can then be used as a normal string.
The most common way to achieve that is with what's called base64. Basically, instead of encoding it as 1
and 0
s, it uses a range of 64 characters which makes the textual representation of it more compact. So for example the number '64' in binary is represented as 1000000
, while in base64 it's simply one character: =
.
There are many ways to encode your image in base64 depending on if you want to do it in the browser or not.
Note that if you're developing a web application, it will be way more efficient to store images separately in binary form, and store paths to those images in your JSON or elsewhere. That also allows your client's browser to cache the images.
Just add profile to session configuration before client call.
boto3.session.Session(profile_name='YOUR_PROFILE_NAME').client('cloudwatch')
I have an Activity that extends ListActivity.
I tried doing something like this in onCreate:
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("Hello!", "Y u no see me?");
}
});
But that didn't work.
Instead I simply needed to override onListItemClick:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.i("Hello!", "Clicked! YAY!");
}
You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.
Add the runat="server" attribute to the tag, then you can reference it from the codebehind.
Try this:
wget -nd -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.somedomain.com
Here is some more information:
-nd
prevents the creation of a directory hierarchy (i.e. no directories).
-r
enables recursive retrieval. See Recursive Download for more information.
-P
sets the directory prefix where all files and directories are saved to.
-A
sets a whitelist for retrieving only certain file types. Strings and patterns are accepted, and both can be used in a comma separated list (as seen above). See Types of Files for more information.
Despite the fact that this question has been answered long time ago, I found some interesting facts to add that are related to the answers above.
As Dirk mentioned, there seems to be a weird fashion of version control from MS, starting from Office 365 / 2019. You cannot distinguish among the three(2016, 2019, O365), by seeing at the executable paths anymore. And just like he reputed himself, looking at the builds of the executable, as a mean of telling which is what, isn't quite effective either.
After some researching, I found a feasible solution. The solution lies under the registry subkey Computer\HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Licensing\LicensingNext
.
So, my logic follows below:
Case 1: If the computer has the MSOffice 2016 installed, there is no subkeys under Licensing
.
Case 2: if the computer has MSOffice 2019 installed, there is the name of the value (which is one of the Office Product ID). (e.g. Standard2019Volume
)
Case 3: if the computer has Office365 installed, there is a value called o365bussinessretail
(which is also a product ID) along with some other values.
The possible productIds are provided here.
To distinguish the three, I just opened the key and see if fails. If the open fails, its Office 2016. Then I enumerate LicensingNext
and try to see if any name has a prefix o365
, if it finds it then its O365. If it does not, then its Office 2019.
Frankly speaking, I did not have enough time to test the logic under varying environment. So please, note that.
Hope this will help whoever's interest.
Both {} and && will cause problems due to being expanded by the command line. I would suggest trying:
find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i \{} -sameq \{}.mp3 \; -exec rm \{} \;
You can using dict
, fillna
with different value for different column
df.fillna({'a':0,'b':0})
Out[829]:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 0.0 7.0
3 0.0 6.0 8.0
After assign it back
df=df.fillna({'a':0,'b':0})
df
Out[831]:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 0.0 7.0
3 0.0 6.0 8.0
An alternative to the many solutions already provided is making use of the glob **
. When you use bash
with the option globstar
(shopt -s globstar
) or you make use of zsh
, you can just use the glob **
for this.
**/bar
does a recursive directory search for files named bar
(potentially including the file bar
in the current directory). Remark that this cannot be combined with other forms of globbing within the same path segment; in that case, the *
operators revert to their usual effect.
Note that there is a subtle difference between zsh
and bash
here. While bash
will traverse soft-links to directories, zsh
will not. For this you have to use the glob ***/
in zsh
.
I solve this by using path variable. The sample code will look like below.
var path = require("path");
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
})
You are probably using Console.WriteLine
for printing the array.
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.WriteLine(item.ToString());
}
If you don't want to have every item on a separate line use Console.Write
:
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.Write(item.ToString());
}
or string.Join<T>
(in .NET Framework 4 or later):
int[] array = new int[] { 1, 2, 3 };
Console.WriteLine(string.Join(",", array));
I assume you need to save couchdb-cartridge
which has an image id of 7ebc8510bc2c:
stratos@Dev-PC:~$ docker images
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
couchdb-cartridge latest 7ebc8510bc2c 17 hours ago 1.102 GB
192.168.57.30:5042/couchdb-cartridge latest 7ebc8510bc2c 17 hours ago 1.102 GB
ubuntu 14.04 53bf7a53e890 3 days ago 221.3 MB
Save the archiveName image to a tar file. I will use the /media/sf_docker_vm/
to save the image.
stratos@Dev-PC:~$ docker save imageID > /media/sf_docker_vm/archiveName.tar
Copy the archiveName.tar file to your new Docker instance using whatever method works in your environment, for example FTP
, SCP
, etc.
Run the docker load
command on your new Docker instance and specify the location of the image tar file.
stratos@Dev-PC:~$ docker load < /media/sf_docker_vm/archiveName.tar
Finally, run the docker images
command to check that the image is now available.
stratos@Dev-PC:~$ docker images
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
couchdb-cartridge latest 7ebc8510bc2c 17 hours ago 1.102 GB
192.168.57.30:5042/couchdb-cartridge latest bc8510bc2c 17 hours ago 1.102 GB
ubuntu 14.04 4d2eab1c0b9a 3 days ago 221.3 MB
Please find this detailed post.
<% form_for(@message) do |f| %>
<%= f.radio_button :contactmethod, 'email', :checked => true %>
<%= label :contactmethod_email, 'Email' %>
<%= f.radio_button :contactmethod, 'sms' %>
<%= label :contactmethod_sms, 'SMS' %>
<% end %>
I also just ran in to a similar problem, that is service apache2 reload
fails but prints no useful information. This is because the script in /etc/init.d/apache
(on Debian, at least) eats the output of the apache2ctl configtest
command it runs to sanitize the Apache config.
An easy solution to get a more meaningful explanation for the failure is to run apache2ctl configtest
again yourself, which will print the (hopefully useful) error messages to the console.
I would actually suggest you a time saving way to go with this assuming that you know what kind of tags have those attributes.
suppose say a tag xyz has that attritube named "staininfo"..
full_tag = soup.findAll("xyz")
And i wan't you to understand that full_tag is a list
for each_tag in full_tag:
staininfo_attrb_value = each_tag["staininfo"]
print staininfo_attrb_value
Thus you can get all the attrb values of staininfo for all the tags xyz
Again, even though this is an old question, it is very relevant! And I have found a simple way to normalise certain columns without the need of any packages:
normFunc <- function(x){(x-mean(x, na.rm = T))/sd(x, na.rm = T)}
For example
x<-rnorm(10,14,2)
y<-rnorm(10,7,3)
z<-rnorm(10,18,5)
df<-data.frame(x,y,z)
df[2:3] <- apply(df[2:3], 2, normFunc)
You will see that the y and z columns have been normalised. No packages needed :-)
the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)
=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679
So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)
If you want to add wsdl reference in .Net Core project, there is no "Add web reference" option.
To add the wsdl reference go to Solution Explorer, right-click on the References project item and then click on the Add Connected Service option.
Then click 'Microsoft WCF Web Service Reference':
Enter the file path into URI text box and import the WSDL:
It will generate a simple, very basic WCF client and you to use it something like this:
YourServiceClient client = new YourServiceClient();
client.DoSomething();
you can use a simple list comprehension:
x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]
I'd recommend using the MomentJS libraries. They make all interactions with Dates a lot simpler.
If you use Moment, your code would be as simple as this:
var today = moment();
var nextMonth = today.add('month', 1);
// note that both variables `today` and `nextMonth` refer to
// the next month at this point, because `add` mutates in-place
You can find MomentJS here: http://momentjs.com/
UPDATE:
In JavaScript, the Date.getDate() function returns the current day of the month from 1-31. You are subtracting 6 from this number, and it is currently the 3rd of the month. This brings the value to -3.
In your CSS Style tag put this:
body {
background: url('yourgif.gif') no-repeat center center fixed;
background-size: cover;
}
If you are using Outlook to send a static image with hyperlink, an easy way would be to use Word.
.clearfix
is defined in less/mixins.less
. Right above its definition is a comment with a link to this article:
The article explains how it all works.
UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):
This “micro clearfix” generates pseudo-elements and sets their
display
totable
. This creates an anonymous table-cell and a new block formatting context that means the:before
pseudo-element prevents top-margin collapse. The:after
pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.Including the
:before
selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:
It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g.,
overflow:hidden
It ensures visual consistency with IE 6/7 when
zoom:1
is applied.N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.
The use of
content:" "
(note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if thecontenteditable
attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to usefont:0/0 a
.Legacy Firefox
Firefox < 3.5 will benefit from using Thierry’s method with the addition of
visibility:hidden
to hide the inserted character. This is because legacy versions of Firefox needcontent:"."
to avoid extra space appearing between thebody
and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)Alternative float-containment methods that create a new block formatting context, such as applying
overflow:hidden
ordisplay:inline-block
to the container element, will also avoid this behaviour in legacy versions of Firefox.
For me the problem was I had to use /usr/bin/php-cgi
command instead of just /usr/bin/php
php-cgi is the command run when accessed thru web browser.
php is the CLI command line command.
Not sure why php cli is not working, but running with php-cgi instead fixed the problem for me.
The example 1 will not compile. This version of it compiles and runs. It uses lambda features to abbreviate it.
/*
* [RollYourOwnTimeouts.java]
*
* Summary: How to roll your own timeouts.
*
* Copyright: (c) 2016 Roedy Green, Canadian Mind Products, http://mindprod.com
*
* Licence: This software may be copied and used freely for any purpose but military.
* http://mindprod.com/contact/nonmil.html
*
* Requires: JDK 1.8+
*
* Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
*
* Version History:
* 1.0 2016-06-28 initial version
*/
package com.mindprod.example;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static java.lang.System.*;
/**
* How to roll your own timeouts.
* Based on code at http://stackoverflow.com/questions/19456313/simple-timeout-in-java
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2016-06-28 initial version
* @since 2016-06-28
*/
public class RollYourOwnTimeout
{
private static final long MILLIS_TO_WAIT = 10 * 1000L;
public static void main( final String[] args )
{
final ExecutorService executor = Executors.newSingleThreadExecutor();
// schedule the work
final Future<String> future = executor.submit( RollYourOwnTimeout::requestDataFromWebsite );
try
{
// where we wait for task to complete
final String result = future.get( MILLIS_TO_WAIT, TimeUnit.MILLISECONDS );
out.println( "result: " + result );
}
catch ( TimeoutException e )
{
err.println( "task timed out" );
future.cancel( true /* mayInterruptIfRunning */ );
}
catch ( InterruptedException e )
{
err.println( "task interrupted" );
}
catch ( ExecutionException e )
{
err.println( "task aborted" );
}
executor.shutdownNow();
}
/**
* dummy method to read some data from a website
*/
private static String requestDataFromWebsite()
{
try
{
// force timeout to expire
Thread.sleep( 14_000L );
}
catch ( InterruptedException e )
{
}
return "dummy";
}
}
You could inititialize it with a size of 0, but you will have to reinitialize it, when you know what the size is, as you cannot append to the array.
string[] a = new string[0];
Use this in your my.ini
under
[mysqldump]
user=root
password=anything
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
Just like any other simple command, [ ... ]
or test
requires spaces between its arguments.
if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
fi
Or
if test "$#" -ne 1; then
echo "Illegal number of parameters"
fi
When in Bash, prefer using [[ ]]
instead as it doesn't do word splitting and pathname expansion to its variables that quoting may not be necessary unless it's part of an expression.
[[ $# -ne 1 ]]
It also has some other features like unquoted condition grouping, pattern matching (extended pattern matching with extglob
) and regex matching.
The following example checks if arguments are valid. It allows a single argument or two.
[[ ($# -eq 1 || ($# -eq 2 && $2 == <glob pattern>)) && $1 =~ <regex pattern> ]]
For pure arithmetic expressions, using (( ))
to some may still be better, but they are still possible in [[ ]]
with its arithmetic operators like -eq
, -ne
, -lt
, -le
, -gt
, or -ge
by placing the expression as a single string argument:
A=1
[[ 'A + 1' -eq 2 ]] && echo true ## Prints true.
That should be helpful if you would need to combine it with other features of [[ ]]
as well.
Take note that [[ ]]
and (( ))
are keywords which have same level of parsing as if
, case
, while
, and for
.
Also as Dave suggested, error messages are better sent to stderr so they don't get included when stdout is redirected:
echo "Illegal number of parameters" >&2
It's also logical to make the script exit when invalid parameters are passed to it. This has already been suggested in the comments by ekangas but someone edited this answer to have it with -1
as the returned value, so I might as well do it right.
-1
though accepted by Bash as an argument to exit
is not explicitly documented and is not right to be used as a common suggestion. 64
is also the most formal value since it's defined in sysexits.h
with #define EX_USAGE 64 /* command line usage error */
. Most tools like ls
also return 2
on invalid arguments. I also used to return 2
in my scripts but lately I no longer really cared, and simply used 1
in all errors. But let's just place 2
here since it's most common and probably not OS-specific.
if [[ $# -ne 1 ]]; then
echo "Illegal number of parameters"
exit 2
fi
First, see if you have splitunc()
as an available function within os.path
. The first item returned should be what you want... but I am on Linux and I do not have this function when I import os
and try to use it.
Otherwise, one semi-ugly way that gets the job done is to use:
>>> pathname = "\\C:\\mystuff\\project\\file.py"
>>> pathname
'\\C:\\mystuff\\project\\file.py'
>>> print pathname
\C:\mystuff\project\file.py
>>> "\\".join(pathname.split('\\')[:-2])
'\\C:\\mystuff'
>>> "\\".join(pathname.split('\\')[:-1])
'\\C:\\mystuff\\project'
which shows retrieving the directory just above the file, and the directory just above that.
String.format("%1$,.2f", myDouble);
String.format
automatically uses the default locale.
You could also use countplot
from seaborn
. This package builds on pandas
to create a high level plotting interface. It gives you good styling and correct axis labels for free.
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame({'colour': ['red', 'blue', 'green', 'red', 'red', 'yellow', 'blue'],
'direction': ['up', 'up', 'down', 'left', 'right', 'down', 'down']})
sns.countplot(df['colour'], color='gray')
It also supports coloring the bars in the right color with a little trick
sns.countplot(df['colour'],
palette={color: color for color in df['colour'].unique()})
http://www.rgagnon.com/javadetails/java-0198.html
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
public class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
Then
import java.awt.*;
import javax.swing.*;
public class DemoJTextFieldWithLimit extends JApplet{
JTextField textfield1;
JLabel label1;
public void init() {
getContentPane().setLayout(new FlowLayout());
//
label1 = new JLabel("max 10 chars");
textfield1 = new JTextField(15);
getContentPane().add(label1);
getContentPane().add(textfield1);
textfield1.setDocument
(new JTextFieldLimit(10));
}
}
(first result from google)
Console.WriteLine allows the user to specify a position in a string.
See sample:
string str = "Tigger"; Console.WriteLine( str[0] ); //returns "T"; Console.WriteLine( str[2] ); //returns "g";
There you go!
http://stefangabos.ro/jquery/zebra-datepicker
use zebra date pickers:
$('#select_month1').Zebra_DatePicker({
direction: false,
format: 'Y-m-d',
pair: $('#select_month2')
});
$('#select_month2').Zebra_DatePicker({
direction: 1, format: 'Y-m-d',
});
Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.
This sounds like homework. If so, please tag it as such.
Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.
Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.
Use transform;
<style type="text/css">
#mydiv {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
Javascript Solution :
var left = (screen.width / 2) - (530 / 2);
var top = (screen.height / 2) - (500 / 2);
var _url = 'PopupListRepair.aspx';
window.open(_url, self, "width=530px,height=500px,status=yes,resizable=no,toolbar=no,menubar=no,left=" + left + ",top=" + top + ",scrollbars=no");
create's an object :
// create a data object to store the information below.
var data = new Object();
// this could be a suffix of a url string.
var string = "?id=5&first=John&last=Doe";
// this will now loop through the string and pull out key value pairs seperated
// by the & character as a combined string, in addition it passes up the ? mark
var pairs = string.substring(string.indexOf('?')+1).split('&');
for(var key in pairs)
{
var value = pairs[key].split("=");
data[value[0]] = value[1];
}
// creates this object
var data = {"id":"5", "first":"John", "last":"Doe"};
// you can then access the data like this
data.id = "5";
data.first = "John";
data.last = "Doe";
One of the ways that you can run your spring-boot application from command line is as follows :
1) First go to your project directory in command line [where is your project located ?]
2) Then in the next step you have to create jar file for that, this can be done as
mvnw package
[for WINDOWS OS ] or ./mvnw package
[for MAC OS] , this will
create jar file for our application.
3) jar file is created in the target sub-directory
4)Now go to target sub directory as jar was created inside of it , i.e cd target
5) Now run the jar file in there.
Use command java -jar name.jar
[ name is the name of your created jar file.]
and there you go , you are done . Now you can run project in browser,
http://localhost:port_number
I could see $.ajax
is removed from jQuery slim 3.2.1
From the jQuery docs
You can also use the slim build, which excludes the ajax and effects modules
Below is the comment from the slim version with the features removed
/*! jQuery v3.2.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */
You can do this conversion with the OpenSSL library
Windows binaries can be found here:
http://www.slproweb.com/products/Win32OpenSSL.html
Once you have the library installed, the command you need to issue is:
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
git branch --set-upstream <<origin/branch>>
is officially not supported anymore and is replaced by git branch --set-upstream-to <<origin/branch>>
Isn't this as simple as adding your git install to your Windows path?
E.g. Win+R rundll32.exe sysdm.cpl,EditEnvironmentVariables
Edit...PATH appending your Mysysgit install path e.g. ;C:\Program Files (x86)\Git\bin
. Re-run Cygwin and voila. As Cygwin automatically loads in the Windows environment, so too will your native install of Git.
I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.
Here is the Pipe being called in an *ngFor directive,
<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
Hello {{item.first}} !
</div>
Here is the Pipe,
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
transform(myobjects: Array<object>, args?: Array<object>): any {
if (args && Array.isArray(myobjects)) {
// copy all objects of original array into new array of objects
var returnobjects = myobjects;
// args are the compare oprators provided in the *ngFor directive
args.forEach(function (filterobj) {
let filterkey = Object.keys(filterobj)[0];
let filtervalue = filterobj[filterkey];
myobjects.forEach(function (objectToFilter) {
if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
// object didn't match a filter value so remove it from array via filter
returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
}
})
});
// return new array of objects to *ngFor directive
return returnobjects;
}
}
}
And here is the Component containing the object to filter,
import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
items = [{ title: "mr", first: "john", last: "jones" }
,{ title: "mr", first: "adrian", last: "jacobs" }
,{ title: "mr", first: "lou", last: "jones" }
,{ title: "ms", first: "linda", last: "hamilton" }
];
}
GitHub Example: Fork a working copy of this example here
*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.
Happy Coding :-)
This is the version that works in IE 9.
<div style="display:table; table-layout: fixed; width:100%; " >
<div style="display:table-row;">
<div style="display:table-cell;">
<table style="width: 100%; table-layout: fixed;">
<div style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">First row. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</table>
</div>
<div style="display:table-cell;">
Top right Cell.
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<table style="width: 100%; table-layout: fixed;">
<div style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">Second row - Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</table>
</div>
<div style="display:table-cell;">
Bottom right cell.
</div>
</div>
</div>
If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.
Start Visual Studio. Go to Tools->Options and expand Projects and solutions. Select VC++ Directories from the tree and choose Include Files from the combo on the right.
You should see:
$(WindowsSdkDir)\include
If this is missing, you found a problem. If not, search for a file. It should be located in
32 bit systems:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include
64 bit systems:
C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\Include
if VS was installed in the default directory.
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.
You can try the quickselect algorithm if faster average-case running times are needed. Quickselect has average (and best) case performance O(n)
, although it can end up O(n²)
on a bad day.
Here's an implementation with a randomly chosen pivot:
import random
def select_nth(n, items):
pivot = random.choice(items)
lesser = [item for item in items if item < pivot]
if len(lesser) > n:
return select_nth(n, lesser)
n -= len(lesser)
numequal = items.count(pivot)
if numequal > n:
return pivot
n -= numequal
greater = [item for item in items if item > pivot]
return select_nth(n, greater)
You can trivially turn this into a method to find medians:
def median(items):
if len(items) % 2:
return select_nth(len(items)//2, items)
else:
left = select_nth((len(items)-1) // 2, items)
right = select_nth((len(items)+1) // 2, items)
return (left + right) / 2
This is very unoptimised, but it's not likely that even an optimised version will outperform Tim Sort (CPython's built-in sort
) because that's really fast. I've tried before and I lost.
There is a simple and clean way of doing this with only directives.
<div ng-class="{'class-name': clicked}" ng-click="clicked = !clicked"></div>
Config caching
The laravel config spreads across dozens of files, and including
every one of them for each request is a costly process. To combine all of your config files into one, use:
php artisan config:cache
Keep in mind that any changes to the config will not have any effect once you cache it. To refresh the config cache, run the above command again. In case you want to completely get rid of the config cache, run
php artisan config:clear
Routes caching Routing is also an expensive task in laravel. To cache the routes.php file run the below command:
php artisan route:cache
Mind that it doesn't work with closures. In case you're using closures this is a great chance to move them into a controller, as the artisan command will throw an exception when trying to compile routes that are bound to closures instead of proper controller methods. In the same as the config cache, any changes to routes.php will not have any effect anymore. To refresh the cache, run the above command everytime you do a change to the routes file. To completely get rid of the route cache, run the below command:
php artisan route:clear
Classmap optimization
It's not uncommon for a medium-sized project to be spread across hundreds of PHP files. As good coding behaviours dictate us, everything has its own file. This, of course, does not come without drawbacks. Laravel has to include dozens of different files for each request, which is a costly thing to do.
Hence, a good optimization method is declaring which files are used for every request (this is, for example, all your service providers, middlewares and a few more) and combining them in only one file, which will be afterwards loaded for each request. This not different from combining all your javascript files into one, so the browser will have to make fewer requests to the server.
The additional compiles files (again: service providers, middlewares and so on) should be declared by you in config/compile.php, in the files key. Once you put there everything essential for every request made to your app, concatenate them in one file with:
php artisan optimize --force
Optimizing the composer autoload
This one is not only for laravel, but for any application that's making use of composer.
I'll explain first how the PSR-4 autoload works, and then I'll show you what command you should run to optimize it. If you're not interested in knowing how composer works, I recommend you jumping directly to the console command.
When you ask composer for the App\Controllers\AuthController
class, it first searches for a direct association in the classmap. The classmap is an array with 1-to-1 associations of classes and files. Since, of course, you did not manually add the Login class and its associated file to the classmap, composer will move on and search in the namespaces.
Because App is a PSR-4 namespace, which comes by default with Laravel and it's associated to the app/
folder, composer will try converting the PSR-4 class name to a filename with basic string manipulation procedures. In the end, it guesses that App\Controllers\AuthController
must be located in an AuthController.php file, which is in a Controllers/
folder that should luckily be in the namespace folder, which is app/
.
All this hard work only to get that the App\Controllers\AuthController
class exists in the app/Controllers/AuthController.php
file. In order to have composer scanning your entire application and create direct 1-to-1 associations of classes and files, run the following command:
composer dumpautoload -o
Keep in mind that if you already ran php artisan optimize --force, you don't have to run this one anymore. Since the optimize command already tells composer to create an optimized autoload.
Map can also be used, but sometimes hard to read when you have lots of things going on.
map{ print "element $_\n" } @array;
My preference is to utilize the inline
attribute. This will cause the icon to correctly scale with the size of the button.
<button mat-button>
<mat-icon inline=true>local_movies</mat-icon>
Movies
</button>
<!-- Link button -->
<a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>
I add this to my styles.css
to:
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
vertical-align: top;
font-size: 1.25em;
}
in VS 2017 I cleaned the solution and rebuilt it and that fixed it
Try this:
$('#select_all').click(function() {
$('#countries option').prop('selected', true);
});
And here's a live demo.
I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )
html, body {
overflow-x: hidden;
}
body {
position: relative;
}
The position relative is important, and i just stumbled about it. Could not make it work without it.
To avoid this sort of trouble, you can use replace
(which takes a plain string) instead of replaceAll
(which takes a regular expression). You will still need to escape backslashes, but not in the wild ways required with regular expressions.
function dateConvertor(date){
var options = { weekday: "long",
year: "numeric",
month: "short",
day: "numeric" };
var newDateFormat = new Date(date).toLocaleDateString("en-US", options);
var newTimeFormat = new Date(date).toLocaleTimeString();
var dateAndTime = newDateFormat +' ' + newTimeFormat
return dateAndTime
}
console.log(dateConvertor("2021-01-19T18:30:00.000Z"));
_x000D_
You can set events on a combination of key and mouse events, and onblur as well, to be sure. In that event, store the value of the input. In the next call, compare the current value with the lastly stored value. Only do your magic if it has actually changed.
To do this in a more or less clean way:
You can associate data with a DOM element (lookup api.jquery.com/jQuery.data ) So you can write a generic set of event handlers that are assigned to all elements in the form. Each event can pass the element it was triggered by to one generic function. That one function can add the old value to the data of the element. That way, you should be able to implement this as a generic piece of code that works on your whole form and every form you'll write from now on. :) And it will probably take no more than about 20 lines of code, I guess.
An example is in this fiddle: http://jsfiddle.net/zeEwX/
Extending your code (assuming that the XML you want to send is in xmlString
) :
String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);
you can use Dependency Walker to view the function name. you can see the function's parameters only if it's decorated. read the following from the FAQ:
How do I view the parameter and return types of a function? For most functions, this information is simply not present in the module. The Windows' module file format only provides a single text string to identify each function. There is no structured way to list the number of parameters, the parameter types, or the return type. However, some languages do something called function "decoration" or "mangling", which is the process of encoding information into the text string. For example, a function like int Foo(int, int) encoded with simple decoration might be exported as _Foo@8. The 8 refers to the number of bytes used by the parameters. If C++ decoration is used, the function would be exported as ?Foo@@YGHHH@Z, which can be directly decoded back to the function's original prototype: int Foo(int, int). Dependency Walker supports C++ undecoration by using the Undecorate C++ Functions Command.
You can get path by this code
Dim CurDir as string = My.Application.Info.DirectoryPath
Only IE6-8 - there's an ActiveX workaround this local-files issue in JavaScript:
function OpenImage(filePath)
{
var myshell = new ActiveXObject("WScript.shell");
myshell.run(filePath, 1, true);
}
Let's say that your time value is in cell A1
then in A2
you can put:
=A1*1000*60*60*24
or simply:
=A1*86400000
What I am doing is taking the decimal value of the time and multiply it by 1000 (milliseconds) and 60 (seconds) and 60 (minutes) and 24 (hours).
You will then need to format cell A2
as General for it to be in milliseconds format.
If your time is a text value then use:
=TIMEVALUE(A1)*86400000
UPDATE
Per @dandfra's comment this solution may not work in the Italian version of Excel.
df.T.iloc[-1]
df.T.tail(1)
pd.Series(df.values[:, -1], name=df.columns[-1])
Not to reorganize imports (not to unfold .* and not to reorder lines) to have least VCS changeset
you can use custom eclipse clenup as this answer suggests
You simply need to add that line legend: { display: false }
div[disabled]
{
pointer-events: none;
opacity: 0.6;
background: rgba(200, 54, 54, 0.5);
background-color: yellow;
filter: alpha(opacity=50);
zoom: 1;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
-moz-opacity: 0.5;
-khtml-opacity: 0.5;
}
As the messages above indicate, the List cannot be differentiated between a List<Object>
and a List<String>
or List<Integer>
.
I've solved this error message for a similar problem:
List<String> strList = (List<String>) someFunction();
String s = strList.get(0);
with the following:
List<?> strList = (List<?>) someFunction();
String s = (String) strList.get(0);
Explanation: The first type conversion verifies that the object is a List without caring about the types held within (since we cannot verify the internal types at the List level). The second conversion is now required because the compiler only knows the List contains some sort of objects. This verifies the type of each object in the List as it is accessed.
I was failing to send a body on a DELETE that required one and was getting this message as a result.
Use the default version:
Collections.sort(myarrayList);
Of course this requires that your Elements implement Comparable
, but the same holds true for the version you mentioned.
BTW: you should use generics in your code, that way you get compile-time errors if your class doesn't implement Comparable. And compile-time errors are much better than the runtime errors you'll get otherwise.
List<MyClass> list = new ArrayList<MyClass>();
// now fill up the list
// compile error here unless MyClass implements Comparable
Collections.sort(list);
Calculating RecyclerView
's height manually is not good, better is to use a custom LayoutManager
.
The reason for above issue is any view which has it's scroll(ListView
, GridView
, RecyclerView
) failed to calculate it's height when add as a child in another view has scroll. So overriding its onMeasure
method will solve the issue.
Please replace the default layout manager with the below:
public class MyLinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {
private static boolean canMakeInsetsDirty = true;
private static Field insetsDirtyField = null;
private static final int CHILD_WIDTH = 0;
private static final int CHILD_HEIGHT = 1;
private static final int DEFAULT_CHILD_SIZE = 100;
private final int[] childDimensions = new int[2];
private final RecyclerView view;
private int childSize = DEFAULT_CHILD_SIZE;
private boolean hasChildSize;
private int overScrollMode = ViewCompat.OVER_SCROLL_ALWAYS;
private final Rect tmpRect = new Rect();
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context) {
super(context);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view) {
super(view.getContext());
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view, int orientation, boolean reverseLayout) {
super(view.getContext(), orientation, reverseLayout);
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
public void setOverScrollMode(int overScrollMode) {
if (overScrollMode < ViewCompat.OVER_SCROLL_ALWAYS || overScrollMode > ViewCompat.OVER_SCROLL_NEVER)
throw new IllegalArgumentException("Unknown overscroll mode: " + overScrollMode);
if (this.view == null) throw new IllegalStateException("view == null");
this.overScrollMode = overScrollMode;
ViewCompat.setOverScrollMode(view, overScrollMode);
}
public static int makeUnspecifiedSpec() {
return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
final boolean hasWidthSize = widthMode != View.MeasureSpec.UNSPECIFIED;
final boolean hasHeightSize = heightMode != View.MeasureSpec.UNSPECIFIED;
final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;
final int unspecified = makeUnspecifiedSpec();
if (exactWidth && exactHeight) {
// in case of exact calculations for both dimensions let's use default "onMeasure" implementation
super.onMeasure(recycler, state, widthSpec, heightSpec);
return;
}
final boolean vertical = getOrientation() == VERTICAL;
initChildDimensions(widthSize, heightSize, vertical);
int width = 0;
int height = 0;
// it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
// happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
// recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
// called whiles scrolling)
recycler.clear();
final int stateItemCount = state.getItemCount();
final int adapterItemCount = getItemCount();
// adapter always contains actual data while state might contain old data (f.e. data before the animation is
// done). As we want to measure the view with actual data we must use data from the adapter and not from the
// state
for (int i = 0; i < adapterItemCount; i++) {
if (vertical) {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, widthSize, unspecified, childDimensions);
} else {
logMeasureWarning(i);
}
}
height += childDimensions[CHILD_HEIGHT];
if (i == 0) {
width = childDimensions[CHILD_WIDTH];
}
if (hasHeightSize && height >= heightSize) {
break;
}
} else {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, unspecified, heightSize, childDimensions);
} else {
logMeasureWarning(i);
}
}
width += childDimensions[CHILD_WIDTH];
if (i == 0) {
height = childDimensions[CHILD_HEIGHT];
}
if (hasWidthSize && width >= widthSize) {
break;
}
}
}
if (exactWidth) {
width = widthSize;
} else {
width += getPaddingLeft() + getPaddingRight();
if (hasWidthSize) {
width = Math.min(width, widthSize);
}
}
if (exactHeight) {
height = heightSize;
} else {
height += getPaddingTop() + getPaddingBottom();
if (hasHeightSize) {
height = Math.min(height, heightSize);
}
}
setMeasuredDimension(width, height);
if (view != null && overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS) {
final boolean fit = (vertical && (!hasHeightSize || height < heightSize))
|| (!vertical && (!hasWidthSize || width < widthSize));
ViewCompat.setOverScrollMode(view, fit ? ViewCompat.OVER_SCROLL_NEVER : ViewCompat.OVER_SCROLL_ALWAYS);
}
}
private void logMeasureWarning(int child) {
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
"To remove this message either use #setChildSize() method or don't run RecyclerView animations");
}
}
private void initChildDimensions(int width, int height, boolean vertical) {
if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
// already initialized, skipping
return;
}
if (vertical) {
childDimensions[CHILD_WIDTH] = width;
childDimensions[CHILD_HEIGHT] = childSize;
} else {
childDimensions[CHILD_WIDTH] = childSize;
childDimensions[CHILD_HEIGHT] = height;
}
}
@Override
public void setOrientation(int orientation) {
// might be called before the constructor of this class is called
//noinspection ConstantConditions
if (childDimensions != null) {
if (getOrientation() != orientation) {
childDimensions[CHILD_WIDTH] = 0;
childDimensions[CHILD_HEIGHT] = 0;
}
}
super.setOrientation(orientation);
}
public void clearChildSize() {
hasChildSize = false;
setChildSize(DEFAULT_CHILD_SIZE);
}
public void setChildSize(int childSize) {
hasChildSize = true;
if (this.childSize != childSize) {
this.childSize = childSize;
requestLayout();
}
}
private void measureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize, int[] dimensions) {
final View child;
try {
child = recycler.getViewForPosition(position);
} catch (IndexOutOfBoundsException e) {
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "MyLinearLayoutManager doesn't work well with animations. Consider switching them off", e);
}
return;
}
final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();
final int hPadding = getPaddingLeft() + getPaddingRight();
final int vPadding = getPaddingTop() + getPaddingBottom();
final int hMargin = p.leftMargin + p.rightMargin;
final int vMargin = p.topMargin + p.bottomMargin;
// we must make insets dirty in order calculateItemDecorationsForChild to work
makeInsetsDirty(p);
// this method should be called before any getXxxDecorationXxx() methods
calculateItemDecorationsForChild(child, tmpRect);
final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);
final int childWidthSpec = getChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
final int childHeightSpec = getChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.height, canScrollVertically());
child.measure(childWidthSpec, childHeightSpec);
dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;
// as view is recycled let's not keep old measured values
makeInsetsDirty(p);
recycler.recycleView(child);
}
private static void makeInsetsDirty(RecyclerView.LayoutParams p) {
if (!canMakeInsetsDirty) {
return;
}
try {
if (insetsDirtyField == null) {
insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");
insetsDirtyField.setAccessible(true);
}
insetsDirtyField.set(p, true);
} catch (NoSuchFieldException e) {
onMakeInsertDirtyFailed();
} catch (IllegalAccessException e) {
onMakeInsertDirtyFailed();
}
}
private static void onMakeInsertDirtyFailed() {
canMakeInsetsDirty = false;
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
}
}
}
Instead of
CGContextDrawImage(context, CGRectMake(0, 0, 145, 15), image.CGImage);
Use
[image drawInRect:CGRectMake(0, 0, 145, 15)];
In the middle of your begin/end CGcontext
methods.
This will draw the image with the correct orientation into your current image context - I'm pretty sure this has something to do with the UIImage
holding onto knowledge of the orientation while the CGContextDrawImage
method gets the underlying raw image data with no understanding of orientation.
easily set
position:absolute;
bottom:0;
width:100%;
to your .footer
just do it
select count(*)
from table_emp
where DATEPART(YEAR, ARR_DATE) = '2012' AND DATEPART(MONTH, ARR_DATE) = '01'
The syntax is :
.nav navbar-nav .navbar-right > li > a {
color: blue;
}
I suggest you to edit your .vimrc file, for running a list of commands. Edit your .vimrc file, like this :
cat >> ~/.vimrc <<EOF
set ffs=unix
set encoding=utf-8
set fileencoding=utf-8
set listchars=eol:¶
set list
EOF
When you're executing vim, the commands into .vimrc are executed, and you can see this example :
My line with CRLF eol here ^M¶