Webview can be used to load Url in your applicaion. URL can be provided from user in text view or you can hardcode it.
Also don't forget internet permissions in AndroidManifest.
String url="http://developer.android.com/index.html"
WebView wv=(WebView)findViewById(R.id.webView);
wv.setWebViewClient(new MyBrowser());
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl(url);
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
I had to do the same thing today and I have found a very useful answer on StackOverflow that I want to share here in case someone else needs it.
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
});
You can try YConsole a js embedded console. It is lightweight and simple to use.
How to use :
<script type="text/javascript" src="js/YConsole-compiled.js"></script>
<script type="text/javascript" >YConsole.show();</script>
A sort of block comment uses an if statement:
if(FALSE) {
all your code
}
It works, but I almost always use the block comment options of my editors (RStudio, Kate, Kwrite).
Please try as below to get the time difference in hh:mm:ss format
Select StartTime, EndTime, CAST((EndTime - StartTime) as time(0)) 'TotalTime' from [TableName]
To get all the elements starting with "jander" you should use:
$("[id^=jander]")
To get those that end with "jander"
$("[id$=jander]")
See also the JQuery documentation
Or try this ;)
try {
this.setContentPane(
new JLabel(new ImageIcon(ImageIO.read(new File("your_file.jpeg")))));
} catch (IOException e) {};
set width attribute as: width: fit-content
Use waitpid() like this:
pid_t childPid; // the child process that the execution will soon run inside of.
childPid = fork();
if(childPid == 0) // fork succeeded
{
// Do something
exit(0);
}
else if(childPid < 0) // fork failed
{
// log the error
}
else // Main (parent) process after fork succeeds
{
int returnStatus;
waitpid(childPid, &returnStatus, 0); // Parent process waits here for child to terminate.
if (returnStatus == 0) // Verify child process terminated without error.
{
printf("The child process terminated normally.");
}
if (returnStatus == 1)
{
printf("The child process terminated with an error!.");
}
}
In my case it was because of the url pattern I used
my url was like /ui/project/:parameter1/:parameter2.
I didn't need paramerter2 in all cases of state change. In cases where I didn't need the second parameter my url would be like /ui/project/:parameter1/. And so whenever I had a state change I will have my controller refreshed twice.
The solution was to set parameter2 as empty string and do the state change.
I see that this question is solved, but, I want to add some information than can help someone.
if you want use hex to set background color, I found this function and work:
func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}
I use this function as follows:
view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)
some times you must use self
:
self.view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)
Well that was it, I hope it helps someone .
sorry for my bad english.
this work on iOS 7.1+
For me, I started the app from within windows explorer (by double clicking on it). Then it crashed immediately.
I then opened Event Viewer
of windows and viewed Application
and it displayed full stacktrace of error. The stacktrace showed relation with Bitmap or images. It was then turned out to be due to app icon not found
You can do it by installing fonts, that means everywhere you want to run that particular application. Simplest way is just add this bl line to your jrxml file:
<property name="net.sf.jasperreports.awt.ignore.missing.font" value="true"/>
Hope it helps.
iData
is a private
member of the class. Now, the word private
have a very definite meaning, in C++ as well as in real life. It means you can't touch it. It's not a recommendation, it's the law. If you don't change the class declaration, you are not allowed to manipulate that member in any way, shape or form.
days + hours
. Minutes are not included.hh:mm
or x hours y minutes
, would require additional calculations and string formatting.timedelta
math, and is faster than using .astype('timedelta64[h]')
timedelta
objects: See supported operations.datetime64[ns] dtype
. It is required that all relevant columns are converted using pandas.to_datetime()
.import pandas as pd
# test data from OP, with values already in a datetime format
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}
# test dataframe; the columns must be in a datetime format; use pandas.to_datetime if needed
df = pd.DataFrame(data)
# add a timedelta column if wanted. It's added here for information only
# df['time_delta_with_sub'] = df.from_date.sub(df.to_date) # also works
df['time_delta'] = (df.from_date - df.to_date)
# create a column with timedelta as total hours, as a float type
df['tot_hour_diff'] = (df.from_date - df.to_date) / pd.Timedelta(hours=1)
# create a colume with timedelta as total minutes, as a float type
df['tot_mins_diff'] = (df.from_date - df.to_date) / pd.Timedelta(minutes=1)
# display(df)
to_date from_date time_delta tot_hour_diff tot_mins_diff
0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 2 days 10:38:09.820000 58.636061 3518.163667
1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 0 days 03:41:04.300000 3.684528 221.071667
2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 0 days 08:42:53.760000 8.714933 522.896000
.total_seconds()
was added and merged when the core developer was on vacation, and would not have been approved.
.total_xx
methods.# convert the entire timedelta to seconds
# this is the same as td / timedelta(seconds=1)
(df.from_date - df.to_date).dt.total_seconds()
[out]:
0 211089.82
1 13264.30
2 31373.76
dtype: float64
# get the number of days
(df.from_date - df.to_date).dt.days
[out]:
0 2
1 0
2 0
dtype: int64
# get the seconds for hours + minutes + seconds, but not days
# note the difference from total_seconds
(df.from_date - df.to_date).dt.seconds
[out]:
0 38289
1 13264
2 31373
dtype: int64
dateutil
maintainer:
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
(df.from_date - df.to_date).dt.total_seconds() / 3600
dateutil
module provides powerful extensions to the standard datetime
module.%%timeit
testimport pandas as pd
# dataframe with 2M rows
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000')], 'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000')]}
df = pd.DataFrame(data)
df = pd.concat([df] * 1000000).reset_index(drop=True)
%%timeit
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
[out]:
43.1 ms ± 1.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
(df.from_date - df.to_date).astype('timedelta64[h]')
[out]:
59.8 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
When working with bootsrap usually face three main problems:
To solve first two problems download this small plugin https://github.com/codekipple/conformity
The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns
<style>
[class*=col-] {position: relative}
.row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
.row-centered {text-align:center}
.row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top}
</style>
<script src="assets/conformity/conformity.js"></script>
<script>
$(document).ready(function () {
$('.row-conformity > [class*=col-]').conformity();
$(window).on('resize', function() {
$('.row-conformity > [class*=col-]').conformity();
});
});
</script>
<div class="row row-conformity">
<div class="col-sm-3">
I<br>create<br>highest<br>column
</div>
<div class="col-sm-3">
<div class="to-bottom">
I am on the bottom
</div>
</div>
</div>
<div class="row row-conformity">
<div class="col-sm-4">We all have equal height</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
</div>
<div class="row row-centered">
<div class="col-sm-3">...</div>
<div class="col-sm-4">...</div>
</div>
<div class="row row-conformity row-centered">
...
</div>
While the above answers are probably best for this situation, if you just want to do a one-off and don't want to bother with modifying other files, you can in-line the CSS.
<p style="margin-bottom:3cm;">This is the first question?</p>
I've been coding for about 2 weeks and created a simple logic to validate an integer has been accepted.
Console.WriteLine("How many numbers do you want to enter?"); // request a number
string input = Console.ReadLine(); // set the input as a string variable
int numberTotal; // declare an int variable
if (!int.TryParse(input, out numberTotal)) // process if input was an invalid number
{
while (numberTotal < 1) // numberTotal is set to 0 by default if no number is entered
{
Console.WriteLine(input + " is an invalid number."); // error message
int.TryParse(Console.ReadLine(), out numberTotal); // allows the user to input another value
}
} // this loop will repeat until numberTotal has an int set to 1 or above
you could also use the above in a FOR loop if you prefer by not declaring an action as the third parameter of the loop, such as
Console.WriteLine("How many numbers do you want to enter?");
string input2 = Console.ReadLine();
if (!int.TryParse(input2, out numberTotal2))
{
for (int numberTotal2 = 0; numberTotal2 < 1;)
{
Console.WriteLine(input2 + " is an invalid number.");
int.TryParse(Console.ReadLine(), out numberTotal2);
}
}
if you don't want a loop, simply remove the entire loop brace
In an Ionic 4 capacitor project, when I packaged and deployed to android phone for testing I got this error. Resolved by re-installing capacitor and updating android platform.
npm run build --prod --release
npx cap copy
npm install --save @capacitor/core @capacitor/cli
npx cap init
npx cap update android
npx cap open android
You can validate a TypeScript type at runtime using ts-validate-type, like so (does require a Babel plugin though):
const user = validateType<{ name: string }>(data);
For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 Now Just go Project under Project settings and select the project SDK.
You need to run
git fetch
To get all changes and then you will not receive message with "your branch is ahead".
This is my solution. you can download demo on my github. https://github.com/krossford/KrossLib/tree/master/android-project
This screenshot was a demo that maxLines = 4
, I think it works well.
package com.krosshuang.krosslib.lib.view;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.TextView;
import java.util.ArrayList;
/*
?????
How to use it?
> 1.?xml??java???????
> 1.use it like other views on xml and java code.
> 2.[??] setMaxLines ?????xml?? "android:maxLines" ??
> 2.[must] call the setMaxLines method to instead of the xml property android:maxLines.
> 3.[??] ???? setMultilineEllipsizeMode() ??,???????
> 3.[option] you can invoke setMultilineEllipsizeMode method, but I have not implement it.
*/
/**
* android???TextView???ellipsize?????
* Created by krosshuang on 2015/12/17.
*/
public class EllipsizeEndTextView extends TextView {
private static final String LOG_TAG = "EllipsizeTextView";
/** ???????? */
//TODO ??????
public static final int MODE_EACH_LINE = 1;
/** ????????? */
public static final int MODE_LAST_LINE = 2;
private static final String ELLIPSIZE = "...";
private ArrayList<String> mTextLines = new ArrayList<String>();
private CharSequence mSrcText = null;
private int mMultilineEllipsizeMode = MODE_LAST_LINE;
private int mMaxLines = 1;
private boolean mNeedIgnoreTextChangeAndSelfInvoke = false;
public EllipsizeEndTextView(Context context) {
super(context);
}
public EllipsizeEndTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EllipsizeEndTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
if (!mNeedIgnoreTextChangeAndSelfInvoke) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
mSrcText = text;
}
}
@Override
public void setMaxLines(int maxlines) {
super.setMaxLines(maxlines);
mMaxLines = maxlines;
}
public int getSupportedMaxLines() {
return mMaxLines;
}
@Override
protected void onDraw(Canvas canvas) {
setVisibleText();
super.onDraw(canvas);
mNeedIgnoreTextChangeAndSelfInvoke = false;
}
private void setVisibleText() {
if (mSrcText == null) {
return;
}
//??????width get available width
final int aw = getWidth() - getPaddingLeft() - getPaddingRight();
String srcText = mSrcText.toString();
//???????????????????????????
String[] lines = srcText.split("\n");
//Log.i(LOG_TAG, "?????: " + lines.length + " ? " + Arrays.toString(lines));
int maxLines = getSupportedMaxLines();
//????????????list
mTextLines.clear();
for (int i = 0; i < lines.length; i++) {
mTextLines.add(lines[i]);
}
switch (mMultilineEllipsizeMode) {
case MODE_EACH_LINE:
break;
default:
case MODE_LAST_LINE:
//????
String eachLine = null;
for (int i = 0; i < mTextLines.size() && i < maxLines - 1; i++) {
eachLine = mTextLines.get(i);
if (getPaint().measureText(eachLine, 0, eachLine.length()) > aw) {
//?????????
boolean isOut = true;
int end = eachLine.length() - 1;
while (isOut) {
if (getPaint().measureText(eachLine.substring(0, end), 0, end) > aw) {
end--;
} else {
isOut = false;
}
}
mTextLines.set(i, eachLine.substring(0, end)); //??????????
mTextLines.add(i + 1, eachLine.substring(end, eachLine.length())); //????????,?????,????????????????,???????
}
}
//??????,??????????????
break;
}
//?? maxLines ? ?????,?????????
int resultSize = Math.min(maxLines, mTextLines.size());
//????????
String lastLine = mTextLines.get(resultSize - 1);
//????????????...
//1.??????????,???????,?????????...
//2.????????,?????????,????????????,????...
if (getPaint().measureText(lastLine, 0, lastLine.length()) > aw || resultSize < mTextLines.size()) {
boolean isOut = true;
int end = lastLine.length();
while (isOut) {
if (getPaint().measureText(lastLine.substring(0, end) + ELLIPSIZE, 0, end + 3) > aw) {
end--;
} else {
isOut = false;
}
}
mTextLines.set(resultSize - 1, lastLine.substring(0, end) + ELLIPSIZE);
}
//??????
StringBuilder sb = new StringBuilder();
for (int i = 0; i < resultSize ; i++) {
sb.append(mTextLines.get(i));
if (i != resultSize - 1) {
sb.append('\n');
}
}
//????,set
if (sb.toString().equals(getText())) {
return;
} else {
mNeedIgnoreTextChangeAndSelfInvoke = true;
setText(sb.toString());
}
}
/**
* ??ellipsize mode,?????
* @deprecated
* */
public void setMultilineEllipsizeMode(int mode) {
mMultilineEllipsizeMode = mode;
}
}
Class re-declaration will be the problem. check duplicate class and build.
It is known HTTP headers problem with Internet Explorer. Try to edit your server's .htaccess
file (if you use Apache) and include the following rules:
# IE: force download of .xxx files
AddType application/octect-stream .xxx
<Files *.xxx>
ForceType application/octet-stream
Header Set Content-Disposition attachment
</Files>
You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2())
.
SELECT b FROM foo;
-- (BLOB)
SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000
This is handy because you this is the same format used for inserting into BLOB columns:
CREATE GLOBAL TEMPORARY TABLE foo (
b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');
DESC foo;
-- Name Null Type
-- ---- ---- ----
-- B BLOB
However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR
for a more complicated approach that will allow you to see substrings of the BLOB.
IF EXISTS()
is semantically incorrect. EXISTS
condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:
declare
l_exst number(1);
begin
select case
when exists(select ce.s_regno
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1
)
then 1
else 0
end into l_exst
from dual;
if l_exst = 1
then
DBMS_OUTPUT.put_line('YES YOU CAN');
else
DBMS_OUTPUT.put_line('YOU CANNOT');
end if;
end;
Or you can simply use count
function do determine the number of rows returned by the query, and rownum=1
predicate - you only need to know if a record exists:
declare
l_exst number;
begin
select count(*)
into l_exst
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1;
if l_exst = 0
then
DBMS_OUTPUT.put_line('YOU CANNOT');
else
DBMS_OUTPUT.put_line('YES YOU CAN');
end if;
end;
You can solve this with one of the following solutions:
As of Android studio 3.0, it becomes much easier as it now shows a more helpful hint, so we only need to follow this hint.
for example:
All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.0.2, 26.1.0. Examples include com.android.support:animated-vector-drawable:27.0.2 and com.android.support:customtabs:26.1.0
there are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion.)
Solution:
Add explicitly the library with the old version but with a new version number.
in my case com.android.support:customtabs:26.1.0
so I need to add:
implementation "com.android.support:customtabs:27.0.2"
ie: Take the library from the second item, and implement it with the version number from the first.
Note: don't forget to press sync now so gradle can rebuild the dependency graph and see if there are any more conflicts.
Explanation:
you may be confused by the error message as don't use customtabs
so how I have a conflict!!
well.. you didn't use it directly but one of your libraries uses an old version of customtabs
internally, so you need to ask for it directly.
if you curious to know which of your libraries is responsible for the old version and maybe ask the author to update his lib, Run a Gradle dependency report, see the old answer to know how.
Note this
inspired by CommonsWare answer:
Run a Gradle dependency report to see what your full tree of dependencies is.
From there, you will see which one of your libraries are asking for a different version of the Android Support libraries. For whatever it is asking for, you can ask for it directly with the 25.2.0 version or use Gradle's other conflict resolution approaches to get the same versions.
As of gradle plugin version: 3.0 compile
has been replaced by implementation
or api
see this answer for the difference.
hence use instead:
./gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath
or for windows cmd:
gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath
and search for the conflicted version.
For me, the error disappeared after removing com.google.android.gms:play-services:10.2.0
And only include com.google.android.gms:play-services-location:10.2.0
and com.google.android.gms:play-services-maps:10.2.0
as they are the only two play services that I use.
I think the gms:play-services
depend on some old components of the support library, so we need to add them explicitly ourselves.
for AS 3.0 an older.
Run:
./gradlew -q dependencies <module-name>:dependencies --configuration implementation
Example:
./gradlew -q dependencies app:dependencies --configuration implementation
if someone knows a better way in the new gradle plugin please let me know.
If your array is static or global it's initialized to zero before main() starts. That would be the most efficient option.
A simple solution would be something like this
$( "form" ).on( "submit", function() {
var has_empty = false;
$(this).find( 'input[type!="hidden"]' ).each(function () {
if ( ! $(this).val() ) { has_empty = true; return false; }
});
if ( has_empty ) { return false; }
});
Note: The jQuery.on()
method is only available in jQuery version 1.7+, but it is now the preferred method of attaching event handlers.
This code loops through all of the inputs in the form and prevents form submission by returning false if any of them have no value. Note that it doesn't display any kind of message to the user about why the form failed to submit (I would strongly recommend adding one).
Or, you could look at the jQuery validate plugin. It does this and a lot more.
NB: This type of technique should always be used in conjunction with server side validation.
If you have a table called memos that has two columns id
and text
you should be able to do like this:
INSERT INTO memos(id,text)
SELECT 5, 'text to insert'
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');
If a record already contains a row where text
is equal to 'text to insert' and id
is equal to 5, then the insert operation will be ignored.
I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.
I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer
below.
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
You can use GROUP_CONCAT to perform that, e.g. something like
SELECT p.id, p.name, GROUP_CONCAT(s.name) AS site_list
FROM sites s
INNER JOIN publications p ON(s.id = p.site_id)
GROUP BY p.id, p.name;
The only reason I can think of is you are adding it as string 'now()'
, not function call now()
.
Or whatever else typo.
SELECT NOW();
to see if it returns correct value?
You can use Matrix to resize your camera image ....
BitmapFactory.Options options=new BitmapFactory.Options();
InputStream is = getContentResolver().openInputStream(currImageURI);
bm = BitmapFactory.decodeStream(is,null,options);
int Height = bm.getHeight();
int Width = bm.getWidth();
int newHeight = 300;
int newWidth = 300;
float scaleWidth = ((float) newWidth) / Width;
float scaleHeight = ((float) newHeight) / Height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0,Width, Height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
What about
this.f = window["instance:" + a] = function(){};
The only drawback is that the function in its toSource method wouldn't indicate a name. That's usually only a problem for debuggers.
Enumerable.Repeat(true, 1000000).ToArray();
Use This code to find exact X and Y cordinates :
int[] array = new int[2];
ViewForWhichLocationIsToBeFound.getLocationOnScreen(array);
if (AppConstants.DEBUG)
Log.d(AppConstants.TAG, "array X = " + array[0] + ", Y = " + array[1]);
ViewWhichToBeMovedOnFoundLocation.setTranslationX(array[0] + 21);
ViewWhichToBeMovedOnFoundLocation.setTranslationY(array[1] - 165);
I have added/subtracted some values to adjust my view. Please do these lines only after whole view has been inflated.
You could just do ...
(.*?)\.txt
You could use this for all devices,
$(document).on('scroll', function() {
if( $(this).scrollTop() >= $('#target_element').position().top ){
do_something();
}
});
Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.
Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.
See http://docs.python.org/library/filecmp.html e.g.
>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False
Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte
Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.
import random
import string
import hashlib
import time
def getRandText(N):
return "".join([random.choice(string.printable) for i in xrange(N)])
N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)
def cmpHash(text1, text2):
hash1 = hashlib.md5()
hash1.update(text1)
hash1 = hash1.hexdigest()
hash2 = hashlib.md5()
hash2.update(text2)
hash2 = hash2.hexdigest()
return hash1 == hash2
def cmpByteByByte(text1, text2):
return text1 == text2
for cmpFunc in (cmpHash, cmpByteByByte):
st = time.time()
for i in range(10):
cmpFunc(randText1, randText2)
print cmpFunc.func_name,time.time()-st
and the output is
cmpHash 0.234999895096
cmpByteByByte 0.0
For example, your remote host is example.com and remote login name is user1:
scp [email protected]:/path/to/file /path/to/store/file
This one works for me:
<?php
if(isset($_GET['action']))
{
//your code
echo 'Welcome';
}
?>
<form id="frm" method="post" action="?action" >
<input type="submit" value="Submit" id="submit" />
</form>
This link can be helpful:
you can use this in your activity tag in AndroidManifest.xml to hide label
android:label=""
Here another cleaner solution by using docker-compose
and a js
script.
This example assumes that both files (docker-compose.yml and mongo-init.js) lay in the same folder.
version: '3.7'
services:
mongodb:
image: mongo:latest
container_name: mongodb
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: <admin-user>
MONGO_INITDB_ROOT_PASSWORD: <admin-password>
MONGO_INITDB_DATABASE: <database to create>
ports:
- 27017:27017
volumes:
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
db.createUser(
{
user: "<user for database which shall be created>",
pwd: "<password of user>",
roles: [
{
role: "readWrite",
db: "<database to create>"
}
]
}
);
Then simply start the service by running the following docker-compose command
docker-compose up --build -d mongodb
Note: The code in the docker-entrypoint-init.d folder is only executed if the database has never been initialized before.
The default behavior of os.walk()
is to walk from root to leaf. Set topdown=False
in os.walk()
to walk from leaf to root.
I use a generic query I call "dump" (why? I don't know) that looks like this:
SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |
spool &1..txt
@@&1
spool off
exit
I then call SQL*Plus passing the actual SQL script I want to run as an argument:
sqlplus -S user/password@database @dump.sql my_real_query.sql
The result is written to a file
my_real_query.sql.txt
.
Or you can use this:
^(?:part[12]|(part)1,\12)$
and here the fork of the toolkit wich contains the port to 4.O,
https://github.com/jogibear9988/wpftoolkit
it's worked very well to me .
str = "aaaaabbbb"
newstr = str[-4:]
require 'json/ext' # to use the C based extension instead of json/pure
puts {hash: 123}.to_json
Adding to @Pierre
Using unittest
directory structure like this:
new_project
+-- antigravity
¦ +-- __init__.py # make it a package
¦ +-- antigravity.py
+-- test
+-- __init__.py # also make test a package
+-- test_antigravity.py
To run the test module test_antigravity.py
:
$ cd new_project
$ python -m unittest test.test_antigravity
Or a single TestCase
$ python -m unittest test.test_antigravity.GravityTestCase
Mandatory don't forget the __init__.py
even if empty otherwise will not work.
less will look in its environment to see if there is a variable named LESS
You can set LESS in one of your ~/.profile (.bash_rc, etc, etc) and then anytime you run less
from the comand line, it will find the LESS.
Try adding this
export LESS="-CQaix4"
This is the setup I use, there are some behaviors embedded in that may confuse you, so you can find out about what all of these mean from the help function in less
, just tap the 'h' key and nose around, or run less --help
.
Edit:
I looked at the help, and noticed there is also an -r
option
-r -R .... --raw-control-chars --RAW-CONTROL-CHARS
Output "raw" control characters.
I agree that cat
may be the most exact match to your stated needs.
cat -vet file | less
Will add '$' at end of each line and convert tab char to visual '^I'.
cat --help
(edited)
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-t equivalent to -vT
-T, --show-tabs display TAB characters as ^I
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
I hope this helps.
I have found this works for all my use cases:
const round = (value, decimalPlaces = 0) => {
const multiplier = Math.pow(10, decimalPlaces);
return Math.round(value * multiplier + Number.EPSILON) / multiplier;
};
Keep in mind that is ES6. An ES5 equiv. would be very easy to code though so I'm not gonna add it.
This could be the easiest in my opinion:
SELECT * FROM `table` WHERE `timestamp` like concat(CURDATE(),'%');
For me, simply adding the current directory worked.
Using the following structure:
+-- myproject
+-- a.py
+-- b.py
a.py:
from b import some_object
# returns ModuleNotFound error
from myproject.b import some_object
# works
You can use python-textops3 :
from textops import *
print('\n'.join(cat(f) | grep(search_term)))
with python-textops3 you can use unix-like commands with pipes
Egypt (free software)
KcacheGrind (GPL)
Graphviz (CPL)
CodeViz (GPL)
What about something like this:
First resample the data frame into 1D intervals. This takes the mean of the values for all duplicate days. Use the fill_method
option to fill in missing date values. Next, pass the resampled frame into pd.rolling_mean
with a window of 3 and min_periods=1 :
pd.rolling_mean(df.resample("1D", fill_method="ffill"), window=3, min_periods=1)
favorable unfavorable other
enddate
2012-10-25 0.495000 0.485000 0.025000
2012-10-26 0.527500 0.442500 0.032500
2012-10-27 0.521667 0.451667 0.028333
2012-10-28 0.515833 0.450000 0.035833
2012-10-29 0.488333 0.476667 0.038333
2012-10-30 0.495000 0.470000 0.038333
2012-10-31 0.512500 0.460000 0.029167
2012-11-01 0.516667 0.456667 0.026667
2012-11-02 0.503333 0.463333 0.033333
2012-11-03 0.490000 0.463333 0.046667
2012-11-04 0.494000 0.456000 0.043333
2012-11-05 0.500667 0.452667 0.036667
2012-11-06 0.507333 0.456000 0.023333
2012-11-07 0.510000 0.443333 0.013333
UPDATE: As Ben points out in the comments, with pandas 0.18.0 the syntax has changed. With the new syntax this would be:
df.resample("1d").sum().fillna(0).rolling(window=3, min_periods=1).mean()
Put the UNIQUE declaration within the column definition section; working example:
CREATE TABLE a (
i INT,
j INT,
UNIQUE(i, j) ON CONFLICT REPLACE
);
If you want to download SVN repository online (e.g. Google Code) without installing anything, you can use wget:
wget -m -np http://myproject.googlecode.com/svn/myproject/trunk/
If authorization is required, you can use the --user
and --ask-password
flags, which will prompt you for your password:
wget --user=yourusername --ask-password -m -np http://myproject.googlecode.com/svn/myproject/trunk/
Explaining what the parameter does:
-m, --mirror:
Turn on options suitable for mirroring. This option turns on recursion and time-stamping, sets infinite recursion depth and keeps FTP directory listings. It is currently equivalent to
-r -N -l inf --no-remove-listing
.
-np, --no-parent:
Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.
Your Maven is reading Java version as 1.6.0_65, Where as the pom.xml says the version is 1.7.
Try installing the required verison.
If already installed check your $JAVA_HOME environment variable, it should contain the path of Java JDK 7. If you dont find it, fix your environment variable.
also remove the lines
<fork>true</fork>
<executable>${JAVA_1_7_HOME}/bin/javac</executable>
from the pom.xml
You can't alter the existing columns for identity.
You have 2 options,
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL
IDENTITY(1, 1),
Name varchar(50) NULL
)
ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS ( SELECT *
FROM dbo.Names )
INSERT INTO dbo.Tmp_Names ( Id, Name )
SELECT Id,
Name
FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
DROP TABLE dbo.Names
go
Exec sp_rename 'Tmp_Names', 'Names'
Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.
Alter Table Names
Add Id_new Int Identity(1, 1)
Go
Alter Table Names Drop Column ID
Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'
See the following Microsoft SQL Server Forum post for more details:
Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.
to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx
The Date
constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.
Date.getDate()
returns the day index for the current date object. In your example, the day is 30
. The final expression is 31
, therefore it's returning 31 milliseconds after December 31st, 1969.
A simple solution using your existing approach is to use Date.getTime()
instead. Then, add a days worth of milliseconds instead of 1
.
For example,
var dateString = 'Mon Jun 30 2014 00:00:00';
var startDate = new Date(dateString);
// seconds * minutes * hours * milliseconds = 1 day
var day = 60 * 60 * 24 * 1000;
var endDate = new Date(startDate.getTime() + day);
Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.
A trick I've used is
>>> ("something" in {"a string":"", "somthing":"", "another string":""})
false
>>> ("something" in {"a string":"", "something":"", "another string":""})
true
You could do something like
>>> a = ["a string", "something", "another string"];
>>> b = {};
>>> for(var i=0; i<a.length;i++){b[a[i]]="";} /* Transform the array in a dict */
>>> ("something" in b)
true
names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
Try:
names = {'John','Joe','Steve'}
for i = 1,3 do
print(names[i])
end
| Basis | Linear | Logistic |
|-----------------------------------------------------------------|--------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| Basic | The data is modelled using a straight line. | The probability of some obtained event is represented as a linear function of a combination of predictor variables. |
| Linear relationship between dependent and independent variables | Is required | Not required |
| The independent variable | Could be correlated with each other. (Specially in multiple linear regression) | Should not be correlated with each other (no multicollinearity exist). |
The code below can be used for taking a photo and for picking a photo. Just show a dialog with two options and upon selection, use the appropriate code.
To take picture from camera:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code (called requestCode)
To pick photo from gallery:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
onActivityResult
code:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageview.setImageURI(selectedImage);
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageview.setImageURI(selectedImage);
}
break;
}
}
Finally add this permission in the manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Could you not have simply added:
align-items:center;
to a new class in your row div. Essentially:
<div class="row align_center">
.align_center { align-items:center; }
The Java Date and Calendar classes are considered by many to be poorly designed. You should take a look at Joda Time, a library commonly used in lieu of Java's built-in date libraries.
The equivalent of DateTime.Now
in Joda Time is:
DateTime dt = new DateTime();
Update
As noted in the comments, the latest versions of Joda Time have a DateTime.now()
method, so:
DateTime dt = DateTime.now();
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
With numpy 1.3 or svn you can do this
In [1]: a = arange(10000.).reshape(100,100)
In [3]: isnan(a.max())
Out[3]: False
In [4]: a[50,50] = nan
In [5]: isnan(a.max())
Out[5]: True
In [6]: timeit isnan(a.max())
10000 loops, best of 3: 66.3 µs per loop
The treatment of nans in comparisons was not consistent in earlier versions.
You can clone the module directly in to your local project.
Start terminal. cd in to your project and then:
npm install https://github.com/repo/npm_module.git --save
Similar to @joe_deniable 's answer the thing I found with my own projects was that gradle would output that kind of error when there was a misconfiguration of my system.
I discovered that by running gradlew installDebug or similar command from the terminal I got better output as to what the real problem was.
e.g. initially it turns out my JAVA_HOME was not setup correctly. Then I discovered it encountered errors because I didn't have a package space setup correctly. Etc.
As I don't have access to postgres account (so can't run SHOW config_file
) and my postgres is installed on Windows, none of the answers helped me, so I'm sharing my file location for future Windows readers:
C:\Program Files\PostgreSQL\9.5\data
For the ones developing in Kotlin, there is a sweet method provided by the Anko library that makes the process of displaying a ProgressDialog
a breeze!
Based on that link:
val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
dialog.show()
//....
dialog.dismiss()
This will show a Progress Dialog with the progress % displayed (for which you have to pass the init
parameter also to calculate the progress).
There is also the indeterminateProgressDialog()
method, which provides the Spinning Circle animation indefinitely until dismissed:
indeterminateProgressDialog("Loading...").show()
Shout out to this blog which led me to this solution.
Are you trying to submit a form?
Listen to the submit
event instead.
This will handle click
and enter
.
If you must use enter key...
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
Once after we build the jar will have the resource files under BOOT-INF/classes or target/classes folder, which is in classpath, use the below method and pass the file under the src/main/resources as method call getAbsolutePath("certs/uat_staging_private.ppk"), even we can place this method in Utility class and the calling Thread instance will be taken to load the ClassLoader to get the resource from class path.
public String getAbsolutePath(String fileName) throws IOException {
return Thread.currentThread().getContextClassLoader().getResource(fileName).getFile();
}
we can add the below tag to tag in pom.xml to include these resource files to build target/classes folder
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.ppk</include>
</includes>
</resource>
</resources>
This worked for me;
1- git init
2- git add .
3- git commit -m "Add all my files"
4- git remote add origin https://github.com/USER_NAME/FOLDER_NAME
5- git pull origin master --allow-unrelated-histories
6- git push origin master
There is no direct HTML solution for the task for now. Even HTML Imports (which is permanently in draft) will not do the thing, because Import != Include and some JS magic will be required anyway.
I recently wrote a VanillaJS script that is just for inclusion HTML into HTML, without any complications.
Just place in your a.html
<link data-wi-src="b.html" />
<!-- ... and somewhere below is ref to the script ... -->
<script src="wm-html-include.js"> </script>
It is open-source
and may give an idea (I hope)
Sharing for future readers:
In our case, we needed to add the host
parameter to make it work
mongoimport -h mongodb://someMongoDBhostUrl:somePORTrunningMongoDB/someDB -d someDB -c someCollection -u someUserName -p somePassword --file someCSVFile.csv --type csv --headerline --host=127.0.0.1
Add both a maximum and a minimum value. You can specify the range of allowed values:
<input type="number" min="1" max="999" />
If you just want to check if the file uploaded is an image you can just try to load it into <img>
tag an check for any error callback.
Example:
var input = document.getElementsByTagName('input')[0];
var reader = new FileReader();
reader.onload = function (e) {
imageExists(e.target.result, function(exists){
if (exists) {
// Do something with the image file..
} else {
// different file format
}
});
};
reader.readAsDataURL(input.files[0]);
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
Code:
var select = function(dropdown, selectedValue) {
var options = $(dropdown).find("option");
var matches = $.grep(options,
function(n) { return $(n).text() == selectedValue; });
$(matches).attr("selected", "selected");
};
Example:
select("#dropdown", "B");
git stash drop
takes no parameter - which drops the top stash - or a stash reference which looks like: stash@{n}
which n
nominates which stash to drop. You can't pass a commit id to git stash drop
.
git stash drop # drop top hash, stash@{0}
git stash drop stash@{n} # drop specific stash - see git stash list
Dropping a stash will change the stash@{n}
designations of all stashes further down the stack.
I'm not sure why you think need to drop a stash because if you are using stash create
a stash entry isn't created for your "stash" so there isn't anything to drop.
//BEWARE
//This works ONLY if the server returns 401 first
//The client DOES NOT send credentials on first request
//ONLY after a 401
client.Credentials = new NetworkCredential(userName, passWord); //doesnt work
//So use THIS instead to send credentials RIGHT AWAY
string credentials = Convert.ToBase64String(
Encoding.ASCII.GetBytes(userName + ":" + password));
client.Headers[HttpRequestHeader.Authorization] = string.Format(
"Basic {0}", credentials);
I don't think gcc
has a flag for it, since it's primarily a compiler, but another of the GNU development tools does. objdump
takes a -d
/--disassemble
flag:
$ objdump -d /path/to/binary
The disassembly looks like this:
080483b4 <main>:
80483b4: 8d 4c 24 04 lea 0x4(%esp),%ecx
80483b8: 83 e4 f0 and $0xfffffff0,%esp
80483bb: ff 71 fc pushl -0x4(%ecx)
80483be: 55 push %ebp
80483bf: 89 e5 mov %esp,%ebp
80483c1: 51 push %ecx
80483c2: b8 00 00 00 00 mov $0x0,%eax
80483c7: 59 pop %ecx
80483c8: 5d pop %ebp
80483c9: 8d 61 fc lea -0x4(%ecx),%esp
80483cc: c3 ret
80483cd: 90 nop
80483ce: 90 nop
80483cf: 90 nop
Being impatient, I created a new App Pool with the same settings and used that.
For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You'll immediately see the red circle with a cross in it on the failing line. It's a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.
Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.
Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.
As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.
The kernel might be the operating system or it might be a part of the operating system. In Linux, the kernel is loaded and executed first. Then it starts up other bits of the OS (like init) to make the system useful.
This is especially true in a micro-kernel environment. The kernel has minimal functionality. Everything else, like file systems and TCP/IP, run as a user process.
You can use -[NSDictionary allKeys]
to access all the keys and loop through it.
You likely have the wrong package installed. You want the package produced by Microsoft which implements the System.Data.Common provider model.
Set this to False on your web.config
<compilation debug="false" targetFramework="4.6.1" />
Use this code
TextView textView = new TextView(YourActivity.this);
textView.setGravity(Gravity.CENTER | Gravity.TOP);
textView.setText("some text");
$dbc
is returning false. Your query has an error in it:
SELECT users.*, profile.* --You do not join with profile anywhere.
FROM users
INNER JOIN contact_info
ON contact_info.user_id = users.user_id
WHERE users.user_id=3");
The fix for this in general has been described by Raveren.
Could it work declaring the filter the following way?
app.filter('dateUTC', function ($filter) {
return function (input, format) {
if (!angular.isDefined(format)) {
format = 'dd/MM/yyyy';
}
var date = new Date(input);
return $filter('date')(date.toISOString().slice(0, 23), format);
};
});
I would also suggest deselecting an item after it has been clicked and use the MouseDoubleClick event
private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try {
//Do your stuff here
listBox.SelectedItem = null;
listBox.SelectedIndex = -1;
} catch (Exception ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
<head>
<title>Test</title>
</head>
<body>
<h1>Hi there<span id="username"></span>!</h1>
<script>
let userName = prompt("What is your name?");
document.getElementById('username').innerHTML = userName;
</script>
</body>
If you want today's date without the time, just use Date.today
In case you want to view more: Here's a link for a list of devices (tablet, mobile, watches), including watch
,chromebook
, windows
and mac
. Here you can find the density, dimensions, and etc. Just based it in here, it's a good resource if your using an emulator too.
If you click a specific item, it will show more details in the right side.
Since it's Android
, I will post related to it.
~ It's better if you save a copy of the web. To view it offline.
Since ViewPager is tending to be replaced by ViewPager2 and we will need to migrate to it.
A quick work around using Java would be something like this:
final List<String> colors = new ArrayList<String>(){
{
add("#FF0000");
add("#800000");
add("#FFFF00");
}
};
ViewPager2 viewPager = findViewById(R.id.viewPager);
ViewPagerAdapter adapter = new ViewPagerAdapter(your_data_structure);
viewPager.setAdapter(adapter);
final TabLayout tabs = findViewById(R.id.tabs);
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tab.view.setAlpha((float) 0.5);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.view.setAlpha(1);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
TabLayoutMediator mediator = new TabLayoutMediator(tabs, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab" + position);
/*
* With this feature the TabIndicator color is ignored
* or covered by the new color ex.(if alpha channel is changed the indicator can be seen through)
*/
tab.view.setBackgroundColor(Color.parseColor(colors.get(position))); //You can use your HEX string color
}
});
mediator.attach();
isEmptyOrSpaces(str){
return str === null || str.trim().length>0;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (url.equals("your url")) {
Intent intent = new Intent(view.getContext(), TransferAllDoneActivity.class);
startActivity(intent);
}
}
As the other answers state:
count
will perform an SQL COUNT
querylength
will calculate the length of the resulting arraysize
will try to pick the most appropriate of the two to avoid excessive queriesBut there is one more thing. We noticed a case where size
acts differently to count
/length
altogether, and I thought I'd share it since it is rare enough to be overlooked.
If you use a :counter_cache
on a has_many
association, size
will use the cached count directly, and not make an extra query at all.
class Image < ActiveRecord::Base
belongs_to :product, counter_cache: true
end
class Product < ActiveRecord::Base
has_many :images
end
> product = Product.first # query, load product into memory
> product.images.size # no query, reads the :images_count column
> product.images.count # query, SQL COUNT
> product.images.length # query, loads images into memory
This behaviour is documented in the Rails Guides, but I either missed it the first time or forgot about it.
isset() only checks if a variable is set.. Has got nothing to do with size or what the array contains
I want to use R rather than pre-processing the data as it makes it easier when the data are revised. Following Shane's suggestion of using gsub
, I think this is about as neat as I can do:
x <- read.csv("file.csv",header=TRUE,colClasses="character")
col2cvt <- 15:41
x[,col2cvt] <- lapply(x[,col2cvt],function(x){as.numeric(gsub(",", "", x))})
$ lsof | tree MyFold
As shown in the image attached:
This is not perfect methods. You have to implement same way which is display here.
You can also call the image under the folder through the code you can use
Resources res = getResources();
Drawable shape = res. getDrawable(R.drawable.gradient_box);
TextView tv = (TextView)findViewByID(R.id.textview);
tv.setBackground(shape);
Pure/vanilla JS solution (working example here)
// All elements with data-company="Microsoft" below "Companies"
let a = document.querySelectorAll("[data-group='Companies'] [data-company='Microsoft']");
// All elements with data-company!="Microsoft" below "Companies"
let b = document.querySelectorAll("[data-group='Companies'] :not([data-company='Microsoft'])");
In querySelectorAll you must use valid CSS selector (currently Level3)
SPEED TEST (2018.06.29) for jQuery and Pure JS: test was performed on MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit). Below screenshot shows results for fastest browser (Safari):
PureJS was faster than jQuery about 12% on Chrome, 21% on Firefox and 25% on Safari. Interestingly speed for Chrome was 18.9M operation per second, Firefox 26M, Safari 160.9M (!).
So winner is PureJS and fastest browser is Safari (more than 8x faster than Chrome!)
Here you can perform test on your machine: https://jsperf.com/js-selectors-x
You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.
A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.
Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1
Use the TextInputLayout
provided by the Material Components Library:
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Label">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
I was just searching for something similar:
I want to sum every odd row column.
SUMIF
has TWO possible ranges, the range to sum from, and a range to consider criteria in.
SUMIF(B1:B1000,1,A1:A1000)
This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.
To get "=1" to return in the B range I put this in B:
=MOD(ROWNUM(B1),2)
Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.
Easier than ARRAY stuff and hides the back-end of loops!
Building off of Fabio's answer, I created two functions that will probably be useful for anyone stumbling upon this question. With these two functions, you can call insertParam()
with a key and value as an argument. It will either add the URL parameter or, if a query param already exists with the same key, it will change that parameter to the new value:
//function to remove query params from a URL
function removeURLParameter(url, parameter) {
//better to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
return url;
} else {
return url;
}
}
//function to add/update query params
function insertParam(key, value) {
if (history.pushState) {
// var newurl = window.location.protocol + "//" + window.location.host + search.pathname + '?myNewUrlQuery=1';
var currentUrlWithOutHash = window.location.origin + window.location.pathname + window.location.search;
var hash = window.location.hash
//remove any param for the same key
var currentUrlWithOutHash = removeURLParameter(currentUrlWithOutHash, key);
//figure out if we need to add the param with a ? or a &
var queryStart;
if(currentUrlWithOutHash.indexOf('?') !== -1){
queryStart = '&';
} else {
queryStart = '?';
}
var newurl = currentUrlWithOutHash + queryStart + key + '=' + value + hash
window.history.pushState({path:newurl},'',newurl);
}
}
Create a function with return format yyyy-mm-hh hh:mi:ss.sss
create function fn_retornaFecha (@i_fecha datetime)
returns varchar(23)
as
begin
declare
@w_fecha varchar(23),
@w_anio varchar(4),
@w_mes varchar(2),
@w_dia varchar(2),
@w_hh varchar(2),
@w_nn varchar(2),
@w_ss varchar(2),
@w_sss varchar(3)
select @w_fecha = null
if ltrim(rtrim(@i_fecha)) is not null
begin
select
@w_anio = replicate('0',4-char_length( convert(varchar(4), year(@i_fecha)) )) + convert(varchar(4), year(@i_fecha)),
@w_mes = replicate('0',2-char_length( convert(varchar(2),month(@i_fecha)) )) + convert(varchar(2),month(@i_fecha)),
@w_dia = replicate('0',2-char_length( convert(varchar(2), day(@i_fecha)) )) + convert(varchar(2), day(@i_fecha)) ,
@w_hh = replicate('0',2-char_length( convert(varchar(2),datepart( hh, @i_fecha ) ) )) + convert(varchar(2),datepart( hh, @i_fecha ) ),
@w_nn = replicate('0',2-char_length( convert(varchar(2),datepart( mi, @i_fecha ) ) )) + convert(varchar(2),datepart( mi, @i_fecha ) ),
@w_ss = replicate('0',2-char_length( convert(varchar(2),datepart( ss, @i_fecha ) ) )) + convert(varchar(2),datepart( ss, @i_fecha ) ),
@w_sss = convert(varchar(3),datepart( ms, @i_fecha ) ) + replicate('0',3-DATALENGTH( convert(varchar(3),datepart( ms, @i_fecha ) ) ))
select @w_fecha = @w_anio + '-' + @w_mes + '-' + @w_dia + ' ' + @w_hh + ':' + @w_nn + ':' + @w_ss + '.' + @w_sss
end
return @w_fecha
end
go
Example
select fn_retornaFecha(getdate())
and the result is: 2016-12-21 10:12:50.123
If you're doing shell commands and you (like I) have a fetish for pipelining, this one is good:
seq 1 $END | xargs -I {} echo {}
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.
Yes, with a lexical cast. Use a stringstream and the << operator, or use Boost, they've already implemented it.
Your own version could look like:
template<typename to, typename from>to lexical_cast(from const &x) {
std::stringstream os;
to ret;
os << x;
os >> ret;
return ret;
}
You can use a generator expression:
>>> dicts = [
... { "name": "Tom", "age": 10 },
... { "name": "Mark", "age": 5 },
... { "name": "Pam", "age": 7 },
... { "name": "Dick", "age": 12 }
... ]
>>> next(item for item in dicts if item["name"] == "Pam")
{'age': 7, 'name': 'Pam'}
If you need to handle the item not being there, then you can do what user Matt suggested in his comment and provide a default using a slightly different API:
next((item for item in dicts if item["name"] == "Pam"), None)
And to find the index of the item, rather than the item itself, you can enumerate() the list:
next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None)
refinement on moylop260's answer:
import serial.tools.list_ports
comlist = serial.tools.list_ports.comports()
connected = []
for element in comlist:
connected.append(element.device)
print("Connected COM ports: " + str(connected))
This lists the ports that exist in hardware, including ones that are in use. A whole lot more information exists in the list, per the pyserial tools documentation
How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.
If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2);
into your callback function.
This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.
You can get to SIZES
by means of self.SIZES
(in an instance method) or cls.SIZES
(in a class method).
In any case, you will have to be explicit about where to find SIZES
. An alternative is to put SIZES
in the module containing the classes, but then you need to define all classes in a single module.
You may not place the deprecated non-block-scoped stage
(as in the original question) inside parallel
.
As of JENKINS-26107, stage
takes a block argument. You may put parallel
inside stage
or stage
inside parallel
or stage
inside stage
etc. However visualizations of the build are not guaranteed to support all nestings; in particular
stage
nesting.parallel
branches inside a top-level stage, but currently no more.JENKINS-27394, if implemented, would display arbitrarily nested stage
s.
I was having this error and a was nuts
my code was
$aux_users='';
foreach ($usuarios['a'] as $iterador) {
#code
if ( is_numeric($consultores[0]->ganancia) ) {
$aux_users[$iterador]['ganancia']=round($consultores[0]->ganancia,2);
}
}
after changing $aux_users='';
to $aux_users=array();
it happen to my in php 7.2 (in production server!) but was working on php 5.6 and php 7.0.30 so be aware! and thanks to Young Michael, i hope it helps you too!
First of all,
pip install --trusted-host pypi.python.org <package name>
did not work for me. I kept getting the CERTIFICATE_VERIFY_FAILED error. However, I noticed in the error messages that they referenced the 'pypi.org' site. So, I used this as the trusted host name instead of pypi.python.org. That almost got me there; the load was still failing with CERTIFICATE_VERIFY_FAILED, but at a later point. Finding the reference to the website that was failing, I included it as a trusted host. What eventually worked for me was:
pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org <package name>
Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.
import pickle
class MyUser(object):
def __init__(self,name):
self.name = name
user = MyUser('Peter')
print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'
with open(filename,'wb') as file_object:
file_object.write(serialized)
with open(filename,'rb') as file_object:
raw_data = file_object.read()
deserialized = pickle.loads(raw_data)
print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
Only While Loop is officially supported by SQL server. Already there is answer for DO while loop. I am detailing answer on ways to achieve different types of loops in SQL server.
If you know, you need to complete first iteration of loop anyway, then you can try DO..WHILE or REPEAT..UNTIL version of SQL server.
DECLARE @X INT=1;
WAY: --> Here the DO statement
PRINT @X;
SET @X += 1;
IF @X<=10 GOTO WAY;
DECLARE @X INT = 1;
WAY: -- Here the REPEAT statement
PRINT @X;
SET @X += 1;
IFNOT(@X > 10) GOTO WAY;
DECLARE @cnt INT = 0;
WHILE @cnt < 10
BEGIN
PRINT 'Inside FOR LOOP';
SET @cnt = @cnt + 1;
END;
PRINT 'Done FOR LOOP';
let test = function() {
return "Hello world"
};
exports.test = test;
select *
from user
left join edge
on user.userid = edge.tailuser
and edge.headuser = 5043
This is actually a bit trickier than you'd think. Since a list can actually (with some effort) contain NULL elements, it might not be enough to check is.null(foo$a)
. A more stringent test might be to check that the name is actually defined in the list:
foo <- list(a=42, b=NULL)
foo
is.null(foo[["a"]]) # FALSE
is.null(foo[["b"]]) # TRUE, but the element "exists"...
is.null(foo[["c"]]) # TRUE
"a" %in% names(foo) # TRUE
"b" %in% names(foo) # TRUE
"c" %in% names(foo) # FALSE
...and foo[["a"]]
is safer than foo$a
, since the latter uses partial matching and thus might also match a longer name:
x <- list(abc=4)
x$a # 4, since it partially matches abc
x[["a"]] # NULL, no match
[UPDATE] So, back to the question why exists('foo$a')
doesn't work. The exists
function only checks if a variable exists in an environment, not if parts of a object exist. The string "foo$a"
is interpreted literary: Is there a variable called "foo$a"? ...and the answer is FALSE
...
foo <- list(a=42, b=NULL) # variable "foo" with element "a"
"bar$a" <- 42 # A variable actually called "bar$a"...
ls() # will include "foo" and "bar$a"
exists("foo$a") # FALSE
exists("bar$a") # TRUE
Another option that you can use is:
onclick="if(confirm('Do you have sure ?')){}else{return false;};"
using this function on submit button you will get what you expect.
I know this is an old post but today I was looking for something like this. In the end I wrote the code myself:
private List reverseList(List myList) {
List invertedList = new ArrayList();
for (int i = myList.size() - 1; i >= 0; i--) {
invertedList.add(myList.get(i));
}
return invertedList;
}
Not recommended for long Lists, this is not optimized at all. It's kind of an easy solution for controlled scenarios (the Lists I handle have no more than 100 elements).
Hope it helps somebody.
All member variables have to load into the heap, so they have to be initialized with default values when an instance of class is created.
In case of local variables, they don't get loaded into the heap. They are stored on the stack until they are being used. This is before Java 7, so we need to explicitly initialize them.
SELECT * FROM my_table WHERE my_column = 'my string'
COLLATE Latin1_General_CS_AS
This would make a case sensitive search.
EDIT
As stated in kouton's comment here and tormuto's comment here whosoever faces problem with the below collation
COLLATE Latin1_General_CS_AS
should first check the default collation for their SQL server, their respective database and the column in question; and pass in the default collation with the query expression. List of collations can be found here.
ObservableCollection Caveat
Mentioned above (Said Roohullah Allem)
What makes the ObservableCollection class unique is that this class supports an event named CollectionChanged.
Keep this in mind...If you adding a large number of items to an ObservableCollection
the UI will also update that many times. This can really gum up or freeze your UI.
A work around would be to create a new list, add all the items then set your property to the new list. This hits the UI once. Again...this is for adding a large number of items.
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
There are many tutorials and answers here how to add your script to be included in the page. But what I couldn't find is how to structure that code so it will work properly. This is due the $ being not used in this form of JQuery.
So here is my code and you can use that as a template.
jQuery(document).ready(function( $ ){
$("#btnCalculate").click(function () {
var val1 = $(".visits").val();
var val2 = $(".collection").val();
var val3 = $(".percent").val();
var val4 = $(".expired").val();
var val5 = $(".payer").val();
var val6 = $(".deductible").val();
var result = val1 * (val3 / 100) * 10 * 0.25;
var result2 = val1 * val2 * (val4 / 100) * 0.2;
var result3 = val1 * val2 * (val5 / 100) * 0.2;
var result4 = val1 * val2 * (val6 / 100) * 0.1;
var val7 = $(".pverify").val();
var result5 = result + result2 + result3 + result4 - val7;
var result6 = result5 * 12;
$("#result").val("$" + result);
$("#result2").val("$" + result2);
$("#result3").val("$" + result3);
$("#result4").val("$" + result4);
$("#result5").val("$" + result5);
$("#result6").val("$" + result6);
});
});
I've got a solution that counts the bits in O(Number of 1's)
time:
bitcount(n):
count = 0
while n > 0:
count = count + 1
n = n & (n-1)
return count
In worst case (when the number is 2^n - 1, all 1's in binary) it will check every bit.
Edit: Just found a very nice constant-time, constant memory algorithm for bitcount. Here it is, written in C:
int BitCount(unsigned int u)
{
unsigned int uCount;
uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}
You can find proof of its correctness here.
I would suggest mine solution that you can find in this GitHub repo. This works also for IE8 and IE9 with a custom arrow that comes from an icon font.
Examples of Custom Cross Browser Drop-down in action: check them with all your browsers to see the cross-browser feature.
Anyway, let's start with the modern browsers and then we will see the solution for the older ones.
For these browser, it is easy to set the same background image for the drop-down in order to have the same arrow.
To do so, you have to reset the browser's default style for the select
tag and set new background rules (like suggested before).
select {
/* you should keep these firsts rules in place to maintain cross-browser behaviour */
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance: none;
background-image: url('<custom_arrow_image_url_here>');
background-position: 98% center;
background-repeat: no-repeat;
outline: none;
...
}
The appearance
rules are set to none to reset browsers default ones, if you want to have the same aspect for each arrow, you should keep them in place.
The background
rules in the examples are set with SVG inline images that represent different arrows. They are positioned 98% from left to keep some margin to the right border (you can easily modify the position as you wish).
In order to maintain the correct cross-browser behavior, the only other rule that have to be left in place is the outline
. This rule resets the default border that appears (in some browsers) when the element is clicked. All the others rules can be easily modified if needed.
This is the harder part... Or maybe not.
There is no standard rule to hide the default arrows for these browsers (like the select::-ms-expand
for IE10+). The solution is to hide the part of the drop-down that contains the default arrow and insert an arrow icon font (or a SVG, if you prefer) similar to the SVG that is used in the other browsers (see the select
CSS rule for more details about the inline SVG used).
The very first step is to set a class that can recognize the browser: this is the reason why I have used the conditional IE IFs at the beginning of the code. These IFs are used to attach specific classes to the html
tag to recognize the older IE browser.
After that, every select
in the HTML have to be wrapped by a div
(or whatever tag that can wraps an element). At this wrapper just add the class that contains the icon font.
<div class="selectTagWrapper prefix-icon-arrow-down-fill">
...
</div>
In easy words, this wrapper is used to simulate the select
tag.
To act like a drop-down, the wrapper must have a border, because we hide the one that comes from the select
.
Notice that we cannot use the select
border because we have to hide the default arrow lengthening it 25% more than the wrapper. Consequently its right border should not be visible because we hide this 25% more by the overflow: hidden
rule applied to the select
itself.
The custom arrow icon-font is placed in the pseudo class :before
where the rule content
contains the reference for the arrow (in this case it is a right parenthesis).
We also place this arrow in an absolute position to center it as much as possible (if you use different icon fonts, remember to adjust them opportunely by changing top and left values and the font size).
.ie8 .prefix-icon-arrow-down-fill:before,
.ie9 .prefix-icon-arrow-down-fill:before {
content: ")";
position: absolute;
top: 43%;
left: 93%;
font-size: 6px;
...
}
You can easily create and substitute the background arrow or the icon font arrow, with every one that you want simply changing it in the background-image
rule or making a new icon font file by yourself.
To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.
var testNum = 134.9567654;
var decPl = 2;
var testRes = roundDec(testNum,decPl);
alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
function roundDec(nbr,dec_places){
var mult = Math.pow(10,dec_places);
return Math.round(nbr * mult) / mult;
}
First of all, when you create ob1
then constructor is called and it starts execution. At that time t.start()
also runs in separate thread. Remember when a new thread is created, it runs parallely to main thread. And thats why main start execution again with next statement.
And Join()
statement is used to prevent the child thread from becoming orphan. Means if you did'nt call join()
in your main class, then main thread will exit after its execution and child thread will be still there executing the statements. Join()
will wait until all child thread complete its execution and then only main method will exit.
Go through this article, helps a lot.
You can use the csv
module to parse tab seperated value files easily.
import csv
with open("tab-separated-values") as tsv:
for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
...
Where line
is a list of the values on the current row for each iteration.
Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip()
builtin:
with open("tab-separated-values") as tsv:
for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
...
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
} catch(Exception e){
System.out.println(e);
}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
To solve your other problem, where you need to set scrolled
if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:
var timer = 0;
$(window).scroll(function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
scrolled = $(window).scrollTop();
}, 250);
});
At any channel page with "user" url for example http://www.youtube.com/user/klauskkpm
, without API call, from YouTube UI, click a video of the channel (in its "VIDEOS" tab) and click the channel name on the video. Then you can get to the page with its "channel" url for example https://www.youtube.com/channel/UCfjTOrCPnAblTngWAzpnlMA
.
In swift
yourLabel.intrinsicContentSize().width
This works for me:
pandas.factorize( ['B', 'C', 'D', 'B'] )[0]
Output:
[0, 1, 2, 0]
You need to make your datetime objects timezone aware. from the datetime docs:
There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.
When you have an aware datetime object, you can use isoformat() and get the output you need.
To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil
Using pytz, this would look like:
import datetime, pytz
datetime.datetime.now(pytz.timezone('US/Central')).isoformat()
You can also control the output format, if you use strftime with the '%z' format directive like
datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')
I recently used Spring Security 3.0 for this (combined with Wicket btw), and am quite happy with it. Here's a good thorough tutorial and documentation. Also take a look at this tutorial which gives a good explanation of the hashing/salting/decoding setup for Spring Security 2.
Vartec's answer with cURL didn't work for me. It did, with a slight improvement due to my specific problem.
e.g.,
When there is a redirect on the server (like when you are trying to save the facebook profile image) you will need following option set:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
The full solution becomes:
$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
There will be an option in configure under Build Triggers
Check the GitHub Branches
A hook will be created and then you can build any branch you like from Jenkins when you select github Branches
Hope it helps :)
I am using Spring Boot 5. I have this controller that I want an unauthenticated user to invoke.
//Builds a form to send to devices
@RequestMapping(value = "/{id}/ViewFormit", method = RequestMethod.GET)
@ResponseBody
String doFormIT(@PathVariable String id) {
try
{
//Get a list of forms applicable to the current user
FormService parent = new FormService();
Here is what i did in the configuuration.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(
"/registration**",
"/{^[\\\\d]$}/ViewFormit",
Hope this helps....
I was getting the MissingManifestResourceException error after I ported my project from VS2005 to VS2010. I didn't have any other classes defined in the file that contains my Form class. And I also had my resx Resource File Name set correctly. Didn't work.
So I deleted the resx files and regenerated them. All good now.
I've been looking for a solution that i can use on bootstrap 4 navbars and other groups of links.
For one reason or another most solutions didn't work especially the ones that try to add 'active' to links onclick because of course once the link is clicked if it takes you to another page then the 'active' you added won't be there because the DOM has changed. Many of the other solutions didn't work either because they often did not match the link or they matched more than one.
This elegant solution is fine for links that are different ie: about.php, index.php, etc...
$(function() {
$('nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');
});
However when it came to the same links with different query strings such as index.php?tag=a, index.php?tag=b, index.php?tag=c it would set all of them to active whichever was clicked as it's matching the pathname not the query as well.
So i tried this code which matched the pathname and the query string and it worked on all the links with query strings but when a link like index.php was clicked it would set the similar query string links active as well. This is because my function is returning an empty string if there is no query string in the link, again just matching the pathname.
$(function() {
$('nav a[href^="' + location.pathname.split("/")[2] + returnQueryString(location.href.split("?")[1]) + '"]').addClass('active');
});
/** returns a query string if there, else an empty string */
function returnQueryString (element) {
if (element === undefined)
return "";
else
return '?' + element;
}
So in the end i abandoned this route and kept it simple and wrote this.
$('.navbar a').each(function(index, element) {
//console.log(index+'-'+element.href);
//console.log(location.href);
/** look at each href in the navbar
* if it matches the location.href then set active*/
if (element.href === location.href){
//console.log("---------MATCH ON "+index+" --------");
$(element).addClass('active');
}
});
It works on all links with or without query strings because element.href and location.href both return the full path. For other menus etc you can simply change the parent class selector (navbar) for another ie:
$('.footer a').each(function(index, element)...
One last thing which also seems important and that is the js & css library's you are using however that's another post perhaps. I hope this helps and contributes.
Because I still have problems with setting proxy settings at work and turning them off at home, I have scripted and publish npm-corpo-proxy.sh. In every corpo the password has to be changed often and must contain special chars, which must be encoded before feeding npm config (the same for backash form domain\user).
Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.
t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]
If you need it to be exception-proof (i.e. supporting empty list), then add:
t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]
If you want to do it without the semicolon, use:
h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]
$ip = $_SERVER['REMOTE_ADDR'];
For linux, you can just use check_output
of the hostname -I
system command like so:
from subprocess import check_output
check_output(['hostname', '-I'])
I have found the answer to my question.
client.DefaultRequestHeaders.Add("X-Version","1");
That should add a custom header to your request
This is not a question about make, it is a question about the semantic of the #include
directive.
The problem is, that there is no file at the path "../StdCUtil/StdCUtil/split.h". This is the path that results when the compiler combines the include path "../StdCUtil" with the relative path from the #include
directive "StdCUtil/split.h".
To fix this, just use -I..
instead of -I../StdCUtil
.
I feel many might be interested in free parameters to alter the shape of the sigmoid function. Second for many applications you want to use a mirrored sigmoid function. Third you might want to do a simple normalization for example the output values are between 0 and 1.
Try:
def normalized_sigmoid_fkt(a, b, x):
'''
Returns array of a horizontal mirrored normalized sigmoid function
output between 0 and 1
Function parameters a = center; b = width
'''
s= 1/(1+np.exp(b*(x-a)))
return 1*(s-min(s))/(max(s)-min(s)) # normalize function to 0-1
And to draw and compare:
def draw_function_on_2x2_grid(x):
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
plt.subplots_adjust(wspace=.5)
plt.subplots_adjust(hspace=.5)
ax1.plot(x, normalized_sigmoid_fkt( .5, 18, x))
ax1.set_title('1')
ax2.plot(x, normalized_sigmoid_fkt(0.518, 10.549, x))
ax2.set_title('2')
ax3.plot(x, normalized_sigmoid_fkt( .7, 11, x))
ax3.set_title('3')
ax4.plot(x, normalized_sigmoid_fkt( .2, 14, x))
ax4.set_title('4')
plt.suptitle('Different normalized (sigmoid) function',size=10 )
return fig
Finally:
x = np.linspace(0,1,100)
Travel_function = draw_function_on_2x2_grid(x)
A slight modification of the suggestion of @Krizz, so that it works properly if the constants header file is to be included in the PCH, which is rather normal. Since the original is imported into the PCH, it won't reload it into the .m
file and thus you get no symbols and the linker is unhappy.
However, the following modification allows it to work. It's a bit convoluted, but it works.
You'll need 3 files, .h
file which has the constant definitions, the .h
file and the .m
file, I'll use ConstantList.h
, Constants.h
and Constants.m
, respectively. the contents of Constants.h
are simply:
// Constants.h
#define STR_CONST(name, value) extern NSString* const name
#include "ConstantList.h"
and the Constants.m
file looks like:
// Constants.m
#ifdef STR_CONST
#undef STR_CONST
#endif
#define STR_CONST(name, value) NSString* const name = @ value
#include "ConstantList.h"
Finally, the ConstantList.h
file has the actual declarations in it and that is all:
// ConstantList.h
STR_CONST(kMyConstant, "Value");
…
A couple of things to note:
I had to redefine the macro in the .m
file after #undef
ing it for the macro to be used.
I also had to use #include
instead of #import
for this to work properly and avoid the compiler seeing the previously precompiled values.
This will require a recompile of your PCH (and probably the entire project) whenever any values are changed, which is not the case if they are separated (and duplicated) as normal.
Hope that is helpful for someone.
UPDATE: I now have a complete turnkey, all-in-one answer, see https://stackoverflow.com/a/49019950/300224. Only took 3 years to figure out!
According to the Travis documentation: https://github.com/travis-ci/travis-ci there is a concoction of projects that collude to deliver the Travis CI web service we know and love. The following subset of projects appears to allow local make test
functionality using the .travis.yml
in your project:
travis-build creates the build
script for each job. It takes the configuration from the .travis.yml
file and
creates a bash
script that is then run in the build environment by
travis-worker.
travis-cookbooks holds the Chef cookbooks that are used to provision the build environments.
travis-worker is responsible for running the build scripts in a clean environment. It streams the log output to travis-logs and pushes state updates (build starting/finishing) to travis-hub.
(The other subprojects are responsible for communicating with GitHub, their web interface, email, and their API.)
For Dot Net Core 3, Microsoft.Data.SqlClient should be used.
This code is not as sophisticated as the answers posted earlier but it will work:
m = max(a)
n = 0 # frequency of max (a)
for number in a :
if number == m :
n = n + 1
ilist = [None] * n # a list containing index values of maximum number in list a.
ilistindex = 0
aindex = 0 # required index value.
for number in a :
if number == m :
ilist[ilistindex] = aindex
ilistindex = ilistindex + 1
aindex = aindex + 1
print ilist
ilist in the above code would contain all the positions of the maximum number in the list.
Use Amazon Athena to query S3 bucket. Also, load data to Amazon Elastic search. Hope this helps.
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
If you using bottombar and insted of viewpager you want to set custom fragment replacement logic with retrieve previously save state you can do using below code
String current_frag_tag = null;
String prev_frag_tag = null;
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
replaceFragment(new Fragment1(), "Fragment1");
break;
case 1:
replaceFragment(new Fragment2(), "Fragment2");
break;
case 2:
replaceFragment(new Fragment3(), "Fragment3");
break;
case 3:
replaceFragment(new Fragment4(), "Fragment4");
break;
default:
replaceFragment(new Fragment1(), "Fragment1");
break;
}
public void replaceFragment(Fragment fragment, String tag) {
if (current_frag_tag != null) {
prev_frag_tag = current_frag_tag;
}
current_frag_tag = tag;
FragmentManager manager = null;
try {
manager = requireActivity().getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (manager.findFragmentByTag(current_frag_tag) == null) { // No fragment in backStack with same tag..
ft.add(R.id.viewpagerLayout, fragment, current_frag_tag);
if (prev_frag_tag != null) {
try {
ft.hide(Objects.requireNonNull(manager.findFragmentByTag(prev_frag_tag)));
} catch (NullPointerException e) {
e.printStackTrace();
}
}
// ft.show(manager.findFragmentByTag(current_frag_tag));
ft.addToBackStack(current_frag_tag);
ft.commit();
} else {
try {
ft.hide(Objects.requireNonNull(manager.findFragmentByTag(prev_frag_tag)))
.show(Objects.requireNonNull(manager.findFragmentByTag(current_frag_tag))).commit();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Inside Child Fragments you can access fragment is visible or not using below method note: you have to implement below method in child fragment
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
try {
if(hidden){
adapter.getFragment(mainVideoBinding.viewPagerVideoMain.getCurrentItem()).onPause();
}else{
adapter.getFragment(mainVideoBinding.viewPagerVideoMain.getCurrentItem()).onResume();
}
}catch (Exception e){
}
}
Copy-on-write is a technique to reduce the memory usage of resource copies using deferred copy. The resource copies are initially virtual (i.e. they share memory) and only become real (i.e. they have their own memory) on the first write operation, hence the name ‘copy-on-write’.
Here after is a Python implementation of the copy-on-write technique using the proxy design pattern. A ValueProxy
object (the proxy) implements the copy-on-write technique by:
Value
object (the subject);ValueProxy
object sharing the same subject attribute as the original ValueProxy
object;Value
object with the new state and the rebinding of the subject attribute to this new immutable Value
object.import abc
class BaseValue(abc.ABC):
@abc.abstractmethod
def read(self):
raise NotImplementedError
@abc.abstractmethod
def write(self, data):
raise NotImplementedError
class Value(BaseValue):
def __init__(self, data):
self.data = data
def read(self):
return self.data
def write(self, data):
pass
class ValueProxy(BaseValue):
def __init__(self, subject):
self.subject = subject
def read(self):
return self.subject.read()
def write(self, data):
self.subject = Value(data)
def clone(self):
return ValueProxy(self.subject)
v1 = ValueProxy(Value('foo'))
v2 = v1.clone() # shares the immutable Value object between the copies
assert v1.subject is v2.subject
v2.write('bar') # creates a new immutable Value object with the new state
assert v1.subject is not v2.subject
Use RVM (Ruby Version Manager) to install and manage any versions of Ruby. You can have multiple versions of Ruby installed on the machine and you can easily select the one you want.
To install RVM type into terminal:
\curl -sSL https://get.rvm.io | bash -s stable
And let it work. After that you will have RVM along with Ruby installed.
Source: RVM Site
The ParameterizedThreadStart
takes one parameter. You can use that to send one parameter, or a custom class containing several properties.
Another method is to put the method that you want to start as an instance member in a class along with properties for the parameters that you want to set. Create an instance of the class, set the properties and start the thread specifying the instance and the method, and the method can access the properties.
RFC3966 defines the IETF standard URI for telephone numbers, that is the 'tel:' URI. That's the standard. There's no similar standard that specifies 'callto:', that's a particular convention for Skype on platforms where is allows registering a URI handler to support it.
Remove these two lines:
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.
MultipleIE , IETester there are many similar to those.
Multiple IE supports IE3 IE4.01 IE5 IE5.5 and IE6 and "is no longer maintained and there are no plans to continue maintaining it! Thanks and good luck!".
IETester seems a better choice : IE10, IE9, IE8, IE7 IE 6 and IE5.5 on Windows 8 desktop, Windows 7, Vista and XP
I'm newbie, so sorry if is a bad practice. Based on the chosen answer, I did this function:
function x_apply(selector, variable, value) {
var scope = angular.element( $(selector) ).scope();
scope.$apply(function(){
scope[variable] = value;
});
}
I'm using it this way:
x_apply('#fileuploader', 'thereisfiles', true);
By the way, sorry for my english
You can use the mciSendString
API to play an MP3 or a WAV file:
[DllImport("winmm.dll")]
public static extern uint mciSendString(
string lpstrCommand,
StringBuilder lpstrReturnString,
int uReturnLength,
IntPtr hWndCallback
);
mciSendString(@"close temp_alias", null, 0, IntPtr.Zero);
mciSendString(@"open ""music.mp3"" alias temp_alias", null, 0, IntPtr.Zero);
mciSendString("play temp_alias repeat", null, 0, IntPtr.Zero);
A single listening port can accept more than one connection simultaneously.
There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.
Each TCP/IP packet has basically four fields for addressing. These are:
source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>
Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).
If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port
varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.
However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.
So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.
The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.
We had the same issue.
The parent pom file was available in our local repository, but maven still unsuccessfully tried to download it from the central repository, or from the relativePath (there were no files in the relative path).
Turns out, there was a file called "_remote.repositories" in the local repository, which was causing this behavior. After deleting all the files with this name from the complete local repository, we could build our modules.
It's obvious, but the App Theme
selection in design is just for display a draft during layout edition, is not related to real app looking in cell phone.
Just change the manifest file (AndroidManifest.xml
) is not enough because the style need to be predefined is styles.xml
. Also is useless change the layout files.
All proposed solution in Java
or Kotlin
has failed for me. Some of them crash the app. And if one never (like me) uses the title bar in app, the static solution is cleaner.
For me the only solution that works in 2019 (Android Studio 3.4.1) is:
in styles.xml
(under app/res/values) add the lines:
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
After in AndroidManifest.xml
(under app/manifests)
Replace
android:theme="@style/AppTheme">
by
android:theme="@style/AppTheme.NoActionBar">
It seems in general you're just looking for a join:
> dat1 = pd.DataFrame({'dat1': [9,5]})
> dat2 = pd.DataFrame({'dat2': [7,6]})
> dat1.join(dat2)
dat1 dat2
0 9 7
1 5 6
In the general case, the answer is No.
However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.
In Visual Studio, this option is located here:
Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic
There, you can check the Thrown box.
For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue>
and not tied directly to Dictionary<TKey, TValue>
, you can implement your own dictionary class which provides this behavior.
I was having the same issue with IIS 7.5 with a WCF REST Service. Trying to upload via POST any file above 65k and it would return Error 413 "Request Entity too large".
The first thing you need to understand is what kind of binding you've configured in the web.config. Here's a great article...
BasicHttpBinding vs WsHttpBinding vs WebHttpBinding
If you have a REST service then you need to configure it as "webHttpBinding". Here's the fix:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" transferMode="Streamed">
</binding>
</webHttpBinding>
</bindings>
Following OP's edit:
var now = new Date();_x000D_
var start = new Date(now.getFullYear(), 0, 0);_x000D_
var diff = now - start;_x000D_
var oneDay = 1000 * 60 * 60 * 24;_x000D_
var day = Math.floor(diff / oneDay);_x000D_
console.log('Day of year: ' + day);
_x000D_
Edit: The code above will fail when now
is a date in between march 26th and October 29th andnow
's time is before 1AM (eg 00:59:59). This is due to the code not taking daylight savings time into account. You should compensate for this:
var now = new Date();_x000D_
var start = new Date(now.getFullYear(), 0, 0);_x000D_
var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);_x000D_
var oneDay = 1000 * 60 * 60 * 24;_x000D_
var day = Math.floor(diff / oneDay);_x000D_
console.log('Day of year: ' + day);
_x000D_
Here is what I write to get the timestamp in millionseconds.
#include<sys/time.h>
long long timeInMilliseconds(void) {
struct timeval tv;
gettimeofday(&tv,NULL);
return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}
In the latest version of ggplot2, this can be more easy.
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))
See ?expansion()
for more details.
Hope this gist help https://gist.github.com/imammubin/a587192982ff8db221da14d094df6fb4
MainActivity as Screen Launcher with handler & runnable function, the Runnable run to login page or feed page with base preference login user with firebase.
Try using the ISO string
var isodate = new Date().toISOString()
See also: method definition at MDN.
Your pip
is a soft link to the same executable file path with pip3
.
you can use the commands below to check where your pip
and pip3
real paths are:
$ ls -l `which pip`
$ ls -l `which pip3`
You may also use the commands below to know more details:
$ pip show pip
$ pip3 show pip
When we install different versions of python, we may create such soft links to
It is the same situation with python
, python2
, python3
More information below if you're interested in how it happens in different cases:
Actually in case if you have any file that has key value pairs like this:
someKey=someValue
someOtherKey=someOtherValue
You can import that into webpack by a npm module called properties-reader
I found this really helpful since I'm integrating react with Java Spring framework where there is already an application.properties file. This helps me to keep all config together in one place.
"properties-reader": "0.0.16"
const PropertiesReader = require('properties-reader');
const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;
externals: {
'Config': JSON.stringify(appProperties)
}
var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')
Use the String.split()
var array = string.split(',');
The core problem is the js errors:
$('#purpose').on('change', function () {
// if (this.value == '1'); { No semicolon and I used === instead of ==
if (this.value === '1'){
$("#business").show();
} else {
$("#business").hide();
}
});
// }); remove
http://jsfiddle.net/Bushwazi/2kGzZ/3/
I had to clean up the html & js...I couldn't help myself.
HTML:
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<form id="business">
<label for="business">Business Name</label>
<input type='text' class='text' name='business' value size='20' />
</form>
CSS:
#business {
display:none;
}
JS:
$('#purpose').on('change', function () {
if(this.value === "1"){
$("#business").show();
} else {
$("#business").hide();
}
});
The accepted answer lead me to believe that decoupling Django backend and React Frontend is the right way to go no matter what. In fact there are approaches in which React and Django are coupled, which may be better suited in particular situations.
This tutorial well explains this. In particular:
I see the following patterns (which are common to almost every web framework):
-React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium)
-Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication)
-Mix and match: mini React apps inside Django templates (difficulty: simple)
Here is how you do in Eloquent
$users = User::whereIn('id', array(1, 2, 3))->get();
And if you are using Query builder then :
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
An Alternative to using an API is to use HTML 5 location Navigator to query the browser about the User location. I was looking for a similar approach as in the subject question but I found that HTML 5 Navigator works better and cheaper for my situation. Please consider that your scinario might be different. To get the User position using Html5 is very easy:
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
console.log("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
console.log("Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude);
}
Try it yourself on W3Schools Geolocation Tutorial
The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:
There are 2 different ways you can look for lowercase characters:
Use str.islower()
to find lowercase characters. Combined with a list comprehension, you can gather all lowercase letters:
lowercase = [c for c in s if c.islower()]
You could use a regular expression:
import re
lc = re.compile('[a-z]+')
lowercase = lc.findall(s)
The first method returns a list of individual characters, the second returns a list of character groups:
>>> import re
>>> lc = re.compile('[a-z]+')
>>> lc.findall('AbcDeif')
['bc', 'eif']