Just add a STYLE line and your progress becomes horizontal:
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/progress"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:max="100"
android:progress="45"/>
Yes, in API level 26
it's deprecated. Instead, you can use progressBar
.
To create it programmatically:
First get a reference to the root layout
RelativeLayout layout = findViewById(R.id.display); //specify here Root layout Id
or
RelativeLayout layout = findViewById(this);
Then add the progress bar
progressBar = new ProgressBar(youractivity.this, null, android.R.attr.progressBarStyleLarge);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(progressBar, params);
To show the progress bar
progressBar.setVisibility(View.VISIBLE);
To hide the progress bar
progressBar.setVisibility(View.GONE);
To disable the user interaction you just need to add the following code
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
To get user interaction back you just need to add the following code
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Just for future reference, change the android.R.attr.progressBarStyleSmall
to android.R.attr.progressBarStyleHorizontal
.
The code below only works above API level 21
progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
To create it via xml:
<ProgressBar
android:id="@+id/progressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
android:max="100"
android:backgroundTint="@color/white"
android:layout_below="@+id/framelauout"
android:indeterminateTint="#1a09d6"
android:layout_marginTop="-7dp"/>
In your activity
progressBar = (ProgressBar) findViewById(R.id.progressbar);
Showing/hiding the progress bar is the same
progressBar.setVisibility(View.VISIBLE); // To show the ProgressBar
progressBar.setVisibility(View.INVISIBLE); // To hide the ProgressBar
Here is a sample image of what it would look like:
For more details:
1. Reference one
2. Reference Two
From this tutorial:
<style name="CustomProgressBarHorizontal" parent="android:Widget.ProgressBar.Horizontal">
<item name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
<item name="android:minHeight">10dip</item>
<item name="android:maxHeight">20dip</item>
</style>
Then simply apply the style to your progress bars or better, override the default style in your theme to style all of your app's progress bars automatically.
The difference you are seeing in the screenshots is because the phones/emulators are using a difference Android version (latest is the theme from ICS (Holo), top is the original theme).
simply use:
PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
mode = PorterDuff.Mode.MULTIPLY;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
progressBar.setProgressBackgroundTintList(ColorStateList.valueOf(Color.RED));
} else {
Drawable progressDrawable;
progressDrawable = (progressBar.isIndeterminate() ? progressBar.getIndeterminateDrawable() : progressBar.getProgressDrawable()).mutate();
progressDrawable.setColorFilter(context.getResources().getColor(Color.RED), mode);
progressBar.setProgressDrawable(progressDrawable);
}
You can try this Circle Progress library
NB: please always use same width and height for progress views
DonutProgress:
<com.github.lzyzsd.circleprogress.DonutProgress
android:id="@+id/donut_progress"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:circle_progress="20"/>
CircleProgress:
<com.github.lzyzsd.circleprogress.CircleProgress
android:id="@+id/circle_progress"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:circle_progress="20"/>
ArcProgress:
<com.github.lzyzsd.circleprogress.ArcProgress
android:id="@+id/arc_progress"
android:background="#214193"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:arc_progress="55"
custom:arc_bottom_text="MEMORY"/>
Update
As of 2019 this can be easily achieved using ProgressIndicator
, in Material Components library, used with the Widget.MaterialComponents.ProgressIndicator.Circular.Indeterminate
style.
For more details please check Gabriele Mariotti's answer below.
Old implementation
Here is an awesome implementation of the material design circular intermediate progress bar https://gist.github.com/castorflex/4e46a9dc2c3a4245a28e. The implementation only lacks the ability add various colors like in inbox by android app but this does a pretty great job.
try this method to create a bitmap and set it to image view.
private void circularImageBar(ImageView iv2, int i) {
Bitmap b = Bitmap.createBitmap(300, 300,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
Paint paint = new Paint();
paint.setColor(Color.parseColor("#c4c4c4"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(150, 150, 140, paint);
paint.setColor(Color.parseColor("#FFDB4C"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.FILL);
final RectF oval = new RectF();
paint.setStyle(Paint.Style.STROKE);
oval.set(10,10,290,290);
canvas.drawArc(oval, 270, ((i*360)/100), false, paint);
paint.setStrokeWidth(0);
paint.setTextAlign(Align.CENTER);
paint.setColor(Color.parseColor("#8E8E93"));
paint.setTextSize(140);
canvas.drawText(""+i, 150, 150+(paint.getTextSize()/3), paint);
iv2.setImageBitmap(b);
}
For your first question try
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
(available since API 8)
To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.
Customizing the color of progressbar namely in case of spinner type needs an xml file and initiating codes in their respective java files.
Create an xml file and name it as progressbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
tools:context=".Radio_Activity" >
<LinearLayout
android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ProgressBar
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ProgressBar>
</LinearLayout>
</LinearLayout>
Use the following code to get the spinner in various expected color.Here we use the hexcode to display spinner in blue color.
Progressbar spinner = (ProgressBar) progrees.findViewById(R.id.spinner);
spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#80DAEB"),
android.graphics.PorterDuff.Mode.MULTIPLY);
I copied this from one of my apps, so there's prob a few extra attributes, but should give you the idea. This is from the layout that has the progress bar:
<ProgressBar
android:id="@+id/ProgressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:maxHeight="10dip"
android:minHeight="10dip"
android:progress="50"
android:progressDrawable="@drawable/greenprogress" />
Then create a new drawable with something similar to the following (In this case greenprogress.xml
):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:startColor="#ff9d9e9d" />
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:centerColor="#80ffb600"
android:centerY="0.75"
android:endColor="#a0ffcb00"
android:startColor="#80ffd300" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:endColor="#008000"
android:startColor="#33FF33" />
</shape>
</clip>
</item>
</layer-list>
You can change up the colors as needed, this will give you a green progress bar.
Put this XML to show only the wheel:
<ProgressBar
android:indeterminate="true"
android:id="@+id/marker_progress"
style="?android:attr/progressBarStyle"
android:layout_height="50dp" />
Here is the code that I am using:
Inside WebViewClient:
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progress1).setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progress1).setVisibility(View.GONE);
}
Here is the XML :
<ProgressBar
android:id="@+id/progress1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Hope this helps..
If you really have to iterate a Pandas dataframe, you will probably want to avoid using iterrows(). There are different methods and the usual iterrows()
is far from being the best. itertuples() can be 100 times faster.
In short:
df.itertuples(name=None)
. In particular, when you have a fixed number columns and less than 255 columns. See point (3)df.itertuples()
except if your columns have special characters such as spaces or '-'. See point (2)itertuples()
even if your dataframe has strange columns by using the last example. See point (4)iterrows()
if you cannot the previous solutions. See point (1)Generate a random dataframe with a million rows and 4 columns:
df = pd.DataFrame(np.random.randint(0, 100, size=(1000000, 4)), columns=list('ABCD'))
print(df)
1) The usual iterrows()
is convenient, but damn slow:
start_time = time.clock()
result = 0
for _, row in df.iterrows():
result += max(row['B'], row['C'])
total_elapsed_time = round(time.clock() - start_time, 2)
print("1. Iterrows done in {} seconds, result = {}".format(total_elapsed_time, result))
2) The default itertuples()
is already much faster, but it doesn't work with column names such as My Col-Name is very Strange
(you should avoid this method if your columns are repeated or if a column name cannot be simply converted to a Python variable name).:
start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
result += max(row.B, row.C)
total_elapsed_time = round(time.clock() - start_time, 2)
print("2. Named Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))
3) The default itertuples()
using name=None is even faster but not really convenient as you have to define a variable per column.
start_time = time.clock()
result = 0
for(_, col1, col2, col3, col4) in df.itertuples(name=None):
result += max(col2, col3)
total_elapsed_time = round(time.clock() - start_time, 2)
print("3. Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))
4) Finally, the named itertuples()
is slower than the previous point, but you do not have to define a variable per column and it works with column names such as My Col-Name is very Strange
.
start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
result += max(row[df.columns.get_loc('B')], row[df.columns.get_loc('C')])
total_elapsed_time = round(time.clock() - start_time, 2)
print("4. Polyvalent Itertuples working even with special characters in the column name done in {} seconds, result = {}".format(total_elapsed_time, result))
Output:
A B C D
0 41 63 42 23
1 54 9 24 65
2 15 34 10 9
3 39 94 82 97
4 4 88 79 54
... .. .. .. ..
999995 48 27 4 25
999996 16 51 34 28
999997 1 39 61 14
999998 66 51 27 70
999999 51 53 47 99
[1000000 rows x 4 columns]
1. Iterrows done in 104.96 seconds, result = 66151519
2. Named Itertuples done in 1.26 seconds, result = 66151519
3. Itertuples done in 0.94 seconds, result = 66151519
4. Polyvalent Itertuples working even with special characters in the column name done in 2.94 seconds, result = 66151519
This article is a very interesting comparison between iterrows and itertuples
Well, here is one solution I ended up with, but I hope there's a more elegant one...
StringBuilder result = new StringBuilder();
for(int i=0; i<name.length(); i++) {
char tmpChar = name.charAt( i );
if (Character.isLetterOrDigit( tmpChar) || tmpChar == '_' ) {
result.append( tmpChar );
}
}
result
ends up with the desired result...
CreateImage(size, depth, channels)
https://opencv.willowgarage.com/documentation/python/core_operations_on_arrays.html#CreateImage
Using unzip
unzip -c whatever.war META-INF/MANIFEST.MF
It will print the output in terminal.
And for extracting all the files,
unzip whatever.war
Using jar
jar xvf test.war
Note! The jar
command will extract war contents to current directory. Not to a subdirectory (like Tomcat does).
Here's a C# method to return the angle (0-360) anticlockwise from the horizontal for a point on a circle.
public static double GetAngle(Point centre, Point point1)
{
// Thanks to Dave Hill
// Turn into a vector (from the origin)
double x = point1.X - centre.X;
double y = point1.Y - centre.Y;
// Dot product u dot v = mag u * mag v * cos theta
// Therefore theta = cos -1 ((u dot v) / (mag u * mag v))
// Horizontal v = (1, 0)
// therefore theta = cos -1 (u.x / mag u)
// nb, there are 2 possible angles and if u.y is positive then angle is in first quadrant, negative then second quadrant
double magnitude = Math.Sqrt(x * x + y * y);
double angle = 0;
if(magnitude > 0)
angle = Math.Acos(x / magnitude);
angle = angle * 180 / Math.PI;
if (y < 0)
angle = 360 - angle;
return angle;
}
Cheers, Paul
Before delete
, there are several methods in laravel.
User::find(1)
and User::first()
return an instance.
User::where('id',1)->get
and User::all()
return a collection of instance.
call delete
on an model instance will returns true/false
$user=User::find(1);
$user->delete(); //returns true/false
call delete
on a collection of instance will returns a number which represents the number of the records had been deleted
//assume you have 10 users, id from 1 to 10;
$result=User::where('id','<',11)->delete(); //returns 11 (the number of the records had been deleted)
//lets call delete again
$result2=User::where('id','<',11)->delete(); //returns 0 (we have already delete the id<11 users, so this time we delete nothing, the result should be the number of the records had been deleted(0) )
Also there are other delete methods, you can call destroy
as a model static method like below
$result=User::destroy(1,2,3);
$result=User::destroy([1,2,3]);
$result=User::destroy(collect([1, 2, 3]));
//these 3 statement do the same thing, delete id =1,2,3 users, returns the number of the records had been deleted
One more thing ,if you are new to laravel
,you can use php artisan tinker
to see the result, which is more efficient and then dd($result)
, print_r($result);
Two different characters.
\n
is used as an end-of-line terminator in Unix text files
\r
Was historically (pre-OS X) used as an end-of-line terminator in Mac text files
\r\n
(ie both) are used to terminate lines in Windows and DOS text files.
I asked in #machomebrew and learned that you can switch between versions using brew switch.
$ brew switch libfoo mycopy
to get version mycopy of libfoo.
The error means that you are providing not as much data as the table wp_posts
does contain columns. And now the DB engine does not know in which columns to put your data.
To overcome this you must provide the names of the columns you want to fill. Example:
insert into wp_posts (column_name1, column_name2)
values (1, 3)
Look up the table definition and see which columns you want to fill.
And insert
means you are inserting a new record. You are not modifying an existing one. Use update
for that.
I use the following to turn all error reporting on for MySQLi
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
*NOTE: don't use this in a production environment.
I have used this one successfully
System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
It works even inside linqpad.
Here's a blog post explains it very well:
http://panks.me/posts/2013/11/install-gdb-on-os-x-mavericks-from-source/
And the way I get it working:
Create a coding signing certificate via KeyChain Access:
1.1 From the Menu, select KeyChain Access > Certificate Assistant > Create a Certificate...
1.2 Follow the wizard to create a certificate and let's name it gdb-cert
, the Identity Type is Self Signed Root, and the Certificate Type is Code Signing and select the Let me override defaults.
1.3 Click several times on Continue until you get to the Specify a Location For The Certificate screen, then set Keychain to System.
Install gdb via Homebrew: brew install gdb
Restart taskgated
: sudo killall taskgated && exit
Reopen a Terminal window and type sudo codesign -vfs gdb-cert /usr/local/bin/gdb
If you grab the MVC Futures assembly (which I would highly recommend) you can then use a generic when creating the ActionLink and a lambda to construct the route:
<%=Html.ActionLink<Product>(c => c.Action( o.Value ), "Details" ) %>
You can get the futures assembly here: http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471
Java doesn't have a Random generator between two values in the same way that Python does. It actually only takes one value in to generate the Random. What you need to do, then, is add ONE CERTAIN NUMBER to the number generated, which will cause the number to be within a range. For instance:
package RandGen;
import java.util.Random;
public class RandGen {
public static Random numGen =new Random();
public static int RandNum(){
int rand = Math.abs((100)+numGen.nextInt(100));
return rand;
}
public static void main(String[]Args){
System.out.println(RandNum());
}
}
This program's function lies entirely in line 6 (The one beginning with "int rand...". Note that Math.abs() simply converts the number to absolute value, and it's declared as an int, that's not really important. The first (100) is the number I am ADDING to the random one. This means that the new output number will be the random number + 100. numGen.nextInt() is the value of the random number itself, and because I put (100) in its parentheses, it is any number between 1 and 100. So when I add 100, it becomes a number between 101 and 200. You aren't actually GENERATING a number between 100 and 200, you are adding to the one between 1 and 100.
Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this question: Anonymous vs named inner classes? - best practices?
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
A neato trick with groupby is to run length encoding in one line:
[(c,len(list(cgen))) for c,cgen in groupby(some_string)]
will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.
Edit: Note that this is what separates itertools.groupby
from the SQL GROUP BY
semantics: itertools doesn't (and in general can't) sort the iterator in advance, so groups with the same "key" aren't merged.
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
undef
, zero, empty string, false
, falsy ...)1 * (aka associative-array, aka dictionary)
You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready
should end with });
not )};
Check this link.
Using BitArray class and making an extension method as OP suggests:
public static bool GetBit(this byte b, int bitNumber)
{
System.Collections.BitArray ba = new BitArray(new byte[]{b});
return ba.Get(bitNumber);
}
You can specify the whole day by doing a range, like so:
WHERE bk_date >= TO_DATE('2012-03-18', 'YYYY-MM-DD')
AND bk_date < TO_DATE('2012-03-19', 'YYYY-MM-DD')
More simply you can use TRUNC:
WHERE TRUNC(bk_date) = TO_DATE('2012-03-18', 'YYYY-MM-DD')
TRUNC without parameter removes hours, minutes and seconds from a DATE.
CodeIgniter User Guide says:
$this->uri->segment(n)
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this: http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1. news 2. local 3. metro 4. crime_is_up
So segment
refers to your url structure segment. By the above example, $this->uri->segment(3)
would be 'metro'
, while $this->uri->segment(4)
would be 'crime_is_up'
.
I had the same problem, so I wrote this. It works rather well. Looks great if you mix it with some CSS transitions.
function toggle_visibility(id) {
var e = document.getElementById("mjwelcome");
if(e.style.height == '')
e.style.height = '0px';
else
e.style.height = '';
}
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
You can also use array_reduce()
if you prefer a more functional approach
For instance:
$userNames = array_reduce($users, function ($carry, $user) {
array_push($carry, $user['name']);
return $carry;
}, []);
Or if you like to be fancy,
$userNames = [];
array_map(function ($user) use (&$userNames){
$userNames[]=$user['name'];
}, $users);
This and all the methods above do loop behind the scenes though ;)
If you are using Homebrew to install [email protected], the location is
/usr/local/Homebrew/var/mysql
I don't know if the location is the same for other versions.
I'd suggest that the -i
means it does match "ABC", but the difference is in the output. -i
doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o
says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.
The output of echo "ABC" | grep -i abc
is ABC
, the -o
shows output matching "abc" so nothing shows:
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC
Here is a plotrix solution:
set.seed(0815)
x <- 1:10
F <- runif(10,1,2)
L <- runif(10,0,1)
U <- runif(10,2,3)
require(plotrix)
plotCI(x, F, ui=U, li=L)
And here is a ggplot solution:
set.seed(0815)
df <- data.frame(x =1:10,
F =runif(10,1,2),
L =runif(10,0,1),
U =runif(10,2,3))
require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
geom_point(size = 4) +
geom_errorbar(aes(ymax = U, ymin = L))
UPDATE: Here is a base solution to your edits:
set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
y = x + rnorm(20))
plot(y ~ x, data = df)
# model
mod <- lm(y ~ x, data = df)
# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx),
interval = 'confidence')
# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')
It's new to SQL 2005 and offers a simplified way to group objects, especially for the purpose of securing the objects in that "group".
The following link offers a more in depth explanation as to what it is, why we would use it:
Understanding the Difference between Owners and Schemas in SQL Server
In Ubuntu/Mint (Debian based)
$ sudo apt-get install php5-gd
here some itemdecoration for recyclerview
public class HeaderItemDecoration extends RecyclerView.ItemDecoration {
private View customView;
public HeaderItemDecoration(View view) {
this.customView = view;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
customView.layout(parent.getLeft(), 0, parent.getRight(), customView.getMeasuredHeight());
for (int i = 0; i < parent.getChildCount(); i++) {
View view = parent.getChildAt(i);
if (parent.getChildAdapterPosition(view) == 0) {
c.save();
final int height = customView.getMeasuredHeight();
final int top = view.getTop() - height;
c.translate(0, top);
customView.draw(c);
c.restore();
break;
}
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) == 0) {
customView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
outRect.set(0, customView.getMeasuredHeight(), 0, 0);
} else {
outRect.setEmpty();
}
}
}
window.oncontextmenu = function (e) {_x000D_
e.preventDefault()_x000D_
alert('Right Click')_x000D_
}
_x000D_
<h1>Please Right Click here!</h1>
_x000D_
Using the constructor
BigInteger(String val)
Translates the decimal String representation of a BigInteger into a BigInteger.
The poster has their java types mixed up. in java, his C in is a short: short (16 bit) = -32768 to 32767 int (32 bit) = -2,147,483,648 to 2,147,483,647
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host
and hostname
.
The following code does this:
var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;
if (isSubdomain) {
domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
domain = window.location.hostname;
}
If you don't know the size of the browser you can simply center in CSS with the following code:
HTML code:
<div class="firstDiv">Some Text</div>
CSS code:
.firstDiv {
width: 500px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #F1F1F1;
}
This also helps in any unforeseen changes in the future.
In Node.js, you can set global variables via the "global" or "GLOBAL" object:
GLOBAL._ = require('underscore'); // But you "shouldn't" do this! (see note below)
or more usefully...
GLOBAL.window = GLOBAL; // Like in the browser
From the Node.js source, you can see that these are aliased to each other:
node-v0.6.6/src/node.js:
28: global = this;
128: global.GLOBAL = global;
In the code above, "this" is the global context. With the CommonJS module system (which Node.js uses), the "this" object inside of a module (i.e., "your code") is not the global context. For proof of this, see below where I spew the "this" object and then the giant "GLOBAL" object.
console.log("\nTHIS:");
console.log(this);
console.log("\nGLOBAL:");
console.log(global);
/* Outputs ...
THIS:
{}
GLOBAL:
{ ArrayBuffer: [Function: ArrayBuffer],
Int8Array: { [Function] BYTES_PER_ELEMENT: 1 },
Uint8Array: { [Function] BYTES_PER_ELEMENT: 1 },
Int16Array: { [Function] BYTES_PER_ELEMENT: 2 },
Uint16Array: { [Function] BYTES_PER_ELEMENT: 2 },
Int32Array: { [Function] BYTES_PER_ELEMENT: 4 },
Uint32Array: { [Function] BYTES_PER_ELEMENT: 4 },
Float32Array: { [Function] BYTES_PER_ELEMENT: 4 },
Float64Array: { [Function] BYTES_PER_ELEMENT: 8 },
DataView: [Function: DataView],
global: [Circular],
process:
{ EventEmitter: [Function: EventEmitter],
title: 'node',
assert: [Function],
version: 'v0.6.5',
_tickCallback: [Function],
moduleLoadList:
[ 'Binding evals',
'Binding natives',
'NativeModule events',
'NativeModule buffer',
'Binding buffer',
'NativeModule assert',
'NativeModule util',
'NativeModule path',
'NativeModule module',
'NativeModule fs',
'Binding fs',
'Binding constants',
'NativeModule stream',
'NativeModule console',
'Binding tty_wrap',
'NativeModule tty',
'NativeModule net',
'NativeModule timers',
'Binding timer_wrap',
'NativeModule _linklist' ],
versions:
{ node: '0.6.5',
v8: '3.6.6.11',
ares: '1.7.5-DEV',
uv: '0.6',
openssl: '0.9.8n' },
nextTick: [Function],
stdout: [Getter],
arch: 'x64',
stderr: [Getter],
platform: 'darwin',
argv: [ 'node', '/workspace/zd/zgap/darwin-js/index.js' ],
stdin: [Getter],
env:
{ TERM_PROGRAM: 'iTerm.app',
'COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET': '/tmp/launch-nNl1vo/ServiceProcessSocket',
TERM: 'xterm',
SHELL: '/bin/bash',
TMPDIR: '/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/',
Apple_PubSub_Socket_Render: '/tmp/launch-9Ga0PT/Render',
USER: 'ddopson',
COMMAND_MODE: 'unix2003',
SSH_AUTH_SOCK: '/tmp/launch-sD905b/Listeners',
__CF_USER_TEXT_ENCODING: '0x12D732E7:0:0',
PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11/bin',
PWD: '/workspace/zd/zgap/darwin-js',
LANG: 'en_US.UTF-8',
ITERM_PROFILE: 'Default',
SHLVL: '1',
COLORFGBG: '7;0',
HOME: '/Users/ddopson',
ITERM_SESSION_ID: 'w0t0p0',
LOGNAME: 'ddopson',
DISPLAY: '/tmp/launch-l9RQXI/org.x:0',
OLDPWD: '/workspace/zd/zgap/darwin-js/external',
_: './index.js' },
openStdin: [Function],
exit: [Function],
pid: 10321,
features:
{ debug: false,
uv: true,
ipv6: true,
tls_npn: false,
tls_sni: true,
tls: true },
kill: [Function],
execPath: '/usr/local/bin/node',
addListener: [Function],
_needTickCallback: [Function],
on: [Function],
removeListener: [Function],
reallyExit: [Function],
chdir: [Function],
debug: [Function],
error: [Function],
cwd: [Function],
watchFile: [Function],
umask: [Function],
getuid: [Function],
unwatchFile: [Function],
mixin: [Function],
setuid: [Function],
setgid: [Function],
createChildProcess: [Function],
getgid: [Function],
inherits: [Function],
_kill: [Function],
_byteLength: [Function],
mainModule:
{ id: '.',
exports: {},
parent: null,
filename: '/workspace/zd/zgap/darwin-js/index.js',
loaded: false,
exited: false,
children: [],
paths: [Object] },
_debugProcess: [Function],
dlopen: [Function],
uptime: [Function],
memoryUsage: [Function],
uvCounters: [Function],
binding: [Function] },
GLOBAL: [Circular],
root: [Circular],
Buffer:
{ [Function: Buffer]
poolSize: 8192,
isBuffer: [Function: isBuffer],
byteLength: [Function],
_charsWritten: 8 },
setTimeout: [Function],
setInterval: [Function],
clearTimeout: [Function],
clearInterval: [Function],
console: [Getter],
window: [Circular],
navigator: {} }
*/
** Note: regarding setting "GLOBAL._", in general you should just do var _ = require('underscore');
. Yes, you do that in every single file that uses Underscore.js, just like how in Java you do import com.foo.bar;
. This makes it easier to figure out what your code is doing because the linkages between files are 'explicit'. It is mildly annoying, but a good thing. .... That's the preaching.
There is an exception to every rule. I have had precisely exactly one instance where I needed to set "GLOBAL._". I was creating a system for defining "configuration" files which were basically JSON, but were "written in JavaScript" to allow a bit more flexibility. Such configuration files had no 'require' statements, but I wanted them to have access to Underscore.js (the entire system was predicated on Underscore.js and Underscore.js templates), so before evaluating the "configuration", I would set "GLOBAL._". So yeah, for every rule, there's an exception somewhere. But you had better have a darn good reason and not just "I get tired of typing 'require', so I want to break with the convention".
When you run the code
listoflists.append((list, list[0]))
You are not (as I think you expect) adding a copy of list
to the end of listoflists
. What you are doing is adding a reference to list
to the end of listoflists
. Thus, every time you update list
, it updates every reference to list
, which in this case, is every item in listoflists
What you could do instead is something like this:
listoflists = []
for i in range(1, 10):
listoflists.append((range(i), 0))
You should change the query to:
SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col
This vl works correctly.
Here is another way, by rotating element
with the scrollbar
for 180deg,
wrapping it's content
into another element, and rotating
that wrapper
for -180deg
.
Check the snippet below
div {_x000D_
display: inline-block;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 2px solid black;_x000D_
margin: 15px;_x000D_
}_x000D_
#vertical {_x000D_
direction: rtl;_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
background: gold;_x000D_
}_x000D_
#vertical p {_x000D_
direction: ltr;_x000D_
margin-bottom: 0;_x000D_
}_x000D_
#horizontal {_x000D_
direction: rtl;_x000D_
transform: rotate(180deg);_x000D_
overflow-y: hidden;_x000D_
overflow-x: scroll;_x000D_
background: tomato;_x000D_
padding-top: 30px;_x000D_
}_x000D_
#horizontal span {_x000D_
direction: ltr;_x000D_
display: inline-block;_x000D_
transform: rotate(-180deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id=vertical>_x000D_
<p>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content</p>_x000D_
</div>_x000D_
<div id=horizontal><span> content_content_content_content_content_content_content_content_content_content_content_content_content_content</span>_x000D_
</div>
_x000D_
Just wanted to add that the options to cron seem to have changed. Need to pass -n rather than -D.
cygrunsrv -I cron -p /usr/sbin/cron -a -n
Just make sure put single space before and after "and" Keyword..
SerialPort (RS-232 Serial COM Port) in C# .NET
This article explains how to use the SerialPort
class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files. It even covers the pin assignments on the port itself.
Example Code:
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace SerialPortExample
{
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this class
new SerialPortProgram();
}
private SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Application.Run();
}
private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
}
If you have any programming experience, you can probably learn the C# syntax in a few hours, and be comfortable with it within a week or so. However, you will not be writing complex structures unless you write a lot of code with it. It's really the same as learning any language: you can learn all the words and grammer fairly quickly, but it takes a while to be fluent.
EDIT
A book you may want to pick up for learning C# is C# in a Nutshell (3.0) which I found to be very useful, and has been recommended by several people here.
M.Ali's answer could be modified as
select Cast(Cast((37.0/38.0)*100 as decimal(18,2)) as varchar(5)) + ' %' as Percentage
I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:
from cx_Freeze import setup, Executable
import sys
productName = "ProductName"
if 'bdist_msi' in sys.argv:
sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
sys.argv += ['--install-script', 'install.py']
exe = Executable(
script="main.py",
base="Win32GUI",
targetName="Product.exe"
)
setup(
name="Product.exe",
version="1.0",
author="Me",
description="Copyright 2012",
executables=[exe],
scripts=[
'install.py'
]
)
Set the [Console]::OuputEncoding
as encoding whatever you want, and print out with [Console]::WriteLine
.
If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)
If you want to get the date of one month from now you can do it like this
echo date('Y-m-d', strtotime('1 month'));
If you want to get the date of two months from now, you can achieve that by doing this
echo date('Y-m-d', strtotime('2 month'));
And so on, that's all.
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the activity. After researching the problem on Stack Overflow, I adopted the following solution:
volatile boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.
I agree that Google's Gson
is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple
:
// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;
@Test
public void json2Object() {
// given
String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
+ "\"address\" : \"some address\","
+ "\"someobject\" : {\"field\" : \"value\"}}";
// when
JSONObject object = (JSONObject) JSONValue.parse(jsonString);
// then
@SuppressWarnings("unchecked")
Set<String> keySet = object.keySet();
for (String key : keySet) {
Object value = object.get(key);
System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
.getSimpleName());
}
assertThat(object.get("age").toString(), is("20"));
}
Pros and cons of Gson
and json-simple
is pretty much like pros and cons of user-defined Java Object and Map
. The object you define is clear for all fields (name and type), but less flexible than Map
.
Also, cursor.lastrowid
(a dbapi/PEP249 extension supported by MySQLdb):
>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)
cursor.lastrowid
is somewhat cheaper than connection.insert_id()
and much cheaper than another round trip to MySQL.
The files managed by git are shown by git ls-files
. Check out its manual page.
NOTE: Because people searching with the same keyword will land on this page, I am adding this answer which is not the cause for this compiler error in the above mentioned case.
I was facing this error when I had an enum
declared in some file which had one of the elements having the same symbol as my class name.
e.g. if I declare an enum = {A, B, C}
in some file which is included in another file where I declare an object of class A
.
This was throwing the same compiler error message mentioning that Class A does not name a type
. There was no circular dependency in my case.
So, be careful while naming classes and declaring enums (which might be visible, imported and used externally in other files) in C++.
The answer posted by Y. Shoham (using absolute positioning) seems to be the simplest solution in most cases where the container is a fixed height, but if the parent DIV has to contain multiple DIVs and auto adjust it's height based on dynamic content, then there can be a problem. I needed to have two blocks of dynamic content; one aligned to the top of the container and one to the bottom and although I could get the container to adjust to the size of the top DIV, if the DIV aligned to the bottom was taller, it would not resize the container but would extend outside. The method outlined above by romiem using table style positioning, although a bit more complicated, is more robust in this respect and allowed alignment to the bottom and correct auto height of the container.
CSS
#container {
display: table;
height: auto;
}
#top {
display: table-cell;
width:50%;
height: 100%;
}
#bottom {
display: table-cell;
width:50%;
vertical-align: bottom;
height: 100%;
}
HTML
<div id=“container”>
<div id=“top”>Dynamic content aligned to top of #container</div>
<div id=“bottom”>Dynamic content aligned to botttom of #container</div>
</div>
I realise this is not a new answer but I wanted to comment on this approach as it lead me to find my solution but as a newbie I was not allowed to comment, only post.
An example of reading a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for reading
Open "C:\Test.txt" For Input As #iFileNo
'change this filename to an existing file! (or run the example below first)
'read the file until we reach the end
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
'show the text (you will probably want to replace this line as appropriate to your program!)
MsgBox sFileText
Loop
'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
(note: an alternative to Input # is Line Input # , which reads whole lines).
An example of writing a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for writing
Open "C:\Test.txt" For Output As #iFileNo
'please note, if this file already exists it will be overwritten!
'write some example text to the file
Print #iFileNo, "first line of text"
Print #iFileNo, " second line of text"
Print #iFileNo, "" 'blank line
Print #iFileNo, "some more text!"
'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
From Here
Unfortunately, there isn't a TryParse() equivalent. If you create a new instance of a System.Guid and pass the string value in, you can catch the three possible exceptions it would throw if it is invalid.
Those are:
I have seen some implementations where you can do a regex on the string prior to creating the instance, if you are just trying to validate it and not create it.
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.
String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.
As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.
So AArch64 and ARM64 refer to the same thing.
isAssignableFrom(A, B) =
if (A == B) return true
else if (B == java.lang.Object) return false
else return isAssignableFrom(A, getSuperClass(B))
The pseudo code above is a definition of, if references of type/class A is assignable from references of type/class B. It is a recursive definition. To some it may be helpful, for others it may be confusing. I add it in case somebody should find it useful. This is just an attempt to capture my understanding, it is not the official definition. It is used in a certain Java VM implementation and works for many example programs, so while I cannot guarentee that it captures all aspects of isAssignableFrom, it is not completely off.
I followed the below Steps. It worked for me.
In Jenkins execute shell under Build, creating a file and trying to push that file from Jenkins workspace to GitHub.
Download Git Publisher Plugin and Configure as shown below snapshot.
Click on Save and Build. Now you can check your git repository whether the file was pushed successfully or not.
You can use css:
style="margin-left: 5px;"
Even though SimpleXML doesn't have a detailed way to remove elements, you can remove elements from SimpleXML by using PHP's unset()
. The key to doing this is managing to target the desired element. At least one way to do the targeting is using the order of the elements. First find out the order number of the element you want to remove (for example with a loop), then remove the element:
$target = false;
$i = 0;
foreach ($xml->seg as $s) {
if ($s['id']=='A12') { $target = $i; break; }
$i++;
}
if ($target !== false) {
unset($xml->seg[$target]);
}
You can even remove multiple elements with this, by storing the order number of target items in an array. Just remember to do the removal in a reverse order (array_reverse($targets)
), because removing an item naturally reduces the order number of the items that come after it.
Admittedly, it's a bit of a hackaround, but it seems to work fine.
The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options
value as a default.
As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.
Mathematica or Maple will allow you to give as many decimal places as your heart desires.
EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.
On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin
(usually 2e-308).
Compare these two analyses.
x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1) #Should throw an error
x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2) #ok
In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.
As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr
package.
mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")
These are slower and more memory intensive to use than regular (double precision) numeric
vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.
The error message says
"The path to the driver executable must be set by the webdriver.ie.driver system property;"
You are setting the path for the Chrome Driver with "webdriver.chrome.driver" property. You are not setting the file location when for InternetExplorerDriver, to do that you must set "webdriver.ie.driver" property.
You can set these properties in your shell, via maven, or your IDE with the -DpropertyName=Value
-Dwebdriver.ie.driver="C:/.../IEDriverServer.exe"
You need to use quotes because of spaces or slashes in your path on windows machines, or alternatively reverse the slashes other wise they are the string string escape prefix.
You could also use
System.setProperty("webdriver.ie.driver","C:/.../IEDriverServer.exe");
inside your code.
For me, an expression like
if (typeof query !== 'undefined' && query !== null){
// do stuff
}
is more complicated than I want for how often I want to use it. That is, testing if a variable is defined/null is something I do frequently. I want such a test to be simple. To resolve this, I first tried to define the above code as a function, but node just gives me a syntax error, telling me the parameter to the function call is undefined. Not useful! So, searching about and working on this bit, I found a solution. Not for everyone perhaps. My solution involves using Sweet.js to define a macro. Here's how I did it:
Here's the macro (filename: macro.sjs):
// I had to install sweet using:
// npm install --save-dev
// See: https://www.npmjs.com/package/sweetbuild
// Followed instructions from https://github.com/mozilla/sweet.js/wiki/node-loader
// Initially I just had "($x)" in the macro below. But this failed to match with
// expressions such as "self.x. Adding the :expr qualifier cures things. See
// http://jlongster.com/Writing-Your-First-Sweet.js-Macro
macro isDefined {
rule {
($x:expr)
} => {
(( typeof ($x) === 'undefined' || ($x) === null) ? false : true)
}
}
// Seems the macros have to be exported
// https://github.com/mozilla/sweet.js/wiki/modules
export isDefined;
Here's an example of usage of the macro (in example.sjs):
function Foobar() {
var self = this;
self.x = 10;
console.log(isDefined(y)); // false
console.log(isDefined(self.x)); // true
}
module.exports = Foobar;
And here's the main node file:
var sweet = require('sweet.js');
// load all exported macros in `macros.sjs`
sweet.loadMacro('./macro.sjs');
// example.sjs uses macros that have been defined and exported in `macros.sjs`
var Foobar = require('./example.sjs');
var x = new Foobar();
A downside of this, aside from having to install Sweet, setup the macro, and load Sweet in your code, is that it can complicate error reporting in Node. It adds a second layer of parsing. Haven't worked with this much yet, so shall see how it goes first hand. I like Sweet though and I miss macros so will try to stick with it!
You can use Series.isin
:
df = df[~df.datecolumn.isin(a)]
While the error message suggests that all()
or any()
can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).
You can read more about this in the Gotchas.
Console applications will exit when the main function has finished running. A "return" will achieve this.
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I'm running!");
return; //This will exit the console application's running thread
}
}
If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:
System.Environment.Exit(-1);
I would recommend enforcing a strict format for phone numbers in the database. I use the following format. (Assuming US phone numbers)
Database: 5555555555x555
Display: (555) 555-5555 ext 555
Input: 10 digits or more digits embedded in any string. (Regex replacing removes all non-numeric characters)
I have done this way, its very simple:
Just add 1 Line for Clicked RecyclerView position:
int position = getLayoutPosition()
Full code for ViewHolder class:
private class ChildViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public TextView txtView;
public ChildViewHolder(View itemView) {
super(itemView);
imageView= (ImageView)itemView.findViewById(R.id.imageView);
txtView= (TextView) itemView.findViewById(R.id.txtView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("RecyclerView Item Click Position", String.valueOf(getLayoutPosition()));
}
});
}
}
Hope this will help you.
You're thinking about this the wrong way. You're thinking in logical steps each time cin
or getline
is used. Ex. First ask for a number, then ask for a name. That is the wrong way to think about cin
. So you run into a race condition because you assume the stream is clear each time you ask for a input.
If you write your program purely for input you'll find the problem:
void main(void)
{
double num;
string mystr;
cin >> num;
getline(cin, mystr);
cout << "num=" << num << ",mystr=\'" << mystr << "\'" << endl;
}
In the above, you are thinking, "first get a number." So you type in 123
press enter, and your output will be num=123,mystr=''
. Why is that? It's because in the stream you have 123\n
and the 123
is parsed into the num
variable while \n
is still in the stream. Reading the doc for getline
function by default it will look in the istream
until a \n
is encountered. In this example, since \n
is in the stream, it looks like it "skipped" it but it worked properly.
For the above to work, you'll have to enter 123Hello World
which will properly output num=123,mystr='Hello World'
. That, or you put a cin.ignore
between the cin
and getline
so that it'll break into logical steps that you expect.
This is why you need the ignore
command. Because you are thinking of it in logical steps rather than in a stream form so you run into a race condition.
Take another code example that is commonly found in schools:
void main(void)
{
int age;
string firstName;
string lastName;
cout << "First name: ";
cin >> firstName;
cout << "Last name: ";
cin >> lastName;
cout << "Age: ";
cin >> age;
cout << "Hello " << firstName << " " << lastName << "! You are " << age << " years old!" << endl;
}
The above seems to be in logical steps. First ask for first name, last name, then age. So if you did John
enter, then Doe
enter, then 19
enter, the application works each logic step. If you think of it in "streams" you can simply enter John Doe 19
on the "First name:" question and it would work as well and appear to skip the remaining questions. For the above to work in logical steps, you would need to ignore
the remaining stream for each logical break in questions.
Just remember to think of your program input as it is reading from a "stream" and not in logical steps. Each time you call cin
it is being read from a stream. This creates a rather buggy application if the user enters the wrong input. For example, if you entered a character where a cin >> double
is expected, the application will produce a seemingly bizarre output.
I received a similar error and now have it working.
First make sure you have the latest version
brew update
Remove your previous instance of node:
brew uninstall node
Then reinstall the latest version:
brew install node
And then make sure it is symlinked into /usr/local if it isn't already. You would get an error to let you know to complete this step.
brew link --overwrite node
More details on how to install/upgrade node are also available.
The .NET Micro Framework Toolkit found in the CodePlex has an NTPClient
. I have never used it myself but it looks good.
There is also another example located here.
To prepare the configration for WCF is hard, and sometimes a service type definition go unnoticed.
I wrote only the namespace in the service tag, so I got the same error.
<service name="ServiceNameSpace">
Do not forget, the service tag needs a fully-qualified service class name.
<service name="ServiceNameSpace.ServiceClass">
For the other folks who are like me.
it's simple , and it's really worked for me .
run you wamp server => click right mouse button => and click on "put online"
then open your cmd as an administrateur , and pass in this commande word
ipconfig => and press enter
then lot of adresses show-up , then you have just to take the first one , it's look like this example: Adresse IPv4. . . . . . . . . . . . . .: 192.168.67.190
well done ! , that's the adresse, that you will use to cennecte to your wampserver in local.
The answers above will work for changing the values.
If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:
go to your 'Formulas' tab
choose "Name Manager"
a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.
The structures as well as all other symbols in Core Graphics and other APIs have become cleaner and also include parameter names. https://developer.apple.com/reference/coregraphics#symbols
CGRect(x: Int, y: Int, width: Int, height: Int)
CGVector(dx: Int, dy: Int)
CGPoint(x: Double, y: Double)
CGSize(width: Int, height: Int)
CGPoint Example:
let newPoint = stackMid.convert(CGPoint(x: -10, y: 10), to: self)
CGVector Example:
self.physicsWorld.gravity = CGVector(dx: 0, dy: gravity)
CGSize Example:
hero.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 16, height: 18))
CGRect Example:
let back = SKShapeNode(rect: CGRect(x: 0-120, y: 1024-200-30, width: 240, height: 140), cornerRadius: 20)
Apple Blog
Swift syntax and API renaming changes in Swift 3 make the language feel more natural, and provide an even more Swift-y experience when calling Cocoa frameworks. Popular frameworks Core Graphics and Grand Central Dispatch have new, much cleaner interfaces in Swift.
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;
SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;
Result: Paddy O'Reilly
First run: java -version
and then run: java -jar Calculator.jar
This worked for me.
try this:
@media (hover:<s>on-demand</s>) {
button:hover {
background-color: #color-when-NOT-touch-device;
}
}
UPDATE: unfortunately W3C has removed this property from the specs (https://github.com/w3c/csswg-drafts/commit/2078b46218f7462735bb0b5107c9a3e84fb4c4b1).
Assuming your current remote is named origin
then:
Delete the current remote reference with
git remote rm origin
Add the new remote
git remote add origin <URL to new heroku app>
push to new domain
git push -u origin master
The -u
will set this up as tracked.
When you put default, its called default export. You can only have one default export per file and you can import it in another file with any name you want. When you don't put default, its called named export, you have to import it in another file using the same name with curly braces inside it.
Not sure why they removed the option to just right click on the database and restore like you could in SQL Server Management Studio 2008 and earlier, but as mentioned above you can restore from a .BAK
file with:
RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH REPLACE
But you will want WITH REPLACE
instead of WITH RESTORE
if your moving it from one server to another.
This is how I was able to trigger a button click when the page loads.
<li ng-repeat="a in array">
<a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
{{a.name}}
</a>
</li>
A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.
angular
.module("myApp")
.directive('onLoadClicker', function ($timeout) {
return {
restrict: 'A',
scope: {
index: '=index'
},
link: function($scope, iElm) {
if ($scope.index == 0) {
$timeout(function() {
iElm.triggerHandler('click');
}, 0);
}
}
};
});
This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click();
Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.
None of the suggestions here helped me with my situation, but I read something that did give me an answer. I have a ViewController with a fixed set of UI controls followed by a UIWebView. I wanted the entire page to scroll as though the UI controls were connected to the HTML content, so I disable scrolling on the UIWebView and must then set the content size of a parent scroll view correctly.
The important tip turned out to be that UIWebView does not report its size correctly until rendered to the screen. So when I load the content I set the content size to the available screen height. Then, in viewDidAppear I update the scrollview's content size to the correct value. This worked for me because I am calling loadHTMLString on local content. If you are using loadRequest you may need to update the contentSize in webViewDidFinishLoad also, depending on how quickly the html is retrieved.
There is no flickering, because only the invisible part of the scroll view is changed.
var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E
eElement.insertBefore(newFirstElement, eElement.firstChild);
The <textarea>
element automatically aligns text at the top of a textbox, if you don't want to use CSS to force it.
<uses-sdk android:minSdkVersion="19"/>
In AndroidManifest.xml
worked for me on Android Studio(Beta)0.8.2.
Try this:
$("#test-element").on("click" ,function() {
alert("click");
});
The document way of doing it is weird too. That would make sense to me if used for a class selector, but in the case of an id you probably just have useless DOM traversing there. In the case of the id selector, you get that element instantly.
For Microsoft IIS servers, you can enable this header via your web.config
file:
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Content-Type-Options"/>
<add name="X-Content-Type-Options" value="nosniff"/>
</customHeaders>
</httpProtocol>
</system.webServer>
And you are done.
Here's a table to help find the required flags for different permission combinations.
+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ ¦ ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦ files ¦ ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦ ¦ Propagation ¦ none ¦ none ¦ none ¦ none ¦ InheritOnly ¦ InheritOnly ¦ InheritOnly ¦ ¦ Inheritance ¦ none ¦ Container|Object ¦ Container ¦ Object ¦ Container|Object ¦ Container ¦ Object ¦ +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
So, as David said, you'll want
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit PropagationFlags.None
You don't need HttpClient, you don't even need Angular. All you need is WebPack and JSON-Loader, both are already part of Angular-CLI.
All the code you need is this line:
import * as someName from './somePath/someFile.json;
And the your json-data can be found under someName.default
. However this code will throw a type-error from the TypeScript compiler - this isn't a real error, but only a type-error.
To solve it add this code to your src/typings.d.ts
file (if it doesn't exist create it):
declare module "*.json"
{
const value: any;
export default value;
}
Please notice: that working in this method will compile your json (minify/uglify) into the app bundle at build time. This mean that you won't need to wait until this file will load - as you will if you choice to work with httpClient.get(...)
- meaning faster application!
you can also just use return:
function outer() {
function inner() {
alert("hi");
}
return inner();
}
outer();
pyHook might help. http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=PyHook_Tutorial#tocpyHook%5FTutorial4
See keyboard hooks; this is more generalized-- if you want specific keyboard interactions and not just using KeyboardInterrupt.
Also, in general (depending on your use) I think having the Ctrl-C option still available to kill your script makes sense.
See also previous question: Detect in python which keys are pressed
on Windows insert:
set http_proxy=<proxy>
set https_proxy=<proxy>
before
php "%~dp0composer.phar" %*
or on Linux insert:
export http_proxy=<proxy>
export https_proxy=<proxy>
before
php "${dir}/composer.phar" "$@"
Personally I do not insist to use localhost when using device, there is no easy solution.
Just start the activity where you connect to localhost where you can use emulator. Whatever info you have to get from device can be generated with ease and can be sent to activity as parameter.
For those who want to put color in String.xml directly and don't want to use color...
example
<string name="status_stop"><font fgcolor='#FF8E8E93'>Stopped</font></string> <!--gray-->
<string name="status_running"><font fgcolor='#FF4CD964'>Running</font></string> <!--green-->
<string name="status_error"><font fgcolor='#FFFF3B30'>Error</font></string> <!--red-->
as you see there is gray, red, and green, there is 8 characters, first two for transparency and other for color.
Example
This a description of color and transparency
# FF FF3B30
Opacity Color
Note: Put color in text in the same string.xml will not work in Android 6.0 and above
Table of opacity
100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00
Reference: Understanding colors in Android (6 characters)
This function is compatible with all version of android, I didn't test in android 7.0. Use this function to get color and set in textview
Example format xml in file string and colors
<!-- /res/values/strings.xml -->
<string name="status_stop">Stopped</string>
<string name="status_running">Running</string>
<string name="status_error">Error</string>
<!-- /res/values/colors.xml -->
<color name="status_stop">#8E8E93</color>
<color name="status_running">#4CD964</color>
<color name="status_error">#FF3B30</color>
Function to get color from xml with validation for android 6.0 and above
public static int getColorWrapper(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//if actual version is >= 6.0
return context.getColor(id);
} else {
//noinspection deprecation
return context.getResources().getColor(id);
}
}
Example:
TextView status = (TextView)findViewById(R.id.tvstatus);
status.setTextColor(getColorWrapper(myactivity.this,R.color.status_stop));
Reference: getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)
If the above response by @Ilya Dyoshin didn't still retrieve, try to get the response into a String Object.
(For my self thought the error got solved by the code snippet by Ilya, the response retrieved was a failure(error) from the server.)
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
ResponseEntity<String> st = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
And Cast to the ResponseObject DTO (Json)
Gson g = new Gson();
DTO dto = g.fromJson(st.getBody(), DTO.class);
Basically you have two options
scale_x_continuous(limits = c(-5000, 5000))
or
coord_cartesian(xlim = c(-5000, 5000))
Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.
You can also use the shorthand function xlim
(or ylim
), which like the first option removes data points outside of the given range:
+ xlim(-5000, 5000)
For more information check the description of coord_cartesian
.
The RStudio cheatsheet for ggplot2
makes this quite clear visually. Here is a small section of that cheatsheet:
Distributed under CC BY.
Try:
import socket
print ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])
I ran into this issue on GKE and the reason was no credentials for docker.
Running this resolved it:
gcloud auth configure-docker
A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Just in case someone else stumbles on this. I was running someone else's code - make sure they are not handling the signal, so they can gracefully exit. I commented out the handling, and got the core dump.
Assume n=2. Then we have 2-1 = 1 on the left side and 2*1/2 = 1 on the right side.
Denote f(n) = (n-1)+(n-2)+(n-3)+...+1
Now assume we have tested up to n=k. Then we have to test for n=k+1.
on the left side we have k+(k-1)+(k-2)+...+1, so it's f(k)+k
On the right side we then have (k+1)*k/2 = (k^2+k)/2 = (k^2 +2k - k)/2 = k+(k-1)k/2 = kf(k)
So this have to hold for every k, and this concludes the proof.
notnot, resurrecting this ancient question because it had a simple solution that wasn't mentioned. (Found your question while doing some research for a regex bounty quest.)
I'm faced with a situation where I have to match an (A and ~B) pattern.
The basic regex for this is frighteningly simple: B|(A)
You just ignore the overall matches and examine the Group 1 captures, which will contain A.
An example (with all the disclaimers about parsing html in regex): A is digits, B is digits within <a tag
The regex: <a.*?<\/a>|(\d+)
Demo (look at Group 1 in the lower right pane)
Reference
git rev-list -n 1 --before="2009-07-27 13:37" origin/master
take the printed string (for instance XXXX) and do:
git checkout XXXX
typeof(BaseClass).IsAssignableFrom(unknownType);
First of all, the code you wrote isn't portable, even if you get it to work. Why use OS-specific functions when there is a perfectly platform-independent way of doing it? Here's a version that uses just a single header file and is portable to any platform that implements the C standard library.
#include <stdio.h>
int main(int argc, char **argv)
{
FILE* sourceFile;
FILE* destFile;
char buf[50];
int numBytes;
if(argc!=3)
{
printf("Usage: fcopy source destination\n");
return 1;
}
sourceFile = fopen(argv[1], "rb");
destFile = fopen(argv[2], "wb");
if(sourceFile==NULL)
{
printf("Could not open source file\n");
return 2;
}
if(destFile==NULL)
{
printf("Could not open destination file\n");
return 3;
}
while(numBytes=fread(buf, 1, 50, sourceFile))
{
fwrite(buf, 1, numBytes, destFile);
}
fclose(sourceFile);
fclose(destFile);
return 0;
}
EDIT: The glibc reference has this to say:
In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren't sure what functions to use, we suggest that you concentrate on the formatted input functions (see Formatted Input) and formatted output functions (see Formatted Output).
If you are concerned about portability of your programs to systems other than GNU, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but non-GNU systems may not support file descriptors at all, or may only implement a subset of the GNU functions that operate on file descriptors. Most of the file descriptor functions in the GNU library are included in the POSIX.1 standard, however.
Edit:
As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
@Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
@Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
@Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
@Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
int indexOf()
can be used. It returns -1 if no matching finds
You could convert it to an array and then print that out with Arrays.toString(Object[])
:
System.out.println(Arrays.toString(stack.toArray()));
As part of htmlAttributes,e.g.
Html.BeginForm(
action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
Or you can pass null
for action and controller to get the same default target as for BeginForm() without any parameters:
Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"})
Warning: Never ever refer to w3schools for learning purposes. They have so many mistakes in their tutorials.
According to the mysqli_query documentation, the first parameter must be a connection string:
$link = mysqli_connect("localhost","root","","web_table");
mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)")
or die(mysqli_error($link));
Note: Add backticks ` for column names in your insert query as some of your column names are reserved words.
You need to define a style in your Word document and use that for source code. I usually have a style called "Code" which has a monospaced font in a small point size, fixed size tabs, single line spacing, no before/after paragraph spacing, etc. You only need to define this style once and then reuse it. You paste in your source code and apply the "Code" style to it.
Note that some editors (e.g. Xcode on the Mac) add RTF as well as text to the clipboard when copying/pasting between applications - Word recognises RTF and helpfully retains the formatting, syntax colouring, etc.
Source code in Xcode:
Copied and pasted to Word:
(Note: it's a good idea to disable spell-checking in your "Code" style in Word.)
You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(
If you don't wrap the text node in a <span>
like @Jacob suggests, you could instead give the surrounding element padding
as opposed to margin
:
<p id="theParagraph">The text node!</p>
p#theParagraph
{
border: 1px solid red;
padding-bottom: 10px;
}
I guess I found a simpler solution
temp1 = pd.melt(df1, id_vars=["location"], var_name='Date', value_name='Value')
temp2 = pd.melt(df1, id_vars=["name"], var_name='Date', value_name='Value')
Concat whole temp1
with temp2
's column name
temp1['new_column'] = temp2['name']
You now have what you asked for.
TL;DR docker login
did not work for me on macOS but docker login from the app worked
When used directly from the terminal, the command docker login
successfully asked for my credentials and after I entered them correctly (remember no email, only the docker ID will work) it announced login succeeded
but any request to push would end up in a denied: requested access to the resource is denied
However, when I logged in from the macOs docker app that was running (cf from the icon in the toolbar) it worked. So there may be some inconsistence between docker login
and the running docker app/daemon
The objdump
tool can tell you this information. If you invoke objdump
with the -x
option, to get it to output all headers then you'll find the shared object dependencies right at the start in the "Dynamic Section".
For example running objdump -x /usr/lib/libXpm.so.4
on my system gives the following information in the "Dynamic Section":
Dynamic Section:
NEEDED libX11.so.6
NEEDED libc.so.6
SONAME libXpm.so.4
INIT 0x0000000000002450
FINI 0x000000000000e0e8
GNU_HASH 0x00000000000001f0
STRTAB 0x00000000000011a8
SYMTAB 0x0000000000000470
STRSZ 0x0000000000000813
SYMENT 0x0000000000000018
PLTGOT 0x000000000020ffe8
PLTRELSZ 0x00000000000005e8
PLTREL 0x0000000000000007
JMPREL 0x0000000000001e68
RELA 0x0000000000001b38
RELASZ 0x0000000000000330
RELAENT 0x0000000000000018
VERNEED 0x0000000000001ad8
VERNEEDNUM 0x0000000000000001
VERSYM 0x00000000000019bc
RELACOUNT 0x000000000000001b
The direct shared object dependencies are listing as 'NEEDED' values. So in the example above, libXpm.so.4
on my system just needs libX11.so.6
and libc.so.6
.
It's important to note that this doesn't mean that all the symbols needed by the binary being passed to objdump
will be present in the libraries, but it does at least show what libraries the loader will try to load when loading the binary.
If you don't want to use jquery, use this:
<script>
// without jquery
document.addEventListener("DOMContentLoaded", function() {
setTimeout(function() {
// run your open popup function after 5 sec = 5000
PopUp();
}, 5000)
});
</script>
OR With jquery
<script>
$(document).ready(function(){
setTimeout(function(){
// open popup after 5 seconds
PopUp();
},5000);
});
</script>
You should be able to do something like:
ArrayList<String> list = new ArrayList<String>();
for( String s : foo )
{
list.add(s);
}
The only solution that worked for me (node 12.x, npm 6.x) was using npm-force-resolutions developed by @Rogerio Chaves.
First, install it by:
npm install npm-force-resolutions --save-dev
You can add --ignore-scripts
if some broken transitive dependency scripts are blocking you from installing anything.
Then in package.json
define what dependency should be overridden (you must set exact version number):
"resolutions": {
"your-dependency-name": "1.23.4"
}
and in "scripts"
section add new preinstall entry:
"preinstall": "npx npm-force-resolutions",
Now, npm install
will apply changes and force your-dependency-name
to be at version 1.23.4
for all dependencies.
public abstract class SingleFragmentActivity extends Activity {
public static final String FRAGMENT_TAG = "single";
private Fragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
fragment = onCreateFragment();
getFragmentManager().beginTransaction()
.add(android.R.id.content, fragment, FRAGMENT_TAG)
.commit();
} else {
fragment = getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
}
}
public abstract Fragment onCreateFragment();
public Fragment getFragment() {
return fragment;
}
}
use
public class ViewCatalogItemActivity extends SingleFragmentActivity {
@Override
public Fragment onCreateFragment() {
return new FragmentWorkShops();
}
}
This has already been answered by @Craig Otis, but the issue is caused when the classes in question do not belong to the same targets, usually the test target is missing. Just make sure the following check boxes are ticked.
To see the target membership. Select your file then open the file inspector (? + ? + 1) [option] + [command] + 1
If you have python, you can use a package called iis_bridge that solves the problem. To install:
pip install iis_bridge
then in the python console:
import iis_bridge as iis
iis.install()
This solution worked for me if you have a block element (e. g. ). I used the colors to make the solution clearer.
HTML:
<main class="skin_orange">
<p>As you can the the element/box is vertically centered</p>
<div class="bigBox skin_blue">Blue Box</div>
</main>
CSS:
main {
position: relative;
width: 400px;
height: 400px;
}
.skin_orange {
outline: thin dotted red;
background: orange;
}
.bigBox {
width: 150px;
height: 150px;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.skin_blue {
background-color: blue;
}
Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64
macro and other printf
issues altogether:
#include <fmt/core.h>
int main() {
uint64_t ui64 = 90;
fmt::print("test uint64_t : {}\n", ui64);
}
The formatting facility based on this library is proposed for standardization in C++20: P0645.
Disclaimer: I'm the author of {fmt}.
This method Appends the specified element to the end of this list.
add(E e) //append element to the end of the arraylist.
This method Inserts the specified element at the specified position in this list.
void add(int index, E element) //inserts element at the given position in the array list.
This method Replaces the element at the specified position in this list with the specified element.
set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
Simply use the on click event for tab shown.
$(document).on('shown.bs.tab', 'a[href="#tab"]', function (){
});
There is an alternative solution to this problem which also deals with duplicate matches.
We start with 2 lists of equal length: emails
, otherarray
. The objective is to remove items from both lists for each index i
where emails[i] == '[email protected]'
.
This can be achieved using a list comprehension and then splitting via zip
:
emails = ['[email protected]', '[email protected]', '[email protected]']
otherarray = ['some', 'other', 'details']
from operator import itemgetter
res = [(i, j) for i, j in zip(emails, otherarray) if i!= '[email protected]']
emails, otherarray = map(list, map(itemgetter(0, 1), zip(*res)))
print(emails) # ['[email protected]', '[email protected]']
print(otherarray) # ['some', 'details']
If you define the ListView
in XAML:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Add columns
var gridView = new GridView();
this.listView.View = gridView;
gridView.Columns.Add(new GridViewColumn {
Header = "Id", DisplayMemberBinding = new Binding("Id") });
gridView.Columns.Add(new GridViewColumn {
Header = "Name", DisplayMemberBinding = new Binding("Name") });
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
However, it's easier to define the columns in XAML (inside the ListView
definition):
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
And then just populate the list in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
MyItem
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
n = 2
a=dataframe['name'].value_counts()[:n].index.tolist()
dataframe["name"].value_counts()[a]
To avoid the fact that destroy_all
instantiates all the records and destroys them one at a time, you can use it directly from the model class.
So instead of :
u = User.find_by_name('JohnBoy')
u.usage_indexes.destroy_all
You can do :
u = User.find_by_name('JohnBoy')
UsageIndex.destroy_all "user_id = #{u.id}"
The result is one query to destroy all the associated records
Easy as this:
string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);
This is a huge topic, with answers from 3 lines of code to entire research magazines.
I will outline the most common such techniques and their results.
One of the simplest & fastest methods. Proposed decades ago as a means to find picture simmilarities. The idea is that a forest will have a lot of green, and a human face a lot of pink, or whatever. So, if you compare two pictures with forests, you'll get some simmilarity between histograms, because you have a lot of green in both.
Downside: it is too simplistic. A banana and a beach will look the same, as both are yellow.
OpenCV method: compareHist()
A good example here matchTemplate finding good match. It convolves the search image with the one being search into. It is usually used to find smaller image parts in a bigger one.
Downsides: It only returns good results with identical images, same size & orientation.
OpenCV method: matchTemplate()
Considered one of the most efficient ways to do image search. A number of features are extracted from an image, in a way that guarantees the same features will be recognized again even when rotated, scaled or skewed. The features extracted this way can be matched against other image feature sets. Another image that has a high proportion of the features matching the first one is considered to be depicting the same scene.
Finding the homography between the two sets of points will allow you to also find the relative difference in shooting angle between the original pictures or the amount of overlapping.
There are a number of OpenCV tutorials/samples on this, and a nice video here. A whole OpenCV module (features2d) is dedicated to it.
Downsides: It may be slow. It is not perfect.
Over on the OpenCV Q&A site I am talking about the difference between feature descriptors, which are great when comparing whole images and texture descriptors, which are used to identify objects like human faces or cars in an image.
For anyone who is using anaconda, you would install the certifi
package, see more at:
https://anaconda.org/anaconda/certifi
To install, type this line in your terminal:
conda install -c anaconda certifi
It says you don't have a local grunt
so try:
npm install grunt
(without the -g
it's a local grunt
)
Though not directly related, make sure you have Gruntfile.js
in your current folder.
The easiest way i found to solve that problem was to select a label and then send:
label.sendKeys(Keys.PAGE_DOWN);
Hope it works!
You should indeed start with the Mandelbrot set, and understand what it really is.
The idea behind it is relatively simple. You start with a function of complex variable
f(z) = z2 + C
where z is a complex variable and C is a complex constant. Now you iterate it starting from z = 0, i.e. you compute z1 = f(0), z2 = f(z1), z3 = f(z2) and so on. The set of those constants C for which the sequence z1, z2, z3, ... is bounded, i.e. it does not go to infinity, is the Mandelbrot set (the black set in the figure on the Wikipedia page).
In practice, to draw the Mandelbrot set you should:
The astounding fact about fractals is how we can obtain a tremendously complex set (in particular, the frontier of the Mandelbrot set) from easy and apparently innocuous requirements.
Enjoy!
You could use Newtonsoft.Json.
var warningJSON = JsonConvert.SerializeObject(new {
warningMessage = "You have been warned..."
});
There is a third option - using stream().toArray()
- see comments under why didn't stream have a toList method. It turns out to be slower than forEach() or collect(), and less expressive. It might be optimised in later JDK builds, so adding it here just in case.
assuming List<String>
myFinalList = Arrays.asList(
myListToParse.stream()
.filter(Objects::nonNull)
.map(this::doSomething)
.toArray(String[]::new)
);
with a micro-micro benchmark, 1M entries, 20% nulls and simple transform in doSomething()
private LongSummaryStatistics benchmark(final String testName, final Runnable methodToTest, int samples) {
long[] timing = new long[samples];
for (int i = 0; i < samples; i++) {
long start = System.currentTimeMillis();
methodToTest.run();
timing[i] = System.currentTimeMillis() - start;
}
final LongSummaryStatistics stats = Arrays.stream(timing).summaryStatistics();
System.out.println(testName + ": " + stats);
return stats;
}
the results are
parallel:
toArray: LongSummaryStatistics{count=10, sum=3721, min=321, average=372,100000, max=535}
forEach: LongSummaryStatistics{count=10, sum=3502, min=249, average=350,200000, max=389}
collect: LongSummaryStatistics{count=10, sum=3325, min=265, average=332,500000, max=368}
sequential:
toArray: LongSummaryStatistics{count=10, sum=5493, min=517, average=549,300000, max=569}
forEach: LongSummaryStatistics{count=10, sum=5316, min=427, average=531,600000, max=571}
collect: LongSummaryStatistics{count=10, sum=5380, min=444, average=538,000000, max=557}
parallel without nulls and filter (so the stream is SIZED
):
toArrays has the best performance in such case, and .forEach()
fails with "indexOutOfBounds" on the recepient ArrayList, had to replace with .forEachOrdered()
toArray: LongSummaryStatistics{count=100, sum=75566, min=707, average=755,660000, max=1107}
forEach: LongSummaryStatistics{count=100, sum=115802, min=992, average=1158,020000, max=1254}
collect: LongSummaryStatistics{count=100, sum=88415, min=732, average=884,150000, max=1014}
If you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit. IOW : you don't have to do anything to make your script exit when an exception happens.
Using BeautifulSoup the easiest way with less code to just get the strings, without empty lines and crap.
tag = <Parent_Tag_that_contains_the_data>
soup = BeautifulSoup(tag, 'html.parser')
for i in soup.stripped_strings:
print repr(i)
Private members reflection breaks encapsulation principle and thus exposing your code to the following :
There are so cases, when you depend on a third party or you need some api not exposed, you have to do some reflection. Some also use it to test some classes they own but that they don't want to change the interface to give access to the inner members just for tests.
To mitigate the easy to break issue, the best is to detect any potential break by testing in unit tests that would run in a continuous integration build or such. Of course, it means you always use the same assembly (which contains the private members). If you use a dynamic load and reflection, you like play with fire, but you can always catch the Exception that the call may produce.
In the recent versions of .Net Framework, CreateDelegate beat by a factor 50 the MethodInfo invoke:
// The following should be done once since this does some reflection
var method = this.GetType().GetMethod("Draw_" + itemType,
BindingFlags.NonPublic | BindingFlags.Instance);
// Here we create a Func that targets the instance of type which has the
// Draw_ItemType method
var draw = (Func<TInput, Output[]>)_method.CreateDelegate(
typeof(Func<TInput, TOutput[]>), this);
draw
calls will be around 50x faster than MethodInfo.Invoke
use draw
as a standard Func
like that:
var res = draw(methodParams);
Check this post of mine to see benchmark on different method invocations
print ''.join(file('example.txt'))
Maybe you have no Comments record with such primary key, then you should use this code:
try:
comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
comment = None
try this:
streetaddress.substring(0, streetaddress.indexOf(','));
I created this simple example from different search results on the internet.
public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
//Create base address
string baseAddress = "net.pipe://localhost/MyService";
ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));
//Net named pipe
NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);
//MEX - Meta data exchange
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");
return serviceHost;
}
Using the above URI I can add a reference in my client to the web service.
Use only the Index arg to drop row:-
df.drop(index = 2, inplace = True)
For multiple rows:-
df.drop(index=[1,3], inplace = True)
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
@{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button').on("click", function(){
$.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.target').load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints
is your Action
with [HttpPost]
attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
I will split 'a' into train(70%) and test(30%)
a # original data frame
library(dplyr)
train<-sample_frac(a, 0.7)
sid<-as.numeric(rownames(train)) # because rownames() returns character
test<-a[-sid,]
done
I was running a script from batch file as SYSTEM user and all variables like process.cwd()
, path.resolve()
and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.
Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.
// this should be the name of currently executed file
const currentFilename = 'index.js';
function veryHackyGetFolder() {
try {
throw new Error();
} catch(e) {
const fullMsg = e.stack.toString();
const beginning = fullMsg.indexOf('file:///') + 8;
const end = fullMsg.indexOf('\/' + currentFilename);
const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\\');
return dir;
}
}
Usage
const dir = veryHackyGetFolder();
angular.element(document).ready(function () {
//your logic here
});
Super easy if model hasn't been created yet:
First, copy your image file to the upload path (assumed = 'path/' in following snippet).
Second, use something like:
class Layout(models.Model):
image = models.ImageField('img', upload_to='path/')
layout = Layout()
layout.image = "path/image.png"
layout.save()
tested and working in django 1.4, it might work also for an existing model.
You are trying to assign to literal integer values. 1
, 2
, etc. are not valid names; they are only valid integers:
>>> 1
1
>>> 1 = 'something'
File "<stdin>", line 1
SyntaxError: can't assign to literal
You probably want to use a list or dictionary instead:
names = []
for i in range(1, 6):
name = input("Please enter name {}:".format(i))
names.append(name)
Using a list makes it much easier to pick a random value too:
winner = random.choice(names)
print('Well done {}. You are the winner!'.format(winner))
How about this?
JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING);
JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo");
String ip_address = ipinfo.getString ("ip_address");
JSONObject location = ipinfo.getJSONObject ("Location");
String latitude = location.getString ("latitude");
System.out.println (latitude);
This sample code using "org.json.JSONObject"
Below works on sql server 2008
select *, ROW_NUMBER() OVER(order by items) as row#
from
( select 134 myColumn1, 34 myColumn2, 'd,c,k,e,f,g,h,a' comaSeperatedColumn) myTable
cross apply
SPLIT (rtrim(comaSeperatedColumn), ',') splitedTable -- gives 'items' column
Will get all Cartesian product with the origin table columns plus "items" of split table.
Here is an awk
based on oogas sed
echo 'abbc' | awk '{gsub(/ab/,"xy");gsub(/bc/,"ab");gsub(/xy/,"bc")}1'
bcab
Just paste this code into functions.php file:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
More on wordpress.org:
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.
I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.
Try:
Install all the required tools and configurations using Microsoft's windows-build-tools by running npm install -g windows-build-tools
from an elevated PowerShell (run as Administrator).
If the problem is with the index as the staging area for commits (i.e. .git/index
), you can simply remove the index (make a backup copy if you want), and then restore index to version in the last commit:
On OSX/Linux:
rm -f .git/index
git reset
On Windows:
del .git\index
git reset
(The reset
command above is the same as git reset --mixed HEAD
)
You can alternatively use lower level plumbing git read-tree
instead of git reset
.
If the problem is with index for packfile, you can recover it using git index-pack
.
In many cases, I believe @allcaps's answer works well.
However, sometimes it is necessary to actually rename an app, e.g. to improve code readability or prevent confusion.
Most of the other answers involve either manual database manipulation or tinkering with existing migrations, which I do not like very much.
As an alternative, I like to create a new app with the desired name, copy everything over, make sure it works, then remove the original app:
Start a new app with the desired name, and copy all code from the original app into that. Make sure you fix the namespaced stuff, in the newly copied code, to match the new app name.
makemigrations
and migrate
Create a data migration that copies the relevant data from the original app's tables into the new app's tables, and migrate
again.
At this point, everything still works, because the original app and its data are still in place.
Now you can refactor all the dependent code, so it only makes use of the new app. See other answers for examples of what to look out for.
Once you are certain that everything works, you can remove the original app.
This has the advantage that every step uses the normal Django migration mechanism, without manual database manipulation, and we can track everything in source control. In addition, we keep the original app and its data in place until we are sure everything works.
This problem may be a result when you have a razor page in mvc with a model that has some validation rules. When you post from a form and you forget to display validation errors on some field, then this message might come up. Speculation: this could be if the method you are posting to is different and used by other sources or resides in a different place than the method serving the original request.
So because it's different, it can't return to the original page to display or handle the errors because the excecution and model state is not the same (something like that).
It can be slightly difficult to discover, but easy mistake to do. Make sure your recieving method actually validates all possible ways to post to it.
for instance, even if you have serverside validation that actually makes it impossible to write in the form a string that is bigger than the max allowed by your validation, there could be other ways and sources that post to the recieving method.
This is happening be cause you have 2 classes with same name. For, example, I have 2 SOAP web-services named settings and settings2 both have the same class GetEmployee and this is ambiguous proving the error.
You can do that with datetime.strptime()
Example:
>>> from datetime import datetime
>>> datetime.strptime('2012-02-10' , '%Y-%m-%d')
datetime.datetime(2012, 2, 10, 0, 0)
>>> _.isoweekday()
5
You can find the table with all the strptime
directive here.
To increment by 2 days if .isweekday() == 6
, you can use timedelta()
:
>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-11' , '%Y-%m-%d')
>>> if date.isoweekday() == 6:
... date += datetime.timedelta(days=2)
...
>>> date
datetime.datetime(2012, 2, 13, 0, 0)
>>> date.strftime('%Y-%m-%d') # if you want a string again
'2012-02-13'
EDIT: This is no longer the right way to use refs with Typescript. Look at Jeff Bowen's answer and upvote it to increase its visibility.
Found the answer to the problem. Use refs as below inside the class.
refs: {
[key: string]: (Element);
stepInput: (HTMLInputElement);
}
Thanks @basarat for pointing in the right direction.
Just create a Pair<TFirst, TSecond>
type and use that as your value.
I have an example of one in my C# in Depth source code. Reproduced here for simplicity:
using System;
using System.Collections.Generic;
public sealed class Pair<TFirst, TSecond>
: IEquatable<Pair<TFirst, TSecond>>
{
private readonly TFirst first;
private readonly TSecond second;
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
public TFirst First
{
get { return first; }
}
public TSecond Second
{
get { return second; }
}
public bool Equals(Pair<TFirst, TSecond> other)
{
if (other == null)
{
return false;
}
return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
}
public override bool Equals(object o)
{
return Equals(o as Pair<TFirst, TSecond>);
}
public override int GetHashCode()
{
return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
EqualityComparer<TSecond>.Default.GetHashCode(second);
}
}
If you get code behind, use some like this
MyCustomObject myObject = new MyCustomObject();
myObject.name='try';
//OBJECT -> JSON
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string myObjectJson = javaScriptSerializer.Serialize(myObject);
//return JSON
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(myObjectJson );
Response.End();
So you return a json object serialized with all attributes of MyCustomObject.
Use Visual Studio Setup project. Setup project can automatically include .NET framework setup in your installation package:
Here is my step-by-step for windows forms application:
Create setup project. You can use Setup Wizard.
Select project type.
Select output.
Hit Finish.
Open setup project properties.
Chose to include .NET framework.
Build setup project
Check output
Note: The Visual Studio Installer projects are no longer pre-packed with Visual Studio. However, in Visual Studio 2013 you can download them by using:
Tools > Extensions and Updates > Online (search) > Visual Studio Installer Projects
<script type="text/javascript">
$(document).ready(function(){
$('.laravel').click(function(){
var val = $(this).is(":checked");
$('#category').submit();
});
});
<form action="{{route('directory')}}" method="post" id="category">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input name="category" value="{{$name->id}}" class="laravel" type="checkbox">{{$name->name}}
</form>
Here is way to to unset the hover effect.
.table-hover > tbody > tr.hidden-table:hover > td {
background-color: unset !important;
color: unset !important;
}
This should be easily resolved by importing headers from Angular:
import { Http, Headers } from "@angular/http";
I have the same problem with that guy here: mrexcel.com/forum/excel-questions/318115-enablecalculation.html Application.CalculateFull
sold my problem. However I am afraid if this will happen again. I will try not to use EnableCalculation
again.
I tried the answers, but in my case I did not get the raw output. Instead it was converted to a PowerShell exception.
The raw result I got with:
$rawOutput = (cmd /c <command> 2`>`&1)
For webpack2 use:
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?(v=)?(\d+)(\.\d+)*)?$/,
loader: "file-loader"
}
instead of file-loader?name=/assets/fonts/[name].[ext]
Google lead me here while searching on the same question phill asked (sorting floats) so I figured it would be worth posting the answer despite the thread being kind of old. I'm new to perl and am still getting my head wrapped around it but brian d foy's statement "Perl cares more about the verbs than it does the nouns." above really hits the nail on the head. You don't need to convert the strings to floats before applying the sort. You need to tell the sort to sort the values as numbers and not strings. i.e.
my @foo = ('1.2', '3.4', '2.1', '4.6');
my @foo_sort = sort {$a <=> $b} @foo;
See http://perldoc.perl.org/functions/sort.html for more details on sort
Basically you will need to read the file line by line.
Then you will need to split each line by the delimiter, say a comma (CSV stands for comma-separated values), with
String[] strArr=line.split(",");
This will turn it into an array of strings which you can then manipulate, for example with
String name=strArr[0];
int yearOfBirth = Integer.valueOf(strArr[1]);
int monthOfBirth = Integer.valueOf(strArr[2]);
int dayOfBirth = Integer.valueOf(strArr[3]);
GregorianCalendar dob=new GregorianCalendar(yearOfBirth, monthOfBirth, dayOfBirth);
Student student=new Student(name, dob); //lets pretend you are creating instances of Student
You will need to do this for every line so wrap this code into a while loop. (If you don't know the delimiter just open the file in a text editor.)
Ideally we should do it from either controller or directive as per applicable.
Use $anchorScroll
, $location
as dependency injection.
Then call this two method as
$location.hash('scrollToDivID');
$anchorScroll();
Here scrollToDivID
is the id where you want to scroll.
Assumed you want to navigate to a error message div as
<div id='scrollToDivID'>Your Error Message</div>
For more information please see this documentation
I don't think your problem is with the BouncyCastle keystore; I think the problem is with a broken javax.net.ssl package in Android. The BouncyCastle keystore is a supreme annoyance because Android changed a default Java behavior without documenting it anywhere -- and removed the default provider -- but it does work.
Note that for SSL authentication you may require 2 keystores. The "TrustManager" keystore, which contains the CA certs, and the "KeyManager" keystore, which contains your client-site public/private keys. (The documentation is somewhat vague on what needs to be in the KeyManager keystore.) In theory, you shouldn't need the TrustManager keystore if all of your certficates are signed by "well-known" Certifcate Authorities, e.g., Verisign, Thawte, and so on. Let me know how that works for you. Your server will also require the CA for whatever was used to sign your client.
I could not create an SSL connection using javax.net.ssl at all. I disabled the client SSL authentication on the server side, and I still could not create the connection. Since my end goal was an HTTPS GET, I punted and tried using the Apache HTTP Client that's bundled with Android. That sort-of worked. I could make the HTTPS conection, but I still could not use SSL auth. If I enabled the client SSL authentication on my server, the connection would fail. I haven't checked the Apache HTTP Client code, but I suspect they are using their own SSL implementation, and don't use javax.net.ssl.
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
One can also use the java.util.EnumSet like this
@Test
void test(){
Enum aEnum =DayOfWeek.MONDAY;
printAll(aEnum);
}
void printAll(Enum value){
Set allValues = EnumSet.allOf(value.getClass());
System.out.println(allValues);
}
I was able to accomplish editing the default.aspx
page by:
By doing that I was able to remove the tagprefix causing a problem on my page.
Name both your submit buttons the same
<input name="submit" type="submit" id="submit" value="Save" />
<input name="submit" type="submit" id="process" value="Process" />
Then in your controller get the value of submit. Only the button clicked will pass its value.
public ActionResult Index(string submit)
{
Response.Write(submit);
return View();
}
You can of course assess that value to perform different operations with a switch block.
public ActionResult Index(string submit)
{
switch (submit)
{
case "Save":
// Do something
break;
case "Process":
// Do something
break;
default:
throw new Exception();
break;
}
return View();
}
package com.example.helloandroid;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
public class HelloAndroid2Activity extends Activity {
/** Called when the activity is first created. */
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLUE);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(10, 20, 30, 40, paint);
canvas.drawLine(20, 10, 50, 20, paint);
}
}
}
This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.
ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg",
"$(document).ready(function(){EnableControls();
alert('Overrides successfully Updated.');
DisableControls();});",
true);
In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.
Refer to this link. A one line solution to that question.
How to elegantly check if a number is within a range?
int x = 30;
if (Enumerable.Range(1,100).Contains(x))
//true
if (x >= 1 && x <= 100)
//true
I know the post is pretty old, but It may help others..
Why and when you should mark the request
parameter as implicit
:
Some methods that you will make use of in the body of your action have an implicit parameter list like, for example, Form.scala defines a method:
def bindFromRequest()(implicit request: play.api.mvc.Request[_]): Form[T] = { ... }
You don't necessarily notice this as you would just call myForm.bindFromRequest()
You don't have to provide the implicit arguments explicitly. No, you leave the compiler to look for any valid candidate object to pass in every time it comes across a method call that requires an instance of the request. Since you do have a request available, all you need to do is to mark it as implicit
.
You explicitly mark it as available for implicit use.
You hint the compiler that it's "OK" to use the request object sent in by the Play framework (that we gave the name "request" but could have used just "r" or "req") wherever required, "on the sly".
myForm.bindFromRequest()
see it? it's not there, but it is there!
It just happens without your having to slot it in manually in every place it's needed (but you can pass it explicitly, if you so wish, no matter if it's marked implicit
or not):
myForm.bindFromRequest()(request)
Without marking it as implicit, you would have to do the above. Marking it as implicit you don't have to.
When should you mark the request as implicit
? You only really need to if you are making use of methods that declare an implicit parameter list expecting an instance of the Request. But to keep it simple, you could just get into the habit of marking the request implicit
always. That way you can just write beautiful terse code.
I had a similar problem, and it was because one of my beans had been moved to another directory recently. I needed to do a "build clean" by deleting the build/classes/java
directory and the problem went away. (The error message had the two different file paths conflicting with each other, although I knew one should not actually exist anymore.)
PHP 7^ version:
sudo apt-get install php-curl
sudo service apache2 restart
Depending on where you look, you'll get slightly different answers. I've read about the subject a lot, and here's my distillation; again, these are slightly wooly and others may disagree.
Unit Tests
Tests the smallest unit of functionality, typically a method/function (e.g. given a class with a particular state, calling x method on the class should cause y to happen). Unit tests should be focussed on one particular feature (e.g., calling the pop method when the stack is empty should throw an InvalidOperationException
). Everything it touches should be done in memory; this means that the test code and the code under test shouldn't:
Any kind of dependency that is slow / hard to understand / initialise / manipulate should be stubbed/mocked/whatevered using the appropriate techniques so you can focus on what the unit of code is doing, not what its dependencies do.
In short, unit tests are as simple as possible, easy to debug, reliable (due to reduced external factors), fast to execute and help to prove that the smallest building blocks of your program function as intended before they're put together. The caveat is that, although you can prove they work perfectly in isolation, the units of code may blow up when combined which brings us to ...
Integration Tests
Integration tests build on unit tests by combining the units of code and testing that the resulting combination functions correctly. This can be either the innards of one system, or combining multiple systems together to do something useful. Also, another thing that differentiates integration tests from unit tests is the environment. Integration tests can and will use threads, access the database or do whatever is required to ensure that all of the code and the different environment changes will work correctly.
If you've built some serialization code and unit tested its innards without touching the disk, how do you know that it'll work when you are loading and saving to disk? Maybe you forgot to flush and dispose filestreams. Maybe your file permissions are incorrect and you've tested the innards using in memory streams. The only way to find out for sure is to test it 'for real' using an environment that is closest to production.
The main advantage is that they will find bugs that unit tests can't such as wiring bugs (e.g. an instance of class A unexpectedly receives a null instance of B) and environment bugs (it runs fine on my single-CPU machine, but my colleague's 4 core machine can't pass the tests). The main disadvantage is that integration tests touch more code, are less reliable, failures are harder to diagnose and the tests are harder to maintain.
Also, integration tests don't necessarily prove that a complete feature works. The user may not care about the internal details of my programs, but I do!
Functional Tests
Functional tests check a particular feature for correctness by comparing the results for a given input against the specification. Functional tests don't concern themselves with intermediate results or side-effects, just the result (they don't care that after doing x, object y has state z). They are written to test part of the specification such as, "calling function Square(x) with the argument of 2 returns 4".
Acceptance Tests
Acceptance testing seems to be split into two types:
Standard acceptance testing involves performing tests on the full system (e.g. using your web page via a web browser) to see whether the application's functionality satisfies the specification. E.g. "clicking a zoom icon should enlarge the document view by 25%." There is no real continuum of results, just a pass or fail outcome.
The advantage is that the tests are described in plain English and ensures the software, as a whole, is feature complete. The disadvantage is that you've moved another level up the testing pyramid. Acceptance tests touch mountains of code, so tracking down a failure can be tricky.
Also, in agile software development, user acceptance testing involves creating tests to mirror the user stories created by/for the software's customer during development. If the tests pass, it means the software should meet the customer's requirements and the stories can be considered complete. An acceptance test suite is basically an executable specification written in a domain specific language that describes the tests in the language used by the users of the system.
Conclusion
They're all complementary. Sometimes it's advantageous to focus on one type or to eschew them entirely. The main difference for me is that some of the tests look at things from a programmer's perspective, whereas others use a customer/end user focus.
Consider using System.Windows.Forms.Timer
instead of System.Threading.Timer
for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.
In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax
method (running in the browser) sends the form data to the server, then a script on the server handles the upload. Here's an example using PHP.
Your HTML is fine, but update your JS jQuery script to look like this:
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that runs on the server and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
And a little bit about the PHP function move_uploaded_file
, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name']
is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize
AND post_max_size
configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
I stumbled upon this question because I created, successfully built and published a PyPI Package, but couldn't execute it after installation. The $PATH
variable was correctly set.
In my case the problem was that I hadn't set the entry_point
in the setup.py
file:
entry_points = {'console_scripts':
['YOUR_CONSOLE_COMMAND=MODULE_NAME.FILE_NAME:FUNCTION_NAME'],},