I had the same issue and I found this nice poweshell script to update all of your app pools at the same time: https://gallery.technet.microsoft.com/scriptcenter/How-to-set-the-IIS-9c295a20
Make sure to set you $IISAppPoolDotNetVersion = "v4.0"
variable at the top.
col-xs-*
have been dropped in Bootstrap 4 in favor of col-*
.
Replace col-xs-12
with col-12
and it will work as expected.
Also note col-xs-offset-{n}
were replaced by offset-{n}
in v4.
ALTER TABLE tablename AUTO_INCREMENT = 1
Unfortunately, this is not a trivial thing to solve for the general case. The easiest thing would be to add a css-style property "float: right;" to your 200px div, however, this would also cause your "main"-div to actually be full width and any text in there would float around the edge of the 200px-div, which often looks weird, depending on the content (pretty much in all cases except if it's a floating image).
EDIT: As suggested by Dom, the wrapping problem could of course be solved with a margin. Silly me.
If you're trying to get the integers from the command line args, you'll need something like this:
public static void main(String[] args) {
int[] nums = new int[args.length];
for(int i = 0; i < args.length; i++) {
try {
nums[i] = Integer.parseInt(args[i]);
}
catch(NumberFormatException nfe) {
System.err.println("Invalid argument");
}
}
// averaging code here
}
As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).
Edit: actually it's probably better to just put it inside the above loop and not use the nums
array at all
For anyone looking to do this in vb (as I was and couldn't find anything)
From c In db.Company
Select c.Name Group By Name Into Group
Where Group.Count > 1
List constructor accepts any data structure that implements Collection interface to be used to build a list.
To get all the keys from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keys = new ArrayList<>(map.keySet());
To get all the values from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<Integer> values = new ArrayList<>(map.values());
I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.
What I though
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
What I've finally done
namespace mycompany\CutreApi;
use \vendor\AwesomeApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new \mycompany\CutreApi\ClassOfVendor();
}
}
So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.
One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.
Currently done
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function getWhatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.
Hope this can help someone.
As far as "built-in" libraries go, the <<
and >>
have been reserved specifically for serialization.
You should override <<
to output your object to some serialization context (usually an iostream
) and >>
to read data back from that context. Each object is responsible for outputting its aggregated child objects.
This method works fine so long as your object graph contains no cycles.
If it does, then you will have to use a library to deal with those cycles.
Check How to: Define Constants in C# on MSDN:
In C# the
#define
preprocessor directive cannot be used to define constants in the way that is typically used in C and C++.
To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.
{
"keyvaluelist": {
"slide0001.html": "Looking Ahead",
"slide0008.html": "Forecast",
"slide0021.html": "Summary"
},
"otherdata": {
"one": "1",
"two": "2",
"three": "3"
},
"anotherthing": "thing1",
"onelastthing": "thing2"
}
I read this as
a JSON object with four elements
element 1 is a map of key/value pairs named "keyvaluelist",
element 2 is a map of key/value pairs named "otherdata",
element 3 is a string named "anotherthing",
element 4 is a string named "onelastthing"
The first element or second element could alternatively be described as objects themselves, of course, with three elements each.
Very simple was to renew your certificate. Go to your developer member centre and go to your Provisioning profile and see what are the certificate Active and InActive and select Inactive certificate and hit Edit button then hit generate button. Now your certificate successful renewal for another 1 year. Thanks
my solution is this:
configurations.all {
resolutionStrategy {
force 'com.android.support:support-v4:27.1.0'
}
}
The MSDN documentation for environment variables tells you what to do:
To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.
You will of course need admin rights to do this. I know of no way to broadcast a windows message from Windows batch so you'll need to write a small program to do this.
You can commit in the current branch, checkout to another branch, and finally cherry-pick that commit (in lieu of merge).
If you are having 112 columns in one single table and you would like to insert data from source table, you could do as
create table employees as select * from source_employees where employee_id=100;
Or from sqlplus do as
copy from source_schema/password insert employees using select * from
source_employees where employee_id=100;
For selenium automation users
I was running a website at localhost/MyApp built and run through Visual Studio - via a Virtual Directory created by Visual Studio itself.
The "solution" for me was to delete the Virtual Directory and let Visual Studio recreate it.
You may well want to use JSON-P instead (see below). First a quick explanation.
The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest
) rather than the standard XMLHttpRequest
that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com
).
To get the JSON data you're requesting, you basically have three options:
If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)
Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax
call (just set dataType
to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:
{"weather": "Dreary start but soon brightening into a fine summer day."}
Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:
jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
That's it. JSON-P is very broadly compatible (because it works via JavaScript script
tags). JSON-P is only for GET
, though, not POST
(again because it works via script
tags).
Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:
A. The browser will send your server a "preflight" message using the OPTIONS
HTTP verb (method). It will contain the various headers it would send with the GET
or POST
as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET
or POST
), and "Access-Control-Request-Headers" (the headers it wants to send).
B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.
C. The browser will look at your response and see whether it's allowed to send you the actual GET
or POST
. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.
D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.
In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):
// Find out what the request is asking for
corsOrigin = get_request_header("Origin")
corsMethod = get_request_header("Access-Control-Request-Method")
corsHeaders = get_request_header("Access-Control-Request-Headers")
if corsOrigin is null or "null" {
// Requests from a `file://` path seem to come through without an
// origin or with "null" (literally) as the origin.
// In my case, for testing, I wanted to allow those and so I output
// "*", but you may want to go another way.
corsOrigin = "*"
}
// Decide whether to accept that request with those headers
// If so:
// Respond with headers saying what's allowed (here we're just echoing what they
// asked for, except we may be using "*" [all] instead of the actual origin for
// the "Access-Control-Allow-Origin" one)
set_response_header("Access-Control-Allow-Origin", corsOrigin)
set_response_header("Access-Control-Allow-Methods", corsMethod)
set_response_header("Access-Control-Allow-Headers", corsHeaders)
if the HTTP request method is "OPTIONS" {
// Done, no body in response to OPTIONS
stop
}
// Process the GET or POST here; output the body of the response
Again stressing that this is pseudo-code.
You first have to define a JTextArea as per usual:
public final JTextArea mainConsole = new JTextArea("");
Then you put a JScrollPane over the TextArea
JScrollPane scrollPane = new JScrollPane(mainConsole);
scrollPane.setBounds(10,60,780,500);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
The last line says that the vertical scrollbar will always be there. There is a similar command for horizontal. Otherwise, the scrollbar will only show up when it is needed (or never, if you use _SCROLLBAR_NEVER). I guess it's your call which way you want to use it.
You can also add wordwrap to the JTextArea if you want to:Guide Here
Good luck,
Norm M
P.S. Make sure you add the ScrollPane to the JPanel and not add the JTextArea.
I believe I had a similar quandary recently
function parentCtrl() {
var pc = this; // pc stands for parent control
pc.foobar = 'SomeVal';
}
function childCtrl($scope) {
// now how do I get the parent control 'foobar' variable?
// I used $scope.$parent
var parentFoobarVariableValue = $scope.$parent.pc.foobar;
// that did it
}
My setup was a little different, but the same thing should probably still work
This should do it:
UPDATE ProductReviews
SET ProductReviews.status = '0'
FROM ProductReviews
INNER JOIN products
ON ProductReviews.pid = products.id
WHERE ProductReviews.id = '17190'
AND products.shopkeeper = '89137'
There is no equivalent of C# async/await in Java at the language level. A concept known as Fibers aka cooperative threads aka lightweight threads could be an interesting alternative. You can find Java libraries providing support for fibers.
Java libraries implementing Fibers
You can read this article (from Quasar) for a nice introduction to fibers. It covers what threads are, how fibers can be implemented on the JVM and has some Quasar specific code.
This was the only way I could get this to work
add_action('init','add_query_args');
function add_query_args()
{
add_query_arg( 'var1', 'val1' );
}
Try our new Bash library product realpath-lib over at GitHub that we have given to the community for free and unencumbered use. It's clean, simple and well documented so it's great to learn from. You can do:
get_realpath <absolute|relative|symlink|local file path>
This function is the core of the library:
if [[ -f "$1" ]]
then
# file *must* exist
if cd "$(echo "${1%/*}")" &>/dev/null
then
# file *may* not be local
# exception is ./file.ext
# try 'cd .; cd -;' *works!*
local tmppwd="$PWD"
cd - &>/dev/null
else
# file *must* be local
local tmppwd="$PWD"
fi
else
# file *cannot* exist
return 1 # failure
fi
# reassemble realpath
echo "$tmppwd"/"${1##*/}"
return 0 # success
}
It's Bash 4+, does not require any dependencies and also provides get_dirname, get_filename, get_stemname and validate_path.
The element.style
property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle
property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle
method.
The two ways have differences, for example, the IE element.currentStyle
property expect that you access the CCS property names composed of two or more words in camelCase (e.g. maxHeight
, fontSize
, backgroundColor
, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height
, font-size
, background-color
, etc).
Also, the IE element.currentStyle
will return all the sizes in the unit that they were specified, (e.g. 12pt, 50%, 5em), the standard way will compute the actual size in pixels always.
I made some time ago a cross-browser function that allows you to get the computed styles in a cross-browser way:
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
The above function is not perfect for some cases, for example for colors, the standard method will return colors in the rgb(...) notation, on IE they will return them as they were defined.
I'm currently working on an article in the subject, you can follow the changes I make to this function here.
Simplification from the above Andrew's answer leads to this key theme to generate the half border.
theme (panel.border = element_blank(),
axis.line = element_line(color='black'))
SELECT DISTINCT C.valueC
FROM C
LEFT JOIN B ON C.id = B.lookupC
LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL
I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.
EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.
There is no distinct join construct you could use so just stay with what you already have :)
if you are not using storyboard, you can try this
var window: UIWindow?
var initialViewController :UIViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
initialViewController = MainViewController(nibName:"MainViewController",bundle:nil)
let frame = UIScreen.mainScreen().bounds
window = UIWindow(frame: frame)
window!.rootViewController = initialViewController
window!.makeKeyAndVisible()
return true
}
You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.
When you run
install.packages("whatever")
you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:
.libPaths()
If libPaths shows 2 locations, then paste into second one. Load library:
library(whatever)
Fixed.
You need to use the string concatenation operator +
String both = name + "-" + dest;
First you need query Intent to handler sharing option. Then use package name to filter Intent then we will have only one Intent that handler sharing option!
Share via Facebook
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
if ((app.activityInfo.name).contains("facebook")) {
final ActivityInfo activity = app.activityInfo;
final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
shareIntent.setComponent(name);
v.getContext().startActivity(shareIntent);
break;
}
}
Bonus - Share via Twitter
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
if ("com.twitter.android.PostActivity".equals(app.activityInfo.name)) {
final ActivityInfo activity = app.activityInfo;
final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
shareIntent.setComponent(name);
v.getContext().startActivity(shareIntent);
break;
}
}
And if you want to find how to share via another sharing application, find it there Tép Blog - Advance share via Android
I think what you want to do is this:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
Make sure the 'AppendDataBoundItems' is set to true or else you will clear the '--Select One--' list item when you bind your data.
If you have the 'AutoPostBack' property of the drop down list set to true you will have to also set the 'CausesValidation' property to true then use a 'RequiredFieldValidator' to make sure the '--Select One--' option doesn't cause a postback.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
Triple check the name and path of the file. In my case I had something like this content in the target folder:
lib
foobar.bundle.js
foobr.css
And this link:
<link rel="stylesheet" href="lib/foobar.css">
I guess that the browser was trying to load the JavaScript file and complaining about its MIME type instead of giving me a file not found error.
I have just tested in Postgres 9.1 a solution which is close to Oracle ROWNUM:
select row_number() over() as id, t.*
from information_schema.tables t;
I used git svn
, and had this problem for one file. Using ls-tree
for each ancestor of the file, I noticed that one had 2 subfolders - Submit
and submit
. Since I was on Windows, they couldn't both be checked out, causing this issue.
The solution was to delete one of them directly from TortoiseSVN
Repo-browser
, then to run git svn fetch
followed by git reset --hard origin/trunk
.
These words existed way before Computer Science came around.
Attribute is a quality or object that we attribute to someone or something. For example, the scepter is an attribute of power and statehood.
Property is a quality that exists without any attribution. For example, clay has adhesive qualities; i.e, a property of clay is its adhesive quality. Another example: one of the properties of metals is electrical conductivity. Properties demonstrate themselves through physical phenomena without the need to attribute them to someone or something. By the same token, saying that someone has masculine attributes is self-evident. In effect, you could say that a property is owned by someone or something.
To be fair though, in Computer Science these two words, at least for the most part, can be used interchangeably - but then again programmers usually don't hold degrees in English Literature and do not write or care much about grammar books :).
foreach(PropertyInfo propertyInfo in original.GetType().GetProperties()) {
if (propertyInfo.GetValue(updatedUser, null) == null)
propertyInfo.SetValue(updatedUser, propertyInfo.GetValue(original, null), null);
}
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();
This is somewhat a go around solution but it worked for me I hope it works for this problem for others as well:
You can run the select SQL query on the table that you want to export and save the result as .xls in you drive.
Now create the table you want to add data with all the columns and indexes. This can be easily done with the right click on the actual table and selecting Create To script option.
Now you can right click on the DB where you want to add you table and select the Tasks>Import .
Import Export wizard opens and select next.Select the Microsoft Excel as input Data source and then browse and select the .xls file you have saved earlier.
Now select the destination server and also the destination table we have created already.
Note:If there is any identity based field, in the destination table you might want to remove the identity property as this data will also be inserted . So if you had this one as Identity property only then it would error out the import process.
Now hit next and hit finish and it will show you how many records are being imported and return success if no errors occur.
To get all rows, don't specify the key. Try this:
$meta_values = get_post_meta( get_the_ID() );
var_dump( $meta_values );
Hope it helps!
Lets say above one is your original dataframe and you want to add a new column 'old'
If age greater than 50 then we consider as older=yes otherwise False
step 1: Get the indexes of rows whose age greater than 50
row_indexes=df[df['age']>=50].index
step 2:
Using .loc we can assign a new value to column
df.loc[row_indexes,'elderly']="yes"
same for age below less than 50
row_indexes=df[df['age']<50].index
df[row_indexes,'elderly']="no"
This question is from 2012, some things are changed from that date, and since it still receives a lot of traffic from google, I feel like completing it adding flexbox as a solution.
By now, flexbox is the advised pattern to be used, even if it lacks IE9 support.
The only thing you have to care about is adding display: flex
in the parent element. As default and without the need of setting other property, all the children of that element will be aligned in the same row.
If you want to read more about flexbox
, you can do it here.
.container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
img {_x000D_
margin: 6px;_x000D_
}
_x000D_
<div class="container">_x000D_
<img src="https://placekitten.com/g/300/300" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>
_x000D_
You can use either SEQUENCE
or TRIGGER
to increment automatically the value of a given column in your database table however the use of TRIGGERS
would be more appropriate. See the following documentation of Oracle that contains major clauses used with triggers with suitable examples.
Use the CREATE TRIGGER statement to create and enable a database trigger, which is:
A stored PL/SQL block associated with a table, a schema, or the database or
An anonymous PL/SQL block or a call to a procedure implemented in PL/SQL or Java
Oracle Database automatically executes a trigger when specified conditions occur. See.
Following is a simple TRIGGER
just as an example for you that inserts the primary key value in a specified table based on the maximum value of that column. You can modify the schema name, table name etc and use it. Just give it a try.
/*Create a database trigger that generates automatically primary key values on the CITY table using the max function.*/
CREATE OR REPLACE TRIGGER PROJECT.PK_MAX_TRIGGER_CITY
BEFORE INSERT ON PROJECT.CITY
FOR EACH ROW
DECLARE
CNT NUMBER;
PKV CITY.CITY_ID%TYPE;
NO NUMBER;
BEGIN
SELECT COUNT(*)INTO CNT FROM CITY;
IF CNT=0 THEN
PKV:='CT0001';
ELSE
SELECT 'CT'||LPAD(MAX(TO_NUMBER(SUBSTR(CITY_ID,3,LENGTH(CITY_ID)))+1),4,'0') INTO PKV
FROM CITY;
END IF;
:NEW.CITY_ID:=PKV;
END;
Would automatically generates values such as CT0001
, CT0002
, CT0002
and so on and inserts into the given column of the specified table.
May be this can help:
Use MyTest
Go
select * from information_schema.COLUMNS where TABLE_NAME='employee'
{ where: MyTest= DatabaseName Employee= TableName } --Optional conditions
Adding to Eric's answer, you can also configure this in the csproj
file:
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>MyTests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
Or if you have one test project per project to be tested, you could do something like this in your Directory.Build.props
file:
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>$(MSBuildProjectName).Test</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
See: https://stackoverflow.com/a/49978185/1678053
Example: https://github.com/gldraphael/evlog/blob/master/Directory.Build.props#L5-L12
This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?
import tkinter
class App(object):
def __init__(self):
self.tree = None
self._setup_widgets()
def _setup_widgets(self):
butts = tkinter.Button(text = "add line", state="disabled")
butts.grid()
def main():
root = tkinter.Tk()
app = App()
root.mainloop()
if __name__ == "__main__":
main()
You can also use Gson for this scenario.
Gson gson = new Gson();
NameList nameList = gson.fromJson(data, NameList.class);
List<Name> list = nameList.getList();
Your NameList class could look like:
class NameList{
List<Name> list;
//getter and setter
}
I've tried many times.
And at last I just put autoindex on;
in http
but outside of server
, and it's OK.
What I do in my scripts is check at runtime if the 'verbose' option is set, and then set my logging level to debug. If it's not set, I set it to info. This way you don't have 'if verbose' checks all over your code.
You can find your solution from apple's DEMO in this page: WWDC 2013 , find out and download UIImageEffects sample code.
Then with @Jeremy Fox's code. I changed it to
- (UIImage*)getDarkBlurredImageWithTargetView:(UIView *)targetView
{
CGSize size = targetView.frame.size;
UIGraphicsBeginImageContext(size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(c, 0, 0);
[targetView.layer renderInContext:c]; // view is the view you are grabbing the screen shot of. The view that is to be blurred.
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [image applyDarkEffect];
}
Hope this will help you.
You have a lot of type-mismatches in your code such as trying to put an int
value where BigDecimal
is required. The corrected version of your code:
public class Payment
{
BigDecimal itemCost = BigDecimal.ZERO;
BigDecimal totalCost = BigDecimal.ZERO;
public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
{
itemCost = itemPrice.multiply(new BigDecimal(itemQuantity));
totalCost = totalCost.add(itemCost);
return totalCost;
}
}
Try this command: "git pull origin master"
It worked for me.
Check this link: https://help.github.com/articles/dealing-with-non-fast-forward-errors
you could try:
<a href="#/controllerone">Controller One</a>||
<a href="#/controllerTwo">Controller Two</a>||
<a href="#/controllerThree">Controller Three</a>
<div>
<div ng-view=""></div>
</div>
I think your all setting is good but you doing to misplace your htaccess file go and add your htaccess to your project file
project_folder->htaccess
and add this code to your htaccess
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
I wanted to delete all records from both tables because it was all test data. I used SSMS GUI to temporarily disable a FK constraint, then I ran a DELETE query on both tables, and finally I re-enabled the FK constraint.
To disable the FK constraint:
[1] in the 'Object Explorer' pane, can be accessed via the 'View' menu option, or key F8
[2] if you're not sure which table is the dependant one, you can check by right clicking the table in question and selecting the 'View Dependencies' option.
The first thing is to make a comparison of functions of SHA and opt for the safest algorithm that supports your programming language (PHP).
Then you can chew the official documentation to implement the hash()
function that receives as argument the hashing algorithm you have chosen and the raw password.
sha256 => 64 bits
sha384 => 96 bits
sha512 => 128 bits
The more secure the hashing algorithm is, the higher the cost in terms of hashing and time to recover the original value from the server side.
$hashedPassword = hash('sha256', $password);
select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),100)
almost works perfectly except for the space issue. if that were changed to:
select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),22)
...then you get the space. And additionally, if the column being converted is already of TIME
format, you can skip the cast if you reference it directly.
Final answer:
select CONVERT(varchar(15),StartTime,22)
>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200
https://docs.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql
image
Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes. Still it IS supported to use image datatype, but be aware of:
https://docs.microsoft.com/en-us/sql/t-sql/data-types/binary-and-varbinary-transact-sql
varbinary [ ( n | max) ]
Variable-length binary data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of the data entered + 2 bytes. The data that is entered can be 0 bytes in length. The ANSI SQL synonym for varbinary is binary varying.
So both are equally in size (2GB). But be aware of:
Though the end of "image" datatype is still not determined, you should use the "future" proof equivalent.
But you have to ask yourself: why storing BLOBS in a Column?
As stated in problem, to solve this error you MUST use correct annotations. In above problem, @NotBlank
or @NotEmpty
annotation must be applied on any String field only.
To validate long type field, use annotation @NotNull
.
Strings in Python are immutable meaning you cannot replace parts of them.
You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.
You could for instance write a function:
def replace_str_index(text,index=0,replacement=''):
return '%s%s%s'%(text[:index],replacement,text[index+1:])
And then for instance call it with:
new_string = replace_str_index(old_string,middle)
If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.
For instance:
replace_str_index('hello?bye',5)
will return 'hellobye'
; and:
replace_str_index('hello?bye',5,'good')
will return 'hellogoodbye'
.
This code securely works to convert Object to Dictionary (having as premise that the source object comes from a Dictionary):
private static Dictionary<TKey, TValue> ObjectToDictionary<TKey, TValue>(object source)
{
Dictionary<TKey, TValue> result = new Dictionary<TKey, TValue>();
TKey[] keys = { };
TValue[] values = { };
bool outLoopingKeys = false, outLoopingValues = false;
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
{
object value = property.GetValue(source);
if (value is Dictionary<TKey, TValue>.KeyCollection)
{
keys = ((Dictionary<TKey, TValue>.KeyCollection)value).ToArray();
outLoopingKeys = true;
}
if (value is Dictionary<TKey, TValue>.ValueCollection)
{
values = ((Dictionary<TKey, TValue>.ValueCollection)value).ToArray();
outLoopingValues = true;
}
if(outLoopingKeys & outLoopingValues)
{
break;
}
}
for (int i = 0; i < keys.Length; i++)
{
result.Add(keys[i], values[i]);
}
return result;
}
A sample code that works for me on Windows:
import requests
with open('pic1.jpg', 'wb') as handle:
response = requests.get(pic_url, stream=True)
if not response.ok:
print response
for block in response.iter_content(1024):
if not block:
break
handle.write(block)
The given answer is correct nontheless as someone above said you can use df.query('line_race != 0')
which depending on your problem is much faster. Highly recommend.
You could try catching the onload event. And stopping the propagation dependent on some flag.
var changeHash = false;
$('ul.questions li a').click(function(event) {
var $this = $(this)
$('.tab').hide(); //you can improve the speed of this selector.
$($this.attr('href')).fadeIn('slow');
StopEvent(event); //notice I've changed this
changeHash = true;
window.location.hash = $this.attr('href');
});
$(window).onload(function(event){
if (changeHash){
changeHash = false;
StopEvent(event);
}
}
function StopEvent(event){
event.preventDefault();
event.stopPropagation();
if ($.browser.msie) {
event.originalEvent.keyCode = 0;
event.originalEvent.cancelBubble = true;
event.originalEvent.returnValue = false;
}
}
Not tested, so can't say if it would work
Use .. LIMIT :pageSize OFFSET :pageStart
Where :pageStart
is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize
is bound to number_of_items_per_pages.
To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1
and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.
If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET
item.
#ck-button:hover {
background:red;
}
Fiddle: http://jsfiddle.net/zAFND/4/
If you have a Replicated table, you can have an Identity=1000 in localDatabase and Identity=2000 in the clientDatabase, so if you catch the last ID you may find always the last from client, not the last from the current connected database. So the best method which returns the last connected database is:
SELECT IDENT_CURRENT('tablename')
Yes, I believe you are creating thousands of objects. If you're looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.
Create "topN" query on "clientip" and then histogram with count on "clientip" and set "topN" query as source. Then you will see count of different ips per time.
As primitives(long) can't be null,It can be converted to wrapper class of that primitive type(ie.Long) and null check can be performed.
If you want to check whether long variable is null,you can convert that into Long and check,
long longValue=null;
if(Long.valueOf(longValue)==null)
So to add the string hello
to a list as individual characters, try this:
newlist = []
newlist[:0] = 'hello'
print (newlist)
['h','e','l','l','o']
However, it is easier to do this:
splitlist = list(newlist)
print (splitlist)
prods.Remove(prods.Single(p=>p.ID == 1));
you can't modify collection in foreach, as Vincent suggests
A little update for Bootstrap 3.
Bootstrap now has the following style for table cells:
.table tbody>tr>td
{
vertical-align: top;
}
The way to go is to add a your own class, with the same selector:
.table tbody>tr>td.vert-align
{
vertical-align: middle;
}
And then add it to your tds
<td class="vert-align"></td>
You have to add an empty option (i.e. <option></option>
) as a first element to see a placeholder.
From Select2 official documentation :
"Note that because browsers assume the first option element is selected in non-multi-value select boxes an empty first option element must be provided (<option></option>
) for the placeholder to work."
Hope this helps.
Example:
<select id="countries">
<option></option>
<option value="1">Germany</option>
<option value="2">France</option>
<option value="3">Spain</option>
</select>
and the Javascript would be:
$('#countries').select2({
placeholder: "Please select a country"
});
Try this
<form method="post" id="reg" name="reg" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"
Works well :)
It solved my issue
smtpClient.Credentials = new NetworkCredential(sendMail.UserName, sendMail.Password);
smtpClient.EnableSsl = false;//sendMail.EnableSSL;
// With Reference to // Problem comes only Use above line to set false SSl to solve error when username and password is entered in SMTP settings.
I am using Maven 3.3.3 and cannot get the default profile to work in a user or global settings.xml
file.
As a workaround, you may also add an additional build plugin to your pom.xml
file.
<properties>
<maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
</properties>
<build>
<plugins>
<!-- Download Java source JARs. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${maven-dependency-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>sources</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Just came into this issue and finally realised that LocalDateTime doesn't have any timezone information. If you received a date string with timezone information, you need to use this as the type:
ZonedDateTime
Check this link
This solution worked for me.
Please place Route2 first in WebApiConfig. Also Add HttpGet and HttpPost before each method and include controller name and method name in the url.
WebApiConfig =>
config.Routes.MapHttpRoute(
name: "MapByAction",
routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
Controller =>
public class ValuesController : ApiController
{
[HttpPost]
public string GetCustomer([FromBody] RequestModel req)
{
return "Customer";
}
[HttpPost]
public string GetCustomerList([FromBody] RequestModel req)
{
return "Customer List";
}
}
Url =>
http://localhost:7050/api/Values/GetCustomer
http://localhost:7050/api/Values/GetCustomerList
Let's take an example: You want to contribute to django, so you fork its repository. In the while you work on your feature, there is much work done on the original repo by other people. So the code you forked is not the most up to date. setting a remote upstream and fetching it time to time makes sure your forked repo is in sync with the original repo.
Use the SQLCMD utility.
http://technet.microsoft.com/en-us/library/ms162773.aspx
There is a connect statement that allows you to swing from database server A to server B in the same batch.
:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]] Connects to an instance of SQL Server. Also closes the current connection.
On the other hand, if you are familiar with PowerShell, you can programmatic do the same.
http://technet.microsoft.com/en-us/library/cc281954(v=sql.105).aspx
All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static
and I used the same STATIC_URL in my dev settings.py file.
This causes a silent failure in django/conf/urls/static.py.
The test elif not settings.DEBUG or '://' in prefix:
picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.
It would be thoughtful if Django spit out an error message stating you can't use a http(s)://
with DEBUG = True
I had to change STATIC_URL to be '/static/'
Consider a=10
, b=15
:
Using Addition and Subtraction
a = a + b //a=25
b = a - b //b=10
a = a - b //a=15
Using Division and multiplication
a = a * b //a=150
b = a / b //b=10
a = a / b //a=15
My own experience has been that it's best to stick to one of two kinds of assembly references:
I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.
Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).
This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D
Hope that helps!
Shelf is a JetBrains feature while Stash is a Git feature for same work. You can switch to different branch without commit and loss of work using either of features. My personal experience is to use Shelf.
From API:
rename_column(table_name, column_name, new_column_name)
It renames a column but keeps the type and content remains same.
You can use in Content-security-policy add "img-src 'self' data:;" And Use outline CSS.Don't use Inline CSS.It's secure from attackers.
Alternatively, you could use tensorflow for the cropping and openCV for making an array from the image.
import cv2
img = cv2.imread('YOURIMAGE.png')
Now img
is a (imageheight, imagewidth, 3) shape array. Crop the array with tensorflow:
import tensorflow as tf
offset_height=0
offset_width=0
target_height=500
target_width=500
x = tf.image.crop_to_bounding_box(
img, offset_height, offset_width, target_height, target_width
)
Reassemble the image with tf.keras, so we can look at it if it worked:
tf.keras.preprocessing.image.array_to_img(
x, data_format=None, scale=True, dtype=None
)
This prints out the pic in a notebook (tested in Google Colab).
The whole code together:
import cv2
img = cv2.imread('YOURIMAGE.png')
import tensorflow as tf
offset_height=0
offset_width=0
target_height=500
target_width=500
x = tf.image.crop_to_bounding_box(
img, offset_height, offset_width, target_height, target_width
)
tf.keras.preprocessing.image.array_to_img(
x, data_format=None, scale=True, dtype=None
)
Assuming you have an ArrayList
that contains characters, you could do this:
List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));
select to_char(sysdate, 'Month') from dual
in your example will be:
select to_char(to_date('15-11-2010', 'DD-MM-YYYY'), 'Month') from dual
In views with {{}}
and/or ng-model, Angular is setting up $watch()
es for you behind the scenes.
By default $watch
compares by reference. If you set the third parameter to $watch
to true
, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:
$scope.$watch('myModel', function() { ... }, true);
Update: Angular v1.2 added a new method for this, `$watchCollection():
$scope.$watchCollection('myModel', function() { ... });
Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.
Perfect! Thank you Jay, below is my HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="../css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="../css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="../css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<link href="../css/highlight.css" rel="stylesheet" type="text/css" media="screen" />
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
$.getJSON("readJSON.php",function(data){
$.each(data.post, function(i,post){
content += '<p>' + post.post_author + '</p>';
content += '<p>' + post.post_content + '</p>';
content += '<p' + post.date + '</p>';
content += '<br/>';
$(content).appendTo("#posts");
});
});
});
/* ]]> */
</script>
</head>
<body>
<div class="container">
<div class="span-24">
<h2>Check out the following posts:</h2>
<div id="posts">
</di>
</div>
</div>
</body>
</html>
And my JSON outputs:
{ posts: [{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"This is a post","author":"Ryan Coughlin"}]}
I get this error, when I run my code:
object is undefined
http://localhost:8888/rks/post/js/jquery.js
Line 19
The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.
You can find the positive value by doing this:
int i = (((-1 % 2) + 2) % 2)
or this:
int i = -1 % 2;
if (i<0) i += 2;
(obviously -1 or 2 can be whatever you want the numerator or denominator to be)
CSS selector:
Use a CSS selector of img[src='images/toolbar/b_edit.gif']
This says select element(s) with img
tag with attribute src
having value of 'images/toolbar/b_edit.gif'
CSS query:
VBA:
You can apply the selector with the .querySelector
method of document
.
IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click
You can use
adb shell ps | grep apps | awk '{print $9}'
to produce an output like:
com.google.process.gapps
com.google.android.apps.uploader
com.google.android.apps.plus
com.google.android.apps.maps
com.google.android.apps.maps:GoogleLocationService
com.google.android.apps.maps:FriendService
com.google.android.apps.maps:LocationFriendService
adb shell ps returns a list of all running processes on the android device, grep apps searches for any row with contains "apps", as you can see above they are all com.google.android.APPS. or GAPPS, awk extracts the 9th column which in this case is the package name.
To search for a particular package use
adb shell ps | grep PACKAGE.NAME.HERE | awk '{print $9}'
i.e adb shell ps | grep com.we7.player | awk '{print $9}'
If it is running the name will appear, if not there will be no result returned.
My C++ templates were there all along, it was my C# ones that were missing.
Similar to CSharpie, after trying many modify/re-installs, oddly the following finally worked for me :
- run the installer, but un-select 'Desktop development with C++'.
- allow installer to complete
- run the installer again, and select 'Desktop development with C++'.
- allow installer to complete
After the configure step you probably have a makefile. Inside this makefile look for CFLAGS (or similar). puf -fPIC at the end and run make again. In other words -fPIC is a compiler option that has to be passed to the compiler somewhere.
Something the original answer didn't have. I added some more code to make it bullet proof.
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
One pragmatic tip: you can search easily for the static_cast keyword in your source code if you plan to tidy up the project.
When Command Extensions are enabled (Windows XP and newer, roughly), you can use the syntax %~nF (where F is the variable and ~n is the request for its name) to only get the filename.
FOR /R C:\Directory %F in (*.*) do echo %~nF
should echo only the filenames.
Use type="application/javascript"
In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.
http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".
Use "application/javascript", because "text/javascript" is obsolete:
RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt
Deployed Scripting Media Types and Compatibility
Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:
+-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+
Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,* application/javascript * application/ecmascript
which are also defined in this document, are intended for common use and should be used instead.
This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.
x-javascript is experimental, don't use it.
str(n).zfill(width)
will work with string
s, int
s, float
s... and is Python 2.x and 3.x compatible:
>>> n = 3
>>> str(n).zfill(5)
'00003'
>>> n = '3'
>>> str(n).zfill(5)
'00003'
>>> n = '3.0'
>>> str(n).zfill(5)
'003.0'
Yes, use @import
detailed info easily googled for, a good one at http://webdesign.about.com/od/beginningcss/f/css_import_link.htm
ActiveWorkbook.FullName would be better I think, in case you have the VBA Macro stored in another Excel Workbook, but you want to get the details of the Excel you are editing, not where the Macro resides.
If they reside in the same file, then it does not matter, but if they are in different files, and you want the file where the Data is rather than where the Macro is, then ActiveWorkbook is the one to go for, because it deals with both scenarios.
It depends on what you want to do and what type of data/information you are displaying. In general, tables are reserved for displaying tabular data.
An alternate for your situation would be to use css. A simple option would be to float your image and give it a margin:
<p>
<img style="float: left; margin: 5px;" ... />
Text goes here...
</p>
This would cause the text to wrap around the image. If you don't want the text to wrap around the image, put the text in a separate container:
<div>
<img style="float: left; margin: ...;" ... />
<p style="float: right;">Text goes here...</p>
</div>
Note that it may be necessary to assign a width to the paragraph tag to display the way you'd like. Also note, for elements that appear below floated elements, you may need to add the style "clear: left;" (or clear: right, or clear: both).
Your input in this case is too ambiguous. Your code will have to know if it should just insert the text as-is or parse out some HTML tags (or otherwise wind up with bad HTML). This is unneeded complexity that you can avoid by adjusting the input you provide.
If the garbled input is unavoidable, then without some sophisticated parsing (preferably in a separate function), you could end up with some bad HTML (like you do in your second example... which is Bad, right?).
I'm guessing you want a function to insert columns into a 1-row table. In this case, your contents should be passed in as an array (without table, tr, td tags). Each array element will be one column.
<table id="__TABLE__"><tr><td></td></tr></table>
using jQuery for brevity...
function insert_columns (columns)
{
var $row = $('<tr></tr>');
for (var i = 0; i < columns.length; i++)
$row.append('<td>'+columns[i]+'</td>');
$('#__TABLE__').empty(); // remove everything inside
$('#__TABLE__').append($row);
}
So then...
insert_columns(['hello', 'there', 'world']);
<table id="__TABLE__"><tr><td>hello</td><td>there</td><td>world</td></tr></table>
Karl answered your search-path question, but as far as the "source of the files" goes, one thing to be aware of is that if you install the libfoo
package and want to do some development with it (i.e., use its headers), you will also need to install libfoo-dev
. The standard library header files are already in /usr/include
, as you saw.
Note that some libraries with a lot of headers will install them to a subdirectory, e.g., /usr/include/openssl
. To include one of those, just provide the path without the /usr/include
part, for example:
#include <openssl/aes.h>
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
Tomcat will only extract the war which is copied to webapps
directory.
Change Dockerfile
as below:
FROM tomcat:8.0.20-jre8
COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war
You might need to access the url as below unless you have specified the webroot
OK, considering that you are using Windows, the most simple way to do that is to use the standard ftp
tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.
First of all, you need to create a batch (script) file for the ftp
program, containing instructions for it. Name it as you want, and put into it:
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
open ftp.myftpsite.com
login
pass
mget *
quit
The first line opens a connection to the ftp server at ftp.myftpsite.com
. The two following lines specify the login, and the password which ftp will ask for (replace login
and pass
with just the login and password, without any keywords). Then, you use mget *
to get all files. Instead of the *
, you can use any wildcard. Finally, you use quit
to close the ftp
program without interactive prompt.
If you needed to enter some directory first, add a cd
command before mget
. It should be pretty straightforward.
Finally, write that file and run ftp
like this:
ftp -i -s:yourscript
where -i
disables interactivity (asking before downloading files), and -s
specifies path to the script you created.
Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use PuTTy tools anyway. The one of particular interest for this case would be pscp
which is practically the PuTTy counter-part of the openssh scp
command.
The syntax is similar to copy
command, and it supports wildcards:
pscp -batch [email protected]:iiumlabs* .
If you authenticate using a key file, you should pass it using -i path-to-key-file
. If you use password, -pw pass
. It can also reuse sessions saved using PuTTy, using the load -load your-session-name
argument.
What causes runtime error 380? Attempting to set a property of an object or control to a value that is not allowed. Look through the code that runs when your search form loads (Form_Load etc.) for any code that sets a property to something that depends on runtime values.
My other advice is to add some error handling and some logging to track down the exact line that is causing the error.
Erl
to report line numbers and find the exact line - MZTools can automatically put in line numbers for you. _
On Error Goto Handler
<routine contents>
Handler:
Err.Raise Err.Number, "(function_name)->" & Err.source, Err.Description
This is not the recommended way to solve this error but you can suppress it quickly, it will do the job . I prefer this for prototypes or demos . add
CheckForIllegalCrossThreadCalls = false
in Form1()
constructor .
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
To enable msbuild
in Command Prompt, you simply have to add the directory of the msbuild.exe
install on your machine to the PATH
environment variable.
You can access the environment variables by:
PATH
For reference, my path was C:\Windows\Microsoft.NET\Framework\v4.0.30319
As of MSBuild 12 (2013)/VS 2013/.NET 4.5.1+ and onward MSBuild is now installed as a part of Visual Studio.
For VS2015 the path was %ProgramFiles(x86)%\MSBuild\14.0\Bin
For VS2017 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin
For VS2019 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin
In TypeScript 3.5, the Omit
type was added to the standard library. See examples below for how to use it.
In TypeScript 2.8, the Exclude
type was added to the standard library, which allows an omission type to be written simply as:
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
You cannot use the Exclude
type in versions below 2.8, but you can create a replacement for it in order to use the same sort of definition as above. However, this replacement will only work for string types, so it is not as powerful as Exclude
.
// Functionally the same as Exclude, but for strings only.
type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>
And an example of that type in use:
interface Test {
a: string;
b: number;
c: boolean;
}
// Omit a single property:
type OmitA = Omit<Test, "a">; // Equivalent to: {b: number, c: boolean}
// Or, to omit multiple properties:
type OmitAB = Omit<Test, "a"|"b">; // Equivalent to: {c: boolean}
Branch with short hash and last comment:
git branch -v
develop 717c2f9 [ahead 42] blabla
* master 2722bbe [ahead 1] bla
Check with your bean class. Column data type and bean datatype must be same.
plt.figure(figsize=(15,10))
graph = sns.barplot(x='name_column_x_axis', y="name_column_x_axis", data = dataframe_name , color="salmon")
for p in graph.patches:
graph.annotate('{:.0f}'.format(p.get_height()), (p.get_x()+0.3, p.get_height()),
ha='center', va='bottom',
color= 'black')
There are a few ways of doing that... the simplest is to have the async method also do the follow-on operation. Another popular approach is to pass in a callback, i.e.
void RunFooAsync(..., Action<bool> callback) {
// do some stuff
bool result = ...
if(callback != null) callback(result);
}
Another approach would be to raise an event (with the result in the event-args data) when the async operation is complete.
Also, if you are using the TPL, you can use ContinueWith
:
Task<bool> outerTask = ...;
outerTask.ContinueWith(task =>
{
bool result = task.Result;
// do something with that
});
Maybe you're looking for something like this:
def tableize(df):
if not isinstance(df, pd.DataFrame):
return
df_columns = df.columns.tolist()
max_len_in_lst = lambda lst: len(sorted(lst, reverse=True, key=len)[0])
align_center = lambda st, sz: "{0}{1}{0}".format(" "*(1+(sz-len(st))//2), st)[:sz] if len(st) < sz else st
align_right = lambda st, sz: "{0}{1} ".format(" "*(sz-len(st)-1), st) if len(st) < sz else st
max_col_len = max_len_in_lst(df_columns)
max_val_len_for_col = dict([(col, max_len_in_lst(df.iloc[:,idx].astype('str'))) for idx, col in enumerate(df_columns)])
col_sizes = dict([(col, 2 + max(max_val_len_for_col.get(col, 0), max_col_len)) for col in df_columns])
build_hline = lambda row: '+'.join(['-' * col_sizes[col] for col in row]).join(['+', '+'])
build_data = lambda row, align: "|".join([align(str(val), col_sizes[df_columns[idx]]) for idx, val in enumerate(row)]).join(['|', '|'])
hline = build_hline(df_columns)
out = [hline, build_data(df_columns, align_center), hline]
for _, row in df.iterrows():
out.append(build_data(row.tolist(), align_right))
out.append(hline)
return "\n".join(out)
df = pd.DataFrame([[1, 2, 3], [11111, 22, 333]], columns=['a', 'b', 'c'])
print tableize(df)
Output: +-------+----+-----+ | a | b | c | +-------+----+-----+ | 1 | 2 | 3 | | 11111 | 22 | 333 | +-------+----+-----+
TimeUnit is an enum, so you can't create a new one.
The following will convert 1000000000000ns to seconds.
TimeUnit.NANOSECONDS.toSeconds(1000000000000L);
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
To expand on @Austin's answer, you should add this.handleScroll = this.handleScroll.bind(this)
to your constructor:
constructor(props){
this.handleScroll = this.handleScroll.bind(this)
}
componentDidMount: function() {
window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount: function() {
window.removeEventListener('scroll', this.handleScroll);
},
handleScroll: function(event) {
let scrollTop = event.srcElement.body.scrollTop,
itemTranslate = Math.min(0, scrollTop/3 - 60);
this.setState({
transform: itemTranslate
});
},
...
This gives handleScroll()
access to the proper scope when called from the event listener.
Also be aware you cannot do the .bind(this)
in the addEventListener
or removeEventListener
methods because they will each return references to different functions and the event will not be removed when the component unmounts.
What you could do is something like this (pseudocode):
<container table>
<tr>
<td>
<"300px" table>
<td>
<fixed layout table>
Basically, split up the table into two tables and have it contained by another table.
function go(type, pageCount) {
if ((type == 2 && pageCount == 0) || (type == 2 && pageCount == '')) {
pageCount = document.getElementById('<%=hfPageCount.ClientID %>').value;
}
}
Problem for me was my ProjectTypeGuid was MVC4 but I didn't have that installed on the target server. The solution was to change the ProjectTypeGuids to that of a Class Library, and include the MVC DLLs with the project rather than the project pick them up from the GAC.
I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified
it worked.
User.findOne({username: oldUsername}, function (err, user) {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.markModified(username)
user.markModified(password)
user.markModified(rights)
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
tell mongoose about the change with doc.markModified('pathToYourDate') before saving.
This worked for me. Select the problematic column in Excel - highlight the whole column. Change the format to "Text". Save the Excel file.
In your SSIS package, go to the Data Flow pane for your import. Double click the Excel Source node. It should warn you that the types have changed and ask you if you want to remap them. Click Yes. Executing should now work and bring in all values.
Note: I'm using Excel 2013 and Visual Studio 2015, but I assume these instructions would work for earlier versions too.
There are a variety of ways to get the URL .m3u8
either by viewing the source of a page, looking at the Network tab in the Developer Tools in Chrome, or using a plugin such as HDL/HLS Video Downloader.
With the .m3u8 URL in hand you can then use ffmpeg
to download the video to a file like so:
$ ffmpeg -i 'https://url/to/some/file.m3u8' -bsf:a aac_adtstoasc \
-vcodec copy -c copy -crf 50 file.mp4
Complementing the previous answers, one big difference between both is that Visual Studio Code comes in a so called "portable" version that does not require full administrative permissions to run on Windows and can be placed in a removable drive for convenience.
You can use the xmljson library to convert using different XML JSON conventions.
For example, this XML:
<p id="1">text</p>
translates via the BadgerFish convention into this:
{
'p': {
'@id': 1,
'$': 'text'
}
}
and via the GData convention into this (attributes are not supported):
{
'p': {
'$t': 'text'
}
}
... and via the Parker convention into this (attributes are not supported):
{
'p': 'text'
}
It's possible to convert from XML to JSON and from JSON to XML using the same conventions:
>>> import json, xmljson
>>> from lxml.etree import fromstring, tostring
>>> xml = fromstring('<p id="1">text</p>')
>>> json.dumps(xmljson.badgerfish.data(xml))
'{"p": {"@id": 1, "$": "text"}}'
>>> xmljson.parker.etree({'ul': {'li': [1, 2]}})
# Creates [<ul><li>1</li><li>2</li></ul>]
Disclosure: I wrote this library. Hope it helps future searchers.
Concatenation:
The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §2.2.1. Otherwise, the "concat" metamethod is called (see §2.8).
I build a module that allows do this kind of tests. But it is focused not only in repeat. But in guarantee that some piece of code is Thread safe.
https://github.com/anderson-marques/concurrent-testing
Maven dependency:
<dependency>
<groupId>org.lite</groupId>
<artifactId>concurrent-testing</artifactId>
<version>1.0.0</version>
</dependency>
Example of use:
package org.lite.concurrent.testing;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import ConcurrentTest;
import ConcurrentTestsRule;
/**
* Concurrent tests examples
*/
public class ExampleTest {
/**
* Create a new TestRule that will be applied to all tests
*/
@Rule
public ConcurrentTestsRule ct = ConcurrentTestsRule.silentTests();
/**
* Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
*/
@Test
@ConcurrentTest(requests = 20, threads = 10)
public void testConcurrentExecutionSuccess(){
Assert.assertTrue(true);
}
/**
* Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
*/
@Test
@ConcurrentTest(requests = 200, threads = 10, timeoutMillis = 100)
public void testConcurrentExecutionSuccessWaitOnly100Millissecond(){
}
@Test(expected = RuntimeException.class)
@ConcurrentTest(requests = 3)
public void testConcurrentExecutionFail(){
throw new RuntimeException("Fail");
}
}
This is a open source project. Feel free to improve.
Note: There appears to be a fix implemented in JDK 10 that ensures the Custom Thread Pool uses the expected number of threads.
Parallel stream execution within a custom ForkJoinPool should obey the parallelism https://bugs.openjdk.java.net/browse/JDK-8190974
Much simpler to my opinion:
sed -r 's/\s+//g' filename
For completeness, this is what you would have found in the svn book, had you known what to look for. It's what you've discovered already:
Same thing, from the more recent (and detailed) version of the book:
Try setting a property in each pom to find the main project directory.
In the parent:
<properties>
<main.basedir>${project.basedir}</main.basedir>
</properties>
In the children:
<properties>
<main.basedir>${project.parent.basedir}</main.basedir>
</properties>
In the grandchildren:
<properties>
<main.basedir>${project.parent.parent.basedir}</main.basedir>
</properties>
Use sprintf
(or snprintf
if like me you can't count) with format string "pre_%d_suff"
.
For what it's worth, with itoa/strcat you could do:
char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");
This is the first post on google so I thought I'd post different ways that are available and how they compare. Unfortunately I can't figure out how to create a table here, so it's an image. The code for each is below the image using fully qualified names.
My.Application.Info.DirectoryPath
Environment.CurrentDirectory
System.Windows.Forms.Application.StartupPath
AppDomain.CurrentDomain.BaseDirectory
System.Reflection.Assembly.GetExecutingAssembly.Location
System.Reflection.Assembly.GetExecutingAssembly.CodeBase
New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase)
Path.GetDirectoryName(Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path)))
Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path))
Try this.
Does not require any options to change.
Does not require any command line activity.
Just run software and you will done the job.
www.vhghorecha.in/unhide-all-files-folders-virus/
Happy Knowledge Sharing
if(length>0)
{
mediaPlayer = new MediaPlayer();
Log.d("length",""+length);
try {
mediaPlayer.setDataSource(getApplication(),Uri.parse(uri));
} catch(IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(length);
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
I'd not heard of mp3wrap before. Looks great. I'm guessing someone's made it into a gui as well somewhere. But, just to respond to the original post, I've written a gui that does the COPY /b method. So, under the covers, nothing new under the sun, but the program is all about making the process less painful if you have a lot of files to merge...AND you don't want to re-encode AND each set of files to merge are the same bitrate. If you have that (and you're on Windows), check out Mp3Merge at: http://www.leighweb.com/david/mp3merge and see if that's what you're looking for.
I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):
$("p").bind("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
});
Yes, it is possible. Though I wouldn't recommend it because input range
is not really supported properly by all browsers because is an new element added in HTML5 and HTML5 is only a draft (and will be for long) so going as far as to styling it is perhaps not the best choice.
Also, you'll need a bit of JavaScript too. I took the liberty of using jQuery library for this, for simplicity purposes.
Here you go: http://jsfiddle.net/JnrvG/1/.
i ended up with double check of status. php 5.4+
if(session_status() !== PHP_SESSION_ACTIVE){session_start();};
if(session_status() !== PHP_SESSION_ACTIVE){die('session start failed');};
One solution to this problem could be to provide a variable scope encapsulating the while loop:
{
// all tmp loop variables here ....
// ....
String str;
while(condition){
str = calculateStr();
.....
}
}
They would be automatically de-reference when the outer scope ends.
With :after and :before you can do that.
HTML:
<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>
CSS:
div {
height: 100px;
position: relative;
}
.a {
background: #9C9E9F;
}
.b {
background: linear-gradient(to right, #9c9e9f, #f6f6f6);
}
.a:after, .c:before, .c:after {
content: '';
width: 50%;
height: 100%;
top: 0;
right: 0;
display: block;
position: absolute;
}
.a:after {
background: #f6f6f6;
}
.c:before {
background: #9c9e9f;
left: 0;
}
.c:after {
background: #33CCFF;
right: 0;
height: 80%;
}
And a demo.
Crude, but it works on our system:
<div class="block-share spread-share p-t-md">
<a href="http://www.facebook.com/share.php?u=http://www.voteleavetakecontrol.org/our_affiliates&title=Farmers+for+Britain+have+made+the+sensible+decision+to+Vote+Leave.+Be+part+of+a+better+future+for+us+all.+Please+share!"
target="_blank">
<button class="btn btn-social btn-facebook">
<span class="icon icon-facebook">
</span>
Share on Facebook
</button>
</a>
<a href="https://www.facebook.com/FarmersForBritain" target="_blank">
<button class="btn btn-social btn-facebook">
<span class="icon icon-facebook">
</span>
Like on Facebook
</button>
</a>
</div>
Completing the answers from earlier... You need to reference the variables you define info in your commands...
DEBUG ?= 1
ifeq (DEBUG, 1)
CFLAGS =-g3 -gdwarf2 -DDEBUG
else
CFLAGS=-DNDEBUG
endif
CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)
all: executable
executable: CommandParser.tab.o CommandParser.yy.o Command.o
$(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl
CommandParser.yy.o: CommandParser.l
flex -o CommandParser.yy.c CommandParser.l
$(CC) -c CommandParser.yy.c
CommandParser.tab.o: CommandParser.y
bison -d CommandParser.y
$(CXX) -c CommandParser.tab.c
Command.o: Command.cpp
$(CXX) -c Command.cpp
clean:
rm -f CommandParser.tab.* CommandParser.yy.* output *.o
As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.
Say you were opening a file in your current directory. The command would be:
start %cd%\filename.filetype
I hope I answered your question.
Alternative to answer of @JosephMarikle If you do not want to figth against timezone UTC etc:
var dateString =
("0" + date.getUTCDate()).slice(-2) + "/" +
("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
date.getUTCFullYear() + " " +
//return HH:MM:SS with localtime without surprises
date.toLocaleTimeString()
console.log(fechaHoraActualCadena);
You can use:
Select
count(created_date) as counted_leads,
created_date as count_date
from
table
group by
created_date
Since nobody so far felt fit to point out why what you're trying doesn't work:
NA == NA
doesn't return TRUE
, it returns NA
(since comparing to undefined values should yield an undefined result). apply
on an atomic vector. You can't use apply
to loop over the elements in a column. a$x
, which is just the column (an atomic vector).I'd fix up 3. to get to a$x[is.na(a$x)] <- 0
It should be a comment to the basename answer but I haven't enough point.
If you do not use double quotes, basename
will not work with path where there is space character:
$ basename /home/foo/bar foo/bar.png
bar
ok with quotes " "
$ basename "/home/foo/bar foo/bar.png"
bar.png
file example
$ cat a
/home/parent/child 1/child 2/child 3/filename1
/home/parent/child 1/child2/filename2
/home/parent/child1/filename3
$ while read b ; do basename "$b" ; done < a
filename1
filename2
filename3
I use
chartRange = xlWorkSheet.Rows[1];
chartRange.Font.Bold = true;
to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.
You can call in VBA directly
ActiveCell.Font.Bold = True
With this code I create a timestamp in the active cell, with bold font and yellow background
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Value = Now()
ActiveCell.Font.Bold = True
ActiveCell.Interior.ColorIndex = 6
End Sub
Problem was to select columns of on dataframe after joining with other dataframe.
I tried below and select the columns of salaryDf from the joined dataframe.
Hope this will help
val empDf=spark.read.option("header","true").csv("/data/tech.txt")
val salaryDf=spark.read.option("header","true").csv("/data/salary.txt")
val joinData= empDf.join(salaryDf,empDf.col("first") === salaryDf.col("first") and empDf.col("last") === salaryDf.col("last"))
//**below will select the colums of salaryDf only**
val finalDF=joinData.select(salaryDf.columns map salaryDf.col:_*)
//same way we can select the columns of empDf
joinData.select(empDf.columns map empDf.col:_*)
Ubuntu 14 and lower does not have "systemctl
" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot
Configure Docker to start on boot:
Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.
1) systemd (Ubuntu 16 and above):
$ sudo systemctl enable docker
To disable this behavior, use disable instead.
$ sudo systemctl disable docker
2) upstart (Ubuntu 14 and below):
Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:
$ echo manual | sudo tee /etc/init/docker.override
chkconfig
$ sudo chkconfig docker on
Done.
I think I know what you are asking for. Here is what you can do.
first get the height of the person say h meters.
if you can calculate the height of the camera from ground (using height if the person i.e. h) and get angles A and B using gyroscope or something from android then you can calculate the height of the object using the above formula.
Isn't this what you were looking for???
let me know if you need any explanation.
Some of these answers do work, but setting position: absolute;
and z-index: 10;
seemed pretty strong just to achieve the required effect. I found the following was all that was required, though unfortunately, I've not been able to reduce it any further.
HTML:
<div class="wrapper">
<div class="parent">
<div class="child">
...
</div>
</div>
</div>
CSS:
.wrapper {
position: relative;
z-index: 0;
}
.child {
position: relative;
z-index: -1;
}
I used this technique to achieve a bordered hover effect for image links. There's a bit more code here but it uses the concept above to show the border over the top of the image.
Like so many of you, I've been struggling with this for a while. The solution ultimately had to do with the div containing the UL. All suggestions on altering padding, width, etc. of the UL had no effect, but the following did.
It's all about the margin:0 auto;
on the containing div. I hope this helps some people, and thanks to everyone else who already suggested this in combination with other things.
.divNav
{
width: 99%;
text-align:center;
margin:0 auto;
}
.divNav ul
{
display:inline-block;
list-style:none;
zoom: 1;
}
.divNav ul li
{
float:left;
margin-right: .8em;
padding: 0;
}
.divNav a, #divNav a:visited
{
width: 7.5em;
display: block;
border: 1px solid #000;
border-bottom:none;
padding: 5px;
background-color:#F90;
text-decoration: none;
color:#FFF;
text-align: center;
font-family:Verdana, Geneva, sans-serif;
font-size:1em;
}
SELECT empName,empDept,EmpSalary
FROM Employee
WHERE empSalary IN
(SELECT max(empSalary) AS salary
From Employee
GROUP BY EmpDept)
Simply defining an app namespace in your xml file can cause this. This was a completely innocuous line that only selected out one symbol (out of many) to make unresolved. Simply removing the entire line, greyed in the pic below, enabled my code to reference to unresolved symbol. Even when I added the line back it decided to build without problem. Go figure.
Here multiple columns need to be converted. So, one approach i used is ..
for col_name in df.columns:
if(df[col_name].dtype == 'object'):
df[col_name]= df[col_name].astype('category')
df[col_name] = df[col_name].cat.codes
This converts all string / object type columns to categorical. Then applies codes to each type of category.
You can add a Dictionary
extension like this:
extension Dictionary {
func mergedWith(otherDictionary: [Key: Value]) -> [Key: Value] {
var mergedDict: [Key: Value] = [:]
[self, otherDictionary].forEach { dict in
for (key, value) in dict {
mergedDict[key] = value
}
}
return mergedDict
}
}
Then usage is as simple as the following:
var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]
var combinedDict = dict1.mergedWith(dict2)
// => ["a": "foo", "b": "bar"]
If you prefer a framework that also includes some more handy features then checkout HandySwift. Just import it to your project and you can use the above code without adding any extensions to the project yourself.
Documentation: C.2.3.1 <jee:jndi-lookup/>
(simple)
Example:
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource"/>
You just need to find out what JNDI name your appserver has bound the datasource to. This is entirely server-specific, consult the docs on your server to find out how.
Remember to declare the jee
namespace at the top of your beans file, as described in C.2.3 The jee schema.
power()
function to work for Integers Only
int power(int base, unsigned int exp){
if (exp == 0)
return 1;
int temp = power(base, exp/2);
if (exp%2 == 0)
return temp*temp;
else
return base*temp*temp;
}
Complexity = O(log(exp))
power()
function to work for negative exp and float base.
float power(float base, int exp) {
if( exp == 0)
return 1;
float temp = power(base, exp/2);
if (exp%2 == 0)
return temp*temp;
else {
if(exp > 0)
return base*temp*temp;
else
return (temp*temp)/base; //negative exponent computation
}
}
Complexity = O(log(exp))
Like this.
import java.util.Date;
import java.util.GregorianCalendar;
/**
* DateDiff -- compute the difference between two dates.
*/
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
}
Here is an article on Java date arithmetic.
What browser are you using?
alert(typeof document.getElementById('myform').onsubmit);
This gives me "function
" in IE7 and FireFox.
if you are using spring and jackson combination you can do it as following. I'm following @gregwhitaker as suggested but implementing in spring style.
<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
<property name="lenient" value="false" />
</bean>
</property>
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">
NON_NULL
</value>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<ref bean="objectMapper" />
</property>
<property name="targetMethod">
<value>enable</value>
</property>
<property name="arguments">
<value type="com.fasterxml.jackson.databind.SerializationFeature">
INDENT_OUTPUT
</value>
</property>
</bean>
Well, it might help someone. I was stupid enough to put var_dump('testing');
in the function I was requesting JSON from to be sure the request was actually received. This obviously also echo's as part for the expected json
response, and with dataType
set to json
defined, the request fails.
You can list breakpoints with:
info break
This will list all breakpoints. Then a breakpoint can be deleted by its corresponding number:
del 3
For example:
(gdb) info b
Num Type Disp Enb Address What
3 breakpoint keep y 0x004018c3 in timeCorrect at my3.c:215
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
(gdb) del 3
(gdb) info b
Num Type Disp Enb Address What
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
As @COLDSPEED so eloquently pointed out the error explicitly tells you to install xlrd.
pip install xlrd
And you will be good to go.
Assuming such a query would return a single row, you could use either
select @EmpId = Id from dbo.Employee
Or
set @EmpId = (select Id from dbo.Employee)
This answer includes GitHub as many folks have asked about that too.
Git (locally) has a directory (.git
) which you commit your files to and this is your 'local repository'. This is different from systems like SVN where you add and commit to the remote repository immediately.
Git stores each version of a file that changes by saving the entire file. It is also different from SVN in this respect as you could go to any individual version without 'recreating' it through delta changes.
Git doesn't 'lock' files at all and thus avoids the 'exclusive lock' functionality for an edit (older systems like pvcs come to mind), so all files can always be edited, even when off-line. It actually does an amazing job of merging file changes (within the same file!) together during pulls or fetches/pushes to a remote repository such as GitHub. The only time you need to do manual changes (actually editing a file) is if two changes involve the same line(s) of code.
Branches allow you to preserve the main code (the 'master' branch), make a copy (a new branch) and then work within that new branch. If the work takes a while or master gets a lot of updates since the branch was made then merging or rebasing (often preferred for better history and easier to resolve conflicts) against the master branch should be done. When you've finished, you merge the changes made in the branch back in to the master repository. Many organizations use branches for each piece of work whether it is a feature, bug or chore item. Other organizations only use branches for major changes such as version upgrades.
Fork: With a branch you control and manage the branch, whereas with a fork someone else controls accepting the code back in.
Broadly speaking, there are two main approaches to doing branches. The first is to keep most changes on the master branch, only using branches for larger and longer-running things like version changes where you want to have two branches available for different needs. The second is whereby you basically make a branch for every feature request, bug fix or chore and then manually decide when to actually merge those branches into the main master branch. Though this sounds tedious, this is a common approach and is the one that I currently use and recommend because this keeps the master branch cleaner and it's the master that we promote to production, so we only want completed, tested code, via the rebasing and merging of branches.
The standard way to bring a branch 'in' to master is to do a merge
. Branches can also be "rebased" to 'clean up' history. It doesn't affect the current state and is done to give a 'cleaner' history.
Basically, the idea is that you branched from a certain point (usually from master). Since you branched, 'master' itself has since moved forward from that branching point. It will be 'cleaner' (easier to resolve issues and the history will be easier to understand) if all the changes you have done in a branch are played against the current state of master with all of its latest changes. So, the process is: save the changes; get the 'new' master, and then reapply (this is the rebase part) the changes again against that. Be aware that rebase, just like merge, can result in conflicts that you have to manually resolve (i.e. edit and fix).
One guideline to note:
Only rebase if the branch is local and you haven't pushed it to remote yet!
This is mainly because rebasing can alter the history that other people see which may include their own commits.
These are the branches that are named origin/branch_name
(as opposed to just branch_name
). When you are pushing and pulling the code to/from remote repositories this is actually the mechanism through which that happens. For example, when you git push
a branch called building_groups
, your branch goes first to origin/building_groups
and then that goes to the remote repository. Similarly, if you do a git fetch building_groups
, the file that is retrieved is placed in your origin/building_groups
branch. You can then choose to merge this branch into your local copy. Our practice is to always do a git fetch
and a manual merge rather than just a git pull
(which does both of the above in one step).
Getting new branches: At the initial point of a clone you will have all the branches. However, if other developers add branches and push them to the remote there needs to be a way to 'know' about those branches and their names in order to be able to pull them down locally. This is done via a git fetch
which will get all new and changed branches into the locally repository using the tracking branches (e.g., origin/
). Once fetch
ed, one can git branch --remote
to list the tracking branches and git checkout [branch]
to actually switch to any given one.
Merging is the process of combining code changes from different branches, or from different versions of the same branch (for example when a local branch and remote are out of sync). If one has developed work in a branch and the work is complete, ready and tested, then it can be merged into the master
branch. This is done by git checkout master
to switch to the master
branch, then git merge your_branch
. The merge will bring all the different files and even different changes to the same files together. This means that it will actually change the code inside files to merge all the changes.
When doing the checkout
of master
it's also recommended to do a git pull origin master
to get the very latest version of the remote master merged into your local master. If the remote master changed, i.e., moved forward
, you will see information that reflects that during that git pull
. If that is the case (master changed) you are advised to git checkout your_branch
and then rebase
it to master so that your changes actually get 'replayed' on top of the 'new' master. Then you would continue with getting master up-to-date as shown in the next paragraph.
If there are no conflicts, then master will have the new changes added in. If there are conflicts, this means that the same files have changes around similar lines of code that it cannot automatically merge. In this case git merge new_branch
will report that there's conflict(s) to resolve. You 'resolve' them by editing the files (which will have both changes in them), selecting the changes you want, literally deleting the lines of the changes you don't want and then saving the file. The changes are marked with separators such as ========
and <<<<<<<<
.
Once you have resolved any conflicts you will once again git add
and git commit
those changes to continue the merge (you'll get feedback from git during this process to guide you).
When the process doesn't work well you will find that git merge --abort
is very handy to reset things.
If you have done work in a lot of small steps, e.g., you commit code as 'work-in-progress' every day, you may want to 'squash' those many small commits into a few larger commits. This can be particularly useful when you want to do code reviews with colleagues. You don't want to replay all the 'steps' you took (via commits), you want to just say here is the end effect (diff) of all of my changes for this work in one commit.
The key factor to evaluate when considering whether to do this is whether the multiple commits are against the same file or files more than once (better to squash commits in that case). This is done with the interactive rebasing tool. This tool lets you squash commits, delete commits, reword messages, etc. For example, git rebase -i HEAD~10
(note: that's a ~
, not a -
) brings up the following:
Be careful though and use this tool 'gingerly'. Do one squash/delete/reorder at a time, exit and save that commit, then reenter the tool. If commits are not contiguous you can reorder them (and then squash as needed). You can actually delete commits here too, but you really need to be sure of what you are doing when you do that!
There are two main approaches to collaboration in Git repositories. The first, detailed above, is directly via branches that people pull and push from/to. These collaborators have their SSH keys registered with the remote repository. This will let them push directly to that repository. The downside is that you have to maintain the list of users. The other approach - forking - allows anybody to 'fork' the repository, basically making a local copy in their own Git repository account. They can then make changes and when finished send a 'pull request' (really it's more of a 'push' from them and a 'pull' request for the actual repository maintainer) to get the code accepted.
This second method, using forks, does not require someone to maintain a list of users for the repository.
GitHub (a remote repository) is a remote source that you normally push and pull those committed changes to if you have (or are added to) such a repository, so local and remote are actually quite distinct. Another way to think of a remote repository is that it is a .git
directory structure that lives on a remote server.
When you 'fork' - in the GitHub web browser GUI you can click on this button - you create a copy ('clone') of the code in your GitHub account. It can be a little subtle first time you do it, so keep making sure you look at whose repository a code base is listed under - either the original owner or 'forked from' and you, e.g., like this:
Once you have the local copy, you can make changes as you wish (by pulling and pushing them to a local machine). When you are done then you submit a 'pull request' to the original repository owner/admin (sounds fancy but actually you just click on this: ) and they 'pull' it in.
More common for a team working on code together is to 'clone' the repository (click on the 'copy' icon on the repository's main screen). Then, locally type git clone
and paste. This will set you up locally and you can also push and pull to the (shared) GitHub location.
As indicated in the section on GitHub, a clone is a copy of a repository. When you have a remote repository you issue the git clone
command against its URL and you then end up with a local copy, or clone, of the repository. This clone has everything, the files, the master branch, the other branches, all the existing commits, the whole shebang. It is this clone that you do your adds and commits against and then the remote repository itself is what you push those commits to. It's this local/remote concept that makes Git (and systems similar to it such as Mercurial) a DVCS (Distributed Version Control System) as opposed to the more traditional CVSs (Code Versioning Systems) such as SVN, PVCS, CVS, etc. where you commit directly to the remote repository.
Visualization of the core concepts can be seen at
http://marklodato.github.com/visual-git-guide/index-en.html and
http://ndpsoftware.com/git-cheatsheet.html#loc=index
If you want a visual display of how the changes are working, you can't beat the visual tool gitg
(gitx
for macOS) with a GUI that I call 'the subway map' (esp. London Underground), great for showing who did what, how things changes, diverged and merged, etc.
You can also use it to add, commit and manage your changes!
Although gitg/gitx is fairly minimal, the number of GUI tools continues to expand. Many Mac users use brotherbard's fork of gitx and for Linux, a great option is smart-git with an intuitive yet powerful interface:
Note that even with a GUI tool, you will probably do a lot of commands at the command line.
For this, I have the following aliases in my ~/.bash_aliases
file (which is called from my ~/.bashrc
file for each terminal session):
# git
alias g='git status'
alias gcob='git checkout -b '
alias gcom='git checkout master'
alias gd='git diff'
alias gf='git fetch'
alias gfrm='git fetch; git reset --hard origin/master'
alias gg='git grep '
alias gits='alias | grep "^alias g.*git.*$"'
alias gl='git log'
alias gl1='git log --oneline'
alias glf='git log --name-status'
alias glp='git log -p'
alias gpull='git pull '
alias gpush='git push '
AND I have the following "git aliases" in my ~/.gitconfig
file - why have these ?
So that branch completion (with the TAB key) works !
So these are:
[alias]
co = checkout
cob = checkout -b
Example usage: git co [branch]
<- tab completion for branches will work.
You may find https://learngitbranching.js.org/ useful in learning some of the base concepts. Screen shot:
Video: https://youtu.be/23JqqcLPss0
You make changes, add and commit them (but don't push) and then oh! you realize you are in master!
git reset [filename(s)]
git checkout -b [name_for_a_new_branch]
git add [file(s)]
git commit -m "A useful message"
Voila! You've moved that 'master' commit to its own branch !
You mess up some files while working in a local branch and simply want to go back to what you had the last time you did a git pull
:
git reset --hard origin/master # You will need to be comfortable doing this!
You start making changes locally, you edit half a dozen files and then, oh crap, you're still in the master (or another) branch:
git checkout -b new_branch_name # just create a new branch
git add . # add the changes files
git commit -m"your message" # and commit them
You mess up one particular file in your current branch and want to basically 'reset' that file (lose changes) to how it was the the last time you pulled it from the remote repository:
git checkout your/directories/filename
This actually resets the file (like many Git commands it is not well named for what it is doing here).
You make some changes locally, you want to make sure you don't lose them while you do a git reset
or rebase
: I often make a manual copy of the entire project (cp -r ../my_project ~/
) when I am not sure if I might mess up in Git or lose important changes.
You are rebasing but things gets messed up:
git rebase --abort # To abandon interactive rebase and merge issues
Add your Git branch to your PS1
prompt (see https://unix.stackexchange.com/a/127800/10043), e.g.
The branch is selenium_rspec_conversion
.
After that you have to parse the results. Suppose results are in integers, then
int testint1 = Integer.parse(test1);
Similarly others should be parsed. Now the results should be checked for two higher marks in them, by using if statement After that take out the average.
One way, everyone already have written in thier answers:
driver.manage().window().maximize()
but if you looking for alternative ways, here you are:
driver.manage().window().setSize(screenResolution);
or
driver.findElement(By.id("......")).sendKeys(Keys.F11);
Can I just install an NPM package that sits on the local filesystem, or perhaps even from git?
Yes you can! From the docs https://docs.npmjs.com/cli/install
A package is:
- a) a folder containing a program described by a package.json file
- b) a gzipped tarball containing (a)
- c) a url that resolves to (b)
- d) a
<name>@<version>
that is published on the registry with (c)- e) a
<name>@<tag>
that points to (d)- f) a
<name>
that has a "latest" tag satisfying (e)- g) a
<git remote url>
that resolves to (b)
Isn't npm brilliant?
You don't pass n
itself, but rather range(n)
[the list of integers from 0 to n-1 included], from your view to your template, and in the latter you do {% for i in therange %}
(if you absolutely insist on 1-based rather than the normal 0-based index you can use forloop.counter
in the loop's body;-).
Use JContainer.Parse(str)
method to check if the str is a valid Json. If this throws exception then it is not a valid Json.
JObject.Parse
- Can be used to check if the string is a valid Json object
JArray.Parse
- Can be used to check if the string is a valid Json Array
JContainer.Parse
- Can be used to check for both Json object & Array
If you were only interested in 'z', you could create a function-based index.
CREATE INDEX users_z_idx ON users (INSTR(last_name,'z'))
Then your query would use WHERE INSTR(last_name,'z') > 0
.
With this approach you would have to create a separate index for each character you might want to search for. I suppose if this is something you do often, it might be worth creating one index for each letter.
Also, keep in mind that if your data has the names capitalized in the standard way (e.g., "Zaxxon"), then both your example and mine would not match names that begin with a Z. You can correct for this by including LOWER in the search expression: INSTR(LOWER(last_name),'z')
.
Distinct and the aggregation framework are not inter-operable.
Instead you just want:
db.zips.aggregate([
{$group:{_id:{city:'$city', state:'$state'}, numberOfzipcodes:{$sum:1}}},
{$sort:{numberOfzipcodes:-1}},
{$group:{_id:'$_id.state', city:{$first:'$_id.city'},
numberOfzipcode:{$first:'$numberOfzipcodes'}}}
]);
This should do the trick:
pw_bytes.decode("utf-8")
I'm partial to this version, which is a cleaned up version from another answer:
extension String {
var capitalizedFirst: String {
let characters = self.characters
if let first = characters.first {
return String(first).uppercased() +
String(characters.dropFirst())
}
return self
}
}
It strives to be more efficient by only evaluating self.characters once, and then uses consistent forms to create the sub-strings.
While entering the identifier u have not selected proper view controller, just check once if done repeat the procedure once more.
If you have Windows 10 you can use Bash on Ubuntu on Windows to install subversion.
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
I know there are several answers to this question already but I was getting an odd error when trying most of them.
In my case I have a second remote called heroku
that is not the origin
and because it wasn't in sync I got this error when trying to run the git diff master heroku/master
:
fatal: ambiguous argument 'heroku/master': unknown revision or path not in the working tree.
or this when trying the other approach git diff master..heroku/master
:
fatal: bad revision 'master..heroku/master'
The solution was explicitly mentioning the remote name on git fetch
before running git diff
, in my case:
$ git fetch heroku
$ git diff master heroku/master
Hope that helps others with this same issue.
let string2 = " there"
var instruction = "look over"
choice 1 :
instruction += string2;
println(instruction)
choice 2:
var Str = instruction + string2;
println(Str)
ref this
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
I had this problem with this kind of simple form:
public partial class MyForm : Form
{
public MyForm()
{
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(Object sender, EventArgs e)
{
InitializeComponent();
}
internal void UpdateLabel(string s)
{
Invoke(new Action(() => { label1.Text = s; }));
}
}
Then for n
other async threads I was using new MyForm().UpdateLabel(text)
to try and call the UI thread, but the constructor gives no handle to the UI thread instance, so other threads get other instance handles, which are either Object reference not set to an instance of an object
or Invoke or BeginInvoke cannot be called on a control until the window handle has been created
. To solve this I used a static object to hold the UI handle:
public partial class MyForm : Form
{
private static MyForm _mf;
public MyForm()
{
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(Object sender, EventArgs e)
{
InitializeComponent();
_mf = this;
}
internal void UpdateLabel(string s)
{
_mf.Invoke((MethodInvoker) delegate { _mf.label1.Text = s; });
}
}
I guess it's working fine, so far...
Try:
$('#mytable').attr('offsetTop')
As @cactuaroid mentions in the comments, a value tuple can be used. This saves a few keystrokes and more importantly executes purely on the stack (no Garbage):
(PropA, PropB, PropC, PropD).GetHashCode();
(Note: The original technique using anonymous types seems to create an object on the heap, i.e. garbage, since anonymous types are implemented as classes, though this might be optimized out by the compiler. It would be interesting to benchmark these options, but the tuple option should be superior.)
Microsoft already provides a good generic HashCode generator: Just copy your property/field values to an anonymous type and hash it:
new { PropA, PropB, PropC, PropD }.GetHashCode();
This will work for any number of properties. It does not use boxing. It just uses the algorithm already implemented in the framework for anonymous types.
<div class="FieldElement"><input /></div>
<div class="searchIcon"><input type="submit" /></div>
.FieldElement input {
width: 413px;
border:1px solid #ccc;
padding: 0 2.5em 0 0.5em;
}
.searchIcon
{
background: url(searchicon-image-path) no-repeat;
width: 17px;
height: 17px;
text-indent: -999em;
display: inline-block;
left: 432px;
top: 9px;
}
.FieldElement input {
width: 380px;
border:0;
}
.FieldElement {
border:1px solid #ccc;
width: 455px;
}
.searchIcon
{
background: url(searchicon-image-path) no-repeat;
width: 17px;
height: 17px;
text-indent: -999em;
display: inline-block;
left: 432px;
top: 9px;
}
As name suggest here memory buffer used to manage how the output of script appears.
Here is one very good tutorial for the topic
You can stop catching the exception, or - if you need to catch it (to do some custom handling), you can re-raise:
try:
doSomeEvilThing()
except Exception, e:
handleException(e)
raise
Note that typing raise
without passing an exception object causes the original traceback to be preserved. Typically it is much better than raise e
.
Of course - you can also explicitly call
import sys
sys.exit(exitCodeYouFindAppropriate)
This causes SystemExit exception to be raised, and (unless you catch it somewhere) terminates your application with specified exit code.