Using ES6 modules you can do the following:
import {version} from './package.json';
With ObsoleteAttribute
you can to show the deprecated method.
Obsolete attribute has three constructor:
[Obsolete]:
is a no parameter constructor and is a default using this attribute.[Obsolete(string message)]:
in this format you can getmessage
of why this method is deprecated.[Obsolete(string message, bool error)]:
in this format message is very explicit buterror
means, in compilation time, compiler must be showing error and cause to fail compiling or not.
This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.
Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.
On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.
Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.
This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).
Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.
Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.
A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.
From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.
From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.
However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!
The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:
develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).
bind to a specific version of the API (which becomes apparent) but only for a limited time
For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):
http://shonzilla/api/customers/1234 http://shonzilla/api/v3.0/customers/1234 http://shonzilla/api/v3/customers/1234
In addition, API clients that still try to point to the old API should be informed to use the latest previous API version, if the API version they're using is obsolete or not supported anymore. So accessing any of the obsolete URIs like these:
http://shonzilla/api/v2.2/customers/1234 http://shonzilla/api/v2.0/customers/1234 http://shonzilla/api/v2/customers/1234 http://shonzilla/api/v1.1/customers/1234 http://shonzilla/api/v1/customers/1234
should return any of the 30x HTTP status codes that indicate redirection that are used in conjunction with Location
HTTP header that redirects to the appropriate version of resource URI which remain to be this one:
http://shonzilla/api/customers/1234
There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:
301 Moved permanently indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a versioned resource URI been replaced by a resource permalink.
302 Found indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).
other scenarios can be found in Redirection 3xx chapter of HTTP 1.1 specification
Unlike many of the other answers, this solution uses completely free software.
Firstly, create a file called Resources.rc
like this:
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,0
PRODUCTVERSION 1,0,0,0
{
BLOCK "StringFileInfo"
{
BLOCK "040904b0"
{
VALUE "CompanyName", "ACME Inc.\0"
VALUE "FileDescription", "MyProg\0"
VALUE "FileVersion", "1.0.0.0\0"
VALUE "LegalCopyright", "© 2013 ACME Inc. All Rights Reserved\0"
VALUE "OriginalFilename", "MyProg.exe\0"
VALUE "ProductName", "My Program\0"
VALUE "ProductVersion", "1.0.0.0\0"
}
}
BLOCK "VarFileInfo"
{
VALUE "Translation", 0x409, 1200
}
}
Next, use GoRC to compile it to a .res
file using:
GoRC /fo Resources.res Resources.rc
(see my comment below for a mirror of GoRC.exe
)
Then use Resource Hacker in CLI mode to add it to an existing .exe
:
ResHacker -add MyProg.exe, MyProg.exe, Resources.res,,,
That's it!
For someone who is going to show Force Update Alert based on version number I have a following Idea. This may be used when comparing the versions between Android Current App version and firebase remote config version. This is not exactly the answer for the question asked but this will help someone definitely.
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Main
{
static String firebaseVersion = "2.1.3"; // or 2.1
static String appVersion = "2.1.4";
static List<String> firebaseVersionArray;
static List<String> appVersionArray;
static boolean isNeedToShowAlert = false;
public static void main (String[]args)
{
System.out.println ("Hello World");
firebaseVersionArray = new ArrayList<String>(Arrays.asList(firebaseVersion.split ("\\.")));
appVersionArray = new ArrayList<String>(Arrays.asList(appVersion.split ("\\.")));
if(appVersionArray.size() < firebaseVersionArray.size()) {
appVersionArray.add("0");
}
if(firebaseVersionArray.size() < appVersionArray.size()) {
firebaseVersionArray.add("0");
}
isNeedToShowAlert = needToShowAlert(); //Returns false
System.out.println (isNeedToShowAlert);
}
static boolean needToShowAlert() {
boolean result = false;
for(int i = 0 ; i < appVersionArray.size() ; i++) {
if (Integer.parseInt(appVersionArray.get(i)) == Integer.parseInt(firebaseVersionArray.get(i))) {
continue;
} else if (Integer.parseInt(appVersionArray.get(i)) > Integer.parseInt(firebaseVersionArray.get(i))){
result = false;
break;
} else if (Integer.parseInt(appVersionArray.get(i)) < Integer.parseInt(firebaseVersionArray.get(i))) {
result = true;
break;
}
}
return result;
}
}
You can run this code by copy pasting in https://www.onlinegdb.com/online_java_compiler
brew versions
and brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/<COMMIT-HASH>/Formula/<Formula>.rb
not supported now.
You can try like this:
$ brew extract --version 5.6.2 gradle vitahlin/core
$ brew install [email protected]
You should first check the app version on the market and compare it with the version of the app on the device. If they are different, it may be an update available. In this post I wrote down the code for getting the current version of market and current version on the device and compare them together. I also showed how to show the update dialog and redirect the user to the update page. Please visit this link: https://stackoverflow.com/a/33925032/5475941
If you're looking for the current and the latest versions of all your installed packages, you can also use:
npm outdated
I Know this old post but Just wanted to add few points. The standard for such problems is what works best for the situation. understanding the need for such storage, and potential use of the historical/audit/change tracking data is very importat.
Audit (security purpose) : Use a common table for all your auditable tables. define structure to store column name , before value and after value fields.
Archive/Historical: for cases like tracking previous address , phone number etc. creating a separate table FOO_HIST is better if you your active transaction table schema does not change significantly in the future(if your history table has to have the same structure). if you anticipate table normalization , datatype change addition/removal of columns, store your historical data in xml format . define a table with the following columns (ID,Date, Schema Version, XMLData). this will easily handle schema changes . but you have to deal with xml and that could introduce a level of complication for data retrieval .
That's a bit of informal terminology.
As far as Git is concerned, every other repository is just a remote.
Generally speaking, upstream is where you cloned from (the origin). Downstream is any project that integrates your work with other works.
The terms are not restricted to Git repositories.
For instance, Ubuntu is a Debian derivative, so Debian is upstream for Ubuntu.
Hudson can be configured to ignore changes to certain paths and files so that it does not prompt a new build.
On the job configuration page, under Source Code Management, click the Advanced button. In the Excluded Regions box you enter one or more regular expression to match exclusions.
For example to ignore changes to the version.properties file you can use:
/MyProject/trunk/version.properties
This will work for languages other than C# and allows you to store your version info within subversion.
My 2 cents: I had this scenario: I had to parse version numbers out of a string literal. (I know this is very different from the original question, but googling to find a regex for parsing version number showed this thread at the top, so adding this answer here)
So the string literal would be something like: "Service version 1.2.35.564 is running!"
I had to parse the 1.2.35.564 out of this literal. Taking a cue from @ajborley, my regex is as follows:
(?:(\d+)\.)?(?:(\d+)\.)?(?:(\d+)\.\d+)
A small C# snippet to test this looks like below:
void Main()
{
Regex regEx = new Regex(@"(?:(\d+)\.)?(?:(\d+)\.)?(?:(\d+)\.\d+)", RegexOptions.Compiled);
Match version = regEx.Match("The Service SuperService 2.1.309.0) is Running!");
version.Value.Dump("Version using RegEx"); // Prints 2.1.309.0
}
Use a version GET
variable to prevent browser caching.
Appending ?v=AUTO_INCREMENT_VERSION
to the end of your url prevents browser caching - avoiding any and all cached scripts.
You can do more advanced versioning using build scripts such as Build Versioning
I use this rule for my applications:
x.y.z
Where:
Example:
This works for me: (i.e. I only need 2 columns of the 30+ returned by sp_help_job
)
SELECT name, current_execution_status
FROM OPENQUERY (MYSERVER,
'EXEC msdb.dbo.sp_help_job @job_name = ''My Job'', @job_aspect = ''JOB''');
Before this would work, I needed to run this:
sp_serveroption 'MYSERVER', 'DATA ACCESS', TRUE;
....to update the sys.servers
table. (i.e. Using a self-reference within OPENQUERY seems to be disabled by default.)
For my simple requirement, I ran into none of the problems described in the OPENQUERY section of Lance's excellent link.
Rossini, if you need to dynamically set those input parameters, then use of OPENQUERY becomes a little more fiddly:
DECLARE @innerSql varchar(1000);
DECLARE @outerSql varchar(1000);
-- Set up the original stored proc definition.
SET @innerSql =
'EXEC msdb.dbo.sp_help_job @job_name = '''+@param1+''', @job_aspect = N'''+@param2+'''' ;
-- Handle quotes.
SET @innerSql = REPLACE(@innerSql, '''', '''''');
-- Set up the OPENQUERY definition.
SET @outerSql =
'SELECT name, current_execution_status
FROM OPENQUERY (MYSERVER, ''' + @innerSql + ''');';
-- Execute.
EXEC (@outerSql);
I'm not sure of the differences (if any) between using sp_serveroption
to update the existing sys.servers
self-reference directly, vs. using sp_addlinkedserver
(as described in Lance's link) to create a duplicate/alias.
Note 1: I prefer OPENQUERY over OPENROWSET, given that OPENQUERY does not require the connection-string definition within the proc.
Note 2:
Having said all this: normally I would just use INSERT ... EXEC :) Yes, it's 10 mins extra typing, but if I can help it, I prefer not to jigger around with:
(a) quotes within quotes within quotes, and
(b) sys tables, and/or sneaky self-referencing Linked Server setups (i.e. for these, I need to plead my case to our all-powerful DBAs :)
However in this instance, I couldn't use a INSERT ... EXEC construct, as sp_help_job
is already using one. ("An INSERT EXEC statement cannot be nested.")
$("#chkdwn2").change(function(){
$("#dropdown").slideToggle();
});
try
const MyFunctionnalComponent: React.FC = props => {_x000D_
useEffect(() => {_x000D_
// Using an IIFE_x000D_
(async function anyNameFunction() {_x000D_
await loadContent();_x000D_
})();_x000D_
}, []);_x000D_
return <div></div>;_x000D_
};
_x000D_
You could just write it out in multiline like this,
$ cat dict.go
package main
import "fmt"
func main() {
items := map[string]interface{}{
"foo": map[string]int{
"strength": 10,
"age": 2000,
},
"bar": map[string]int{
"strength": 20,
"age": 1000,
},
}
for key, value := range items {
fmt.Println("[", key, "] has items:")
for k,v := range value.(map[string]int) {
fmt.Println("\t-->", k, ":", v)
}
}
}
And the output:
$ go run dict.go
[ foo ] has items:
--> strength : 10
--> age : 2000
[ bar ] has items:
--> strength : 20
--> age : 1000
This confusing me a bit too.
The problem is on "path" attribute in your xml file.
From this document FileProvider 'path' is a subdirectory, but in another document (camera/photobasics) shown 'path' is full path.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
I just change this 'path' to full path and it just work.
"Gets the path or UNC location of the loaded file that contains the manifest."
See: http://msdn.microsoft.com/en-us/library/system.reflection.assembly.location.aspx
Application.ResourceAssembly.Location
You override $today
in the if statement.
if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;
It is then not a Date() object anymore - hence the error.
'In' a string, you cant. Strings are immutable. You can easily create a second string with:
String second = first.replaceFirst("(.)(.)", "$2$1");
You can use Detach/Attach Option in SQL Server Management Studio.
Check this: Move a Database Using Detach and Attach
componentDidUpdate(prevProps){
if (this.state.authToken==null&&prevProps.authToken==null) {
AccountKit.getCurrentAccessToken()
.then(token => {
if (token) {
AccountKit.getCurrentAccount().then(account => {
this.setState({
authToken: token,
loggedAccount: account
});
});
} else {
console.log("No user account logged");
}
})
.catch(e => console.log("Failed to get current access token", e));
}
}
In the tradition of itoa()
:
#define btoa(x) ((x)?"true":"false")
bool x = true;
printf("%s\n", btoa(x));
Yes, but you need to declare it readonly
instead of const
:
public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
The reason is that const
can only be applied to a field whose value is known at compile-time. The array initializer you've shown is not a constant expression in C#, so it produces a compiler error.
Declaring it readonly
solves that problem because the value is not initialized until run-time (although it's guaranteed to have initialized before the first time that the array is used).
Depending on what it is that you ultimately want to achieve, you might also consider declaring an enum:
public enum Titles { German, Spanish, Corrects, Wrongs };
Under Python 3.x, you can do this nicely:
>>> head, *tail = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
A new feature in 3.x is to use the *
operator in unpacking, to mean any extra values. It is described in PEP 3132 - Extended Iterable Unpacking. This also has the advantage of working on any iterable, not just sequences.
It's also really readable.
As described in the PEP, if you want to do the equivalent under 2.x (without potentially making a temporary list), you have to do this:
it = iter(iterable)
head, tail = next(it), list(it)
As noted in the comments, this also provides an opportunity to get a default value for head
rather than throwing an exception. If you want this behaviour, next()
takes an optional second argument with a default value, so next(it, None)
would give you None
if there was no head element.
Naturally, if you are working on a list, the easiest way without the 3.x syntax is:
head, tail = seq[0], seq[1:]
The referenced field must be a "Key" in the referenced table, not necessarily a primary key. So the "car_id" should either be a primary key or be defined with NOT NULL and UNIQUE constraints in the "Cars" table.
And moreover, both fields must be of the same type and collation.
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
You need add parameter errors='coerce'
to function to_numeric
:
ID = pd.to_numeric(ID, errors='coerce')
If ID
is column:
df.ID = pd.to_numeric(df.ID, errors='coerce')
but non numeric are converted to NaN
, so all values are float
.
For int
need convert NaN
to some value e.g. 0
and then cast to int
:
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
Sample:
df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
ID
0 4806105017087
1 4806105017087
2 CN414149
print (pd.to_numeric(df.ID, errors='coerce'))
0 4.806105e+12
1 4.806105e+12
2 NaN
Name: ID, dtype: float64
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
ID
0 4806105017087
1 4806105017087
2 0
EDIT: If use pandas 0.25+ then is possible use integer_na
:
df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
ID
0 4806105017087
1 4806105017087
2 NaN
This is a more statble code for all Android versions and possibly for new ones
void checkGPS() {
LocationRequest locationRequest = LocationRequest.create();
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.d("GPS_main", "OnSuccess");
// GPS is ON
}
});
task.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull final Exception e) {
Log.d("GPS_main", "GPS off");
// GPS off
if (e instanceof ResolvableApiException) {
ResolvableApiException resolvable = (ResolvableApiException) e;
try {
resolvable.startResolutionForResult(ActivityMain.this, REQUESTCODE_TURNON_GPS);
} catch (IntentSender.SendIntentException e1) {
e1.printStackTrace();
}
}
}
});
}
And you can handle the GPS state changes here
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Static_AppVariables.REQUESTCODE_TURNON_GPS) {
switch (resultCode) {
case Activity.RESULT_OK:
// GPS was turned on;
break;
case Activity.RESULT_CANCELED:
// User rejected turning on the GPS
break;
default:
break;
}
}
}
1) set the UIViewControllerBasedStatusBarAppearance to YES in the plist
2) in viewDidLoad do a [self setNeedsStatusBarAppearanceUpdate];
3) add the following method:
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
UPDATE:
also check developers-guide-to-the-ios-7-status-bar
Here is an example with @RequestBody, First look at the controller !!
public ResponseEntity<Void> postNewProductDto(@RequestBody NewProductDto newProductDto) {
...
productService.registerProductDto(newProductDto);
return new ResponseEntity<>(HttpStatus.CREATED);
....
}
And here is angular controller
function postNewProductDto() {
var url = "/admin/products/newItem";
$http.post(url, vm.newProductDto).then(function () {
//other things go here...
vm.newProductMessage = "Product successful registered";
}
,
function (errResponse) {
//handling errors ....
}
);
}
And a short look at form
<label>Name: </label>
<input ng-model="vm.newProductDto.name" />
<label>Price </label>
<input ng-model="vm.newProductDto.price"/>
<label>Quantity </label>
<input ng-model="vm.newProductDto.quantity"/>
<label>Image </label>
<input ng-model="vm.newProductDto.photo"/>
<Button ng-click="vm.postNewProductDto()" >Insert Item</Button>
<label > {{vm.newProductMessage}} </label>
I noticed that Visual Studio's built-in error detector kind of gets goofy if you try to do this:
var intvar = @(ViewBag.someNumericValue);
Because @(ViewBag.someNumericValue) has the potential to evaluate to nothing, which would lead to the following erroneous JavaScript being generated:
var intvar = ;
If you're certain that someNemericValue will be set to a valid numeric data type, you can avoid having Visual Studio warnings by doing the following:
var intvar = Number(@(ViewBag.someNumericValue));
This might generate the following sample:
var intvar = Number(25.4);
And it works for negative numbers. In the event that the item isn't in your viewbag, Number() evaluates to 0.
No more Visual Studio warnings! But make sure the value is set and is numeric, otherwise you're opening doors to possible JavaScript injection attacks or run time errors.
Have you taken a look at ExpandoObject?
From MSDN:
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").
Allowing you to do cool things like:
dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
{
Console.WriteLine(msg);
};
dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);
Based on your actual code you may be more interested in:
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
That way you just need:
var dyn = GetDynamicObject(new Dictionary<string, object>()
{
{"prop1", 12},
});
Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;
Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.
XCOPY /S folder1\data.zip copy_of_folder1
XCOPY /S folder1\info.txt copy_of_folder1
EDIT: If you want to preserve the empty folders (which, on rereading your post, you seem to) use /E instead of /S.
You can mark source directory as a source root like so:
Per Arvand:
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select Open declaration in layout/simple_list_item_1.xml. It'll direct you to the contents of the XML.
From there, if you then hover over the resulting simple_list_item_1.xml tab in the Editor, you'll see the file is located at C:\Data\applications\Android\android-sdk\platforms\android-19\data\res\layout\simple_list_item_1.xml (or equivalent location for your installation).
Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.
The .ascx:
<script type="text/javascript">
function checkAgreement(source, args)
{
var elem = document.getElementById('<%= chkAgree.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
function checkAge(source, args)
{
var elem = document.getElementById('<%= chkAge.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
</script>
<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />
<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAgreement">
You must agree to the terms and conditions.
</asp:CustomValidator>
<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAge">
You must be 18 years or older to continue.
</asp:CustomValidator>
And the codebehind:
Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
e.IsValid = chkAgree.Checked
End Sub
Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
e.IsValid = chkAge.Checked
End Sub
If its a maven project, add the below dependency in your pom file
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>
use this function to get a standard array back of the type you are after...
return get_object_vars($booking);
This worked for me,
CREATE TABLE newtable LIKE oldtable;
Replicates newtable with old table
INSERT newtable SELECT * FROM oldtable
;
Copies all the row data to new table.
Thank you
In vb60 you can do this:
Public Cn As ADODB.Connection
'open connection
Dim Rs As ADODB.Recordset
Set Rs = Cn.OpenSchema(adSchemaColumns, Array(Empty, Empty, UCase("Table"), UCase("field")))
'and sample (valRs is my function for rs.fields("CHARACTER_MAXIMUM_LENGTH").value):
RT_Charactar_Maximum_Length = (ValRS(Rs, "CHARACTER_MAXIMUM_LENGTH"))
rt_Tipo = (ValRS(Rs, "DATA_TYPE"))
You need to use the val()
function to get the textbox value. text
does not exist as a property only as a function and even then its not the correct function to use in this situation.
var from = $("input#fromAddress").val()
val()
is the standard function for getting the value of an input.
I understand much better the output of:
git diff <remote-tracking branch> <local branch>
that shows me what is going to be dropped and what is going to be added if I push the local branch. Of course it is the same, just the inverse, but for me is more readable and I'm more confortable looking at what is going to happen.
Below works for first tr
of the table under thead
table thead tr:first-child {
background: #f2f2f2;
}
And this works for the first tr
of thead
and tbody
both:
table thead tbody tr:first-child {
background: #f2f2f2;
}
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
More than one line can be drawn on the same chart by using the lines()
function
# Create the data for the chart.
v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)
# Give the chart file a name.
png(file = "line_chart_2_lines.jpg")
# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall",
main = "Rain fall chart")
lines(t, type = "o", col = "blue")
# Save the file.
dev.off()
If you want to rollback and migrate you can run:
rake db:migrate:redo
That's the same as:
rake db:rollback
rake db:migrate
This should display 'Tue':
new SimpleDateFormat("EEE").format(new Date());
This should display 'Tuesday':
new SimpleDateFormat("EEEE").format(new Date());
This should display 'T':
new SimpleDateFormat("EEEEE").format(new Date());
So your specific example would be:
new SimpleDateFormat("yyyy-MM-EEE").format(new Date());
Very simple method:
.create:before {
content: url(image.png);
}
Works in all modern browsers and IE8+.
Edit
Don't use this on large sites though. The :before pseudo-element is horrible in terms of performance.
Maybe remove the semi-colon after set because now the where statement doesn't belong to the update statement. Also the idRequest
could be a problem, better write BookingRequest.idRequest
Use SequenceEqual
to check for sequence equality because Equals
method checks for reference equality.
var a = ints1.SequenceEqual(ints2);
Or if you don't care about elements order use Enumerable.All
method:
var a = ints1.All(ints2.Contains);
The second version also requires another check for Count
because it would return true even if ints2
contains more elements than ints1
. So the more correct version would be something like this:
var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;
In order to check inequality just reverse the result of All
method:
var a = !ints1.All(ints2.Contains)
$personCount=1;
while ($personCount < 10) {
$result=0;
$result.= $personCount . "person ";
$personCount++;
echo $result;
}
Another way to achieve the same outcome, which I found useful for a pandas dataframe.
As suggested below by mousetail:
bool(1 - False)
bool(1 - True)
You can't use primitive types as generic arguments in Java. Use instead:
Map<String, Integer> myMap = new HashMap<String, Integer>();
With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:
myMap.put("foo", 3);
instead of:
myMap.put("foo", new Integer(3));
Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:
int i = myMap.get("foo");
instead of:
int i = myMap.get("foo").intValue();
The implicit call to intValue()
means if the key isn't found it will generate a NullPointerException
, for example:
int i = myMap.get("bar"); // NullPointerException
The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:
Integer i = (Integer)myMap.get("foo");
To give you an example, this code is perfectly legal:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");
Sometimes a dependency added with ng add
will add more than one package, typing npm uninstall lib1 lib2
could be error prone and slow, so just remove the not needed libraries from package.json
and run npm i
The solution with the anonymous type should work fine. LINQ can only represent equijoins (with join clauses, anyway), and indeed that's what you've said you want to express anyway based on your original query.
If you don't like the version with the anonymous type for some specific reason, you should explain that reason.
If you want to do something other than what you originally asked for, please give an example of what you really want to do.
EDIT: Responding to the edit in the question: yes, to do a "date range" join, you need to use a where clause instead. They're semantically equivalent really, so it's just a matter of the optimisations available. Equijoins provide simple optimisation (in LINQ to Objects, which includes LINQ to DataSets) by creating a lookup based on the inner sequence - think of it as a hashtable from key to a sequence of entries matching that key.
Doing that with date ranges is somewhat harder. However, depending on exactly what you mean by a "date range join" you may be able to do something similar - if you're planning on creating "bands" of dates (e.g. one per year) such that two entries which occur in the same year (but not on the same date) should match, then you can do it just by using that band as the key. If it's more complicated, e.g. one side of the join provides a range, and the other side of the join provides a single date, matching if it falls within that range, that would be better handled with a where
clause (after a second from
clause) IMO. You could do some particularly funky magic by ordering one side or the other to find matches more efficiently, but that would be a lot of work - I'd only do that kind of thing after checking whether performance is an issue.
There are two ways to get the ip address :
let ip = req.ip
let ip = req.connection.remoteAddress;
But there is a problem with above approaches.
If you are running your app behind Nginx or any proxy, every single IP addresses will be 127.0.0.1
.
So, the best solution to get the ip address of user is :-
let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
The 'Enter some junk value' answer didn't do the trick for me, my site was continuing to load despite the entered junk.
Instead I added the following line to the top of the .htaccess file:
deny from all
This will quickly let you know if .htaccess is being picked up or not. If the .htaccess is being used, the files in that folder won't load at all.
list objects are unhashable. you might want to turn them in to tuples though.
I believe contentOffset
will give you an object containing the top-left scroll offset:
http://facebook.github.io/react-native/docs/scrollview.html#contentoffset
Set the min SDK version in your project's AndroidManifest.xml file and in the toolbar search for "Sync Projects with Gradle Files" icon. It works for me.
Also look for your project's build.gradle file and update the min sdk version.
Edit: It actually seems that editing the file shortcut breaks the Win+x, c key shortcut. (Moral of the story: only change system files you know how to fix! Eventually after a Windows update it repaired itself.)
What I ended up doing is creating a new customized Command Prompt shortcut in the start folder and pinned to the taskbar that I launch instead of cmd.exe
As other answers point out, changing the registry Autorun cmd start location is a bad idea because it silently will break other programs that shell out for tasks, like Visual Studio Code.
You should just change whatever shortcut you use to open cmd to have a Start In entry.
If you use Win+x, c to launch cmd, you can edit the Start In for
"%LOCALAPPDATA%\Microsoft\Windows\WinX\Group3\02 - Command Prompt.lnk"
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
The most efficient way (before django 1.2) is this:
if orgs.count() == 0:
# no results
else:
# alrigh! let's continue...
My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......
function CheckLength()
{
var keyCode = event.keyCode
if (keyCode == 13)
{
document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
}
}
This CSS effectively hides the spin-button for webkit browsers (have tested it in Chrome 7.0.517.44 and Safari Version 5.0.2 (6533.18.5)):
input::-webkit-outer-spin-button,_x000D_
input::-webkit-inner-spin-button {_x000D_
/* display: none; <- Crashes Chrome on hover */_x000D_
-webkit-appearance: none;_x000D_
margin: 0; /* <-- Apparently some margin are still there even though it's hidden */_x000D_
}_x000D_
_x000D_
input[type=number] {_x000D_
-moz-appearance:textfield; /* Firefox */_x000D_
}
_x000D_
<input type="number" step="0.01" />
_x000D_
You can always use the inspector (webkit, possibly Firebug for Firefox) to look for matched CSS properties for the elements you are interested in, look for Pseudo elements. This image shows results for an input element type="number":
Since TypeScript 1.8+
you can use simple simple import
statement like:
import { ClassName } from '../relative/path/to/file';
or the wildcard version:
import * as YourName from 'global-or-relative';
Read more: https://www.typescriptlang.org/docs/handbook/modules.html
mvc:annotation-driven is a tag added in Spring 3.0 which does the following:
context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.
A more complete answer would be it is not possible with ftp(at least the ftp program installed on centos 6).
Since you wanted an un-attended process, "pts"'s answer will work fine.
Do the unattended upload with curl instead of ftp:
curl -u user:password -T file ftp://server/dir/file
%40 doesn't appear to work.
[~]# ftp domain.com
ftp: connect: Connection refused
ftp> quit
[~]# ftp some_user%[email protected]
ftp: some_user%[email protected]: Name or service not known
ftp> quit
All I've got is to open the ftp program and use the domain and enter the user when asked. Usually, a password is required anyway, so the interactive nature probably isn't problematic.
[~]# ftp domain.com
Connected to domain.com (173.254.13.235).
220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
220-You are user number 2 of 1000 allowed.
220-Local time is now 02:47. Server port: 21.
220-This is a private system - No anonymous login
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.
Name (domain.com:user): [email protected]
331 User [email protected] OK. Password required
Password:
230 OK. Current restricted directory is /
Remote system type is UNIX.
Using binary mode to transfer files.
See: Multiple-line-syntax
It also support variables in multiline string, for example:
String name="zzg";
String lines = ""/**~!{
SELECT *
FROM user
WHERE name="$name"
}*/;
System.out.println(lines);
Output:
SELECT *
FROM user
WHERE name="zzg"
Here's a simple little utility class that you can use to convert local date times from zone to zone, including a utility method directly to convert a local date time from the current zone to UTC (with main method so you can run it and see the results of a simple test):
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public final class DateTimeUtil {
private DateTimeUtil() {
super();
}
public static void main(final String... args) {
final LocalDateTime now = LocalDateTime.now();
final LocalDateTime utc = DateTimeUtil.toUtc(now);
System.out.println("Now: " + now);
System.out.println("UTC: " + utc);
}
public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
final ZonedDateTime zonedtime = time.atZone(fromZone);
final ZonedDateTime converted = zonedtime.withZoneSameInstant(toZone);
return converted.toLocalDateTime();
}
public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);
}
public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);
}
public static LocalDateTime toUtc(final LocalDateTime time) {
return DateTimeUtil.toUtc(time, ZoneId.systemDefault());
}
}
A Minor contribution.
As many of them explain about 'when to use' and 'use with foreach'. I thought of adding Another States Difference here as requested in question about the difference between both IEnumerable an IEnumerator.
I created the below code sample based on the below discussion threads.
IEnumerable , IEnumerator vs foreach, when to use what What is the difference between IEnumerator and IEnumerable?
Enumerator preserves the state (iteration position) between function calls while iterations the other hand Enumerable does not.
Here is the tested example with comments to understand.
Experts please add/correct me.
static void EnumerableVsEnumeratorStateTest()
{
IList<int> numList = new List<int>();
numList.Add(1);
numList.Add(2);
numList.Add(3);
numList.Add(4);
numList.Add(5);
numList.Add(6);
Console.WriteLine("Using Enumerator - Remembers the state");
IterateFrom1to3(numList.GetEnumerator());
Console.WriteLine("Using Enumerable - Does not Remembers the state");
IterateFrom1to3Eb(numList);
Console.WriteLine("Using Enumerable - 2nd functions start from the item 1 in the collection");
}
static void IterateFrom1to3(IEnumerator<int> numColl)
{
while (numColl.MoveNext())
{
Console.WriteLine(numColl.Current.ToString());
if (numColl.Current > 3)
{
// This method called 3 times for 3 items (4,5,6) in the collection.
// It remembers the state and displays the continued values.
IterateFrom3to6(numColl);
}
}
}
static void IterateFrom3to6(IEnumerator<int> numColl)
{
while (numColl.MoveNext())
{
Console.WriteLine(numColl.Current.ToString());
}
}
static void IterateFrom1to3Eb(IEnumerable<int> numColl)
{
foreach (int num in numColl)
{
Console.WriteLine(num.ToString());
if (num>= 5)
{
// The below method invokes for the last 2 items.
//Since it doesnot persists the state it will displays entire collection 2 times.
IterateFrom3to6Eb(numColl);
}
}
}
static void IterateFrom3to6Eb(IEnumerable<int> numColl)
{
Console.WriteLine();
foreach (int num in numColl)
{
Console.WriteLine(num.ToString());
}
}
I have the feeling that the check should be different
new: h < 768 || w < 1024
You can try this
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
</dependencies>`
You can just rewrite it as:
int qempty(){ return(f==r);}
Which does the same thing as said in the other answers.
I am an Ionic framework user and the one I found that would consistently provide the current controller's $scope is:
angular.element(document.querySelector('ion-view[nav-view="active"]')).scope()
I suspect this can be modified to fit most scenarios regardless of framework (or not) by finding the query that will target the specific DOM element(s) that are available only during a given controller instance.
The problem is that C++ is a statically-typed language, meaning that if something is declared as a string
, it's a string, and if something is declared as a double
, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!"
to a double
, there's no meaningful conversion. Sure, you could just set the double
to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.
To fix this, don't buffer the file contents into a string. Instead, just read directly into the double
:
double lol;
openfile >> lol;
This reads the value directly as a real number, and if an error occurs will cause the stream's .fail()
method to return true. For example:
double lol;
openfile >> lol;
if (openfile.fail()) {
cout << "Couldn't read a double from the file." << endl;
}
I know you already have several answers, but I was on a similar situation where my team didn't want to depend on a heavy libraries or anything related to bootstrap since we are using material so I made our own autocomplete control, using material-like styles, you can use my autocomplete or at least you can give a look to give you some guiadance, there was not much documentation on simple examples on how to upload your components to be shared on NPM.
All,
From what I'm seeing here all answers are wrong, especially if you entered the sudo mode, with all returning 'root' instead of the logged in user. The answer is in using 'who' and finding eh 'tty1' user and extracting that. Thw "w" command works the same and var=$SUDO_USER gets the real logged in user.
Cheers!
TBNK
Just use os.listdir
and os.path.isfile
instead of os.walk
.
Example:
import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
# do something
But be careful while applying this to other directory, like
files = [f for f in os.listdir(somedir) if os.path.isfile(f)].
which would not work because f
is not a full path but relative to the current dir.
Therefore, for filtering on another directory, do os.path.isfile(os.path.join(somedir, f))
(Thanks Causality for the hint)
Current version 1.4.0 has clearBtn
option:
$('.datepicker').datepicker({
clearBtn: true
});
Besides adding button to interface it allows to delete value from input box manually.
You can do it with jQuery.
I have my video and controls in their own <div>
like this:
<div id="videoPlayer" style="width:520px; -webkit-border-radius:10px; height:420px; background-color:white; position:relative; float:left; left:25px; top:55px;" align="center">
<video controls width="500" height="400" style="background-color:black; margin-top:10px; -webkit-border-radius:10px;">
<source src="videos/gin.mp4" type="video/mp4" />
</video>
<script>
video.removeAttribute('controls');
</script>
<div id="vidControls" style="position:relative; width:100%; height:50px; background-color:white; -webkit-border-bottom-left-radius:10px; -webkit-border-bottom-right-radius:10px; padding-top:10px; padding-bottom:10px;">
<table width="100%" height="100%" border="0">
<tr>
<td width="100%" align="center" valign="middle" colspan="4"><input class="vidPos" type="range" value="0" step="0.1" style="width:500px;" /></td>
</tr>
<tr>
<td width="100%" align="center" valign="middle"><a href="javascript:;" class="playVid">Play</a></td>
<td width="100%" align="center" valign="middle"><a href="javascript:;" class="vol">Vol</a></td>
<td width="100%" align="left" valign="middle"><p class="timer"><strong>0:00</strong> / 0:00</p></td>
<td width="100%" align="center" valign="middle"><a href="javascript:;" class="fullScreen">Full</a></td>
</tr>
</table>
</div>
</div>
And then my jQuery for the .fullscreen class is:
var fullscreen = 0;
$(".fullscreen").click(function(){
if(fullscreen == 0){
fullscreen = 1;
$("video").appendTo('body');
$("#vidControls").appendTo('body');
$("video").css('position', 'absolute').css('width', '100%').css('height', '90%').css('margin', 0).css('margin-top', '5%').css('top', '0').css('left', '0').css('float', 'left').css('z-index', 600);
$("#vidControls").css('position', 'absolute').css('bottom', '5%').css('width', '90%').css('backgroundColor', 'rgba(150, 150, 150, 0.5)').css('float', 'none').css('left', '5%').css('z-index', 700).css('-webkit-border-radius', '10px');
}
else
{
fullscreen = 0;
$("video").appendTo('#videoPlayer');
$("#vidControls").appendTo('#videoPlayer');
//change <video> css back to normal
//change "#vidControls" css back to normal
}
});
It needs a little cleaning up as I'm still working on it but that should work for most browsers as far as I can see.
Hope it helps!
I know this is late but it might be of some use:
echo "<pre>";
print_r($array);
echo "</pre>";
Implement an interface to call your function in your method
interface IMyInterface
{
void MyinterfaceMethod();
}
IMyInterface MyObj = obj as IMyInterface;
if ( MyObj != null)
{
MyMethod(IMyInterface MyObj );
}
$ git branch -D <branch-name>
[NOTE]:
-D
is a shortcut for --delete --force
.
You need to use:
number_map[int(x)]
Note the square brackets!
Your CA file must have been in a binary X.509 format instead of Base64 encoding; it needs to be a regular DER or PEM in order for it to be added successfully to the list of trusted CAs on your server.
To proceed, do place your CA file inside your /usr/share/pki/ca-trust-source/anchors/
directory, then run the command line below (you might need sudo privileges based on your settings);
# CentOS 7, Red Hat 7, Oracle Linux 7
update-ca-trust
Please note that all trust settings available in the /usr/share/pki/ca-trust-source/anchors/
directory are interpreted with a lower priority compared to the ones placed under the /etc/pki/ca-trust/source/anchors/
directory which may be in the extended BEGIN TRUSTED file format.
For Ubuntu and Debian systems, /usr/local/share/ca-certificates/
is the preferred directory for that purpose.
As such, you need to place your CA file within the /usr/local/share/ca-certificates/
directory, then update the of trusted CAs by running, with sudo privileges where required, the command line below;
update-ca-certificates
Try this
SELECT DATEDIFF(DAY, DATEADD(day, -1, '2013-03-13 00:00:00.000'), GETDATE())
OR
SELECT DATEDIFF(DAY, DATEADD(day, -1, @CreatedDate), GETDATE())
I'd rather than ternary if-statements go with a switch-case. For example:
switch($result->vocation){
case 1:
echo "Sorcerer";
break;
case 2:
echo "Druid";
break;
case 3:
echo "Paladin";
break;
case 4:
echo "Knight";
break;
case 5:
echo "Master Sorcerer";
break;
case 6:
echo "Elder Druid";
break;
case 7:
echo "Royal Paladin";
break;
default:
echo "Elite Knight";
break;
}
According to documentation class date
is a parent for class datetime
. And isinstance()
method will give you True
in all cases. If you need to distinguish datetime
from date
you should check name of the class
import datetime
datetime.datetime.now().__class__.__name__ == 'date' #False
datetime.datetime.now().__class__.__name__ == 'datetime' #True
datetime.date.today().__class__.__name__ == 'date' #True
datetime.date.today().__class__.__name__ == 'datetime' #False
I've faced with this problem when i have different formatting rules for dates and dates with time
A little note to the SeanJA answer.
Interestingly, if you use KnockoutJS and jQuery together the following inputs with different IDs, but with the same data-bind observable:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: first_dt" id="date_2" class="datepick" />
will bind one (the same) datepicker to both of the inputs (even though they have different ids or names).
Use separate observables in your ViewModel to bind a separate datepicker to each input:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: second_dt" id="date_2" class="datepick" />
Initialization:
$('.datepick').each(function(){
$(this).datepicker();
});
You could just set the width to auto. Then the width of the div will equal 0 if it has no content.
width:auto;
I had the same issue (same error on heroku, working on local machine) and I tried all the solutions listed here including
heroku run rails console
which ran without error messages. I tried heroku run rake db:migrate
and heroku run rake db:migrate:reset
a few times. None of this solved the problem. On going through some files that are used in production but not in dev environment, I found some whitespace in the puma.rb file to be the culprit. Hope this helps someone who has the same issue.
Changing this made it work
ActiveRecord::Base.establish_connection
End
to
ActiveRecord::Base.establish_connection
end
... | paste -sd+ - | bc
is the shortest one I've found (from the UNIX Command Line blog).
Edit: added the -
argument for portability, thanks @Dogbert and @Owen.
If you need a standalone connection pool, my preference goes to C3P0 over DBCP (that I've mentioned in this previous answer), I just had too much problems with DBCP under heavy load. Using C3P0 is dead simple. From the documentation:
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("swaldman");
cpds.setPassword("test-password");
// the settings below are optional -- c3p0 can work with defaults
cpds.setMinPoolSize(5);
cpds.setAcquireIncrement(5);
cpds.setMaxPoolSize(20);
// The DataSource cpds is now a fully configured and usable pooled DataSource
But if you are running inside an application server, I would recommend to use the built-in connection pool it provides. In that case, you'll need to configure it (refer to the documentation of your application server) and to retrieve a DataSource via JNDI:
DataSource ds = (DataSource) new InitialContext().lookup("jdbc/myDS");
Try go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically.
PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for.[...]
See Cannot find or open the PDB file in Visual Studio C++ 2010
As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
Replace backup.ab with the path to your file.
This is the same as thefreeman but more in pythonic way using list and dictionary comprehension
columns = cursor.description
result = [{columns[index][0]:column for index, column in enumerate(value)} for value in cursor.fetchall()]
pprint.pprint(result)
You can try using something like this. In this case I used one stored procedure to get more data tables and export all of them using CSV.
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace bo
{
class Program
{
static private void CreateCSVFile(DataTable dt, string strFilePath)
{
#region Export Grid to CSV
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
int iColCount = dt.Columns.Count;
// First we will write the headers.
//DataTable dt = m_dsProducts.Tables[0];
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(";");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount -1 )
{
sw.Write(";");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
#endregion
}
static void Main(string[] args)
{
string strConn = "connection string to sql";
string direktorij = @"d:";
SqlConnection conn = new SqlConnection(strConn);
SqlCommand command = new SqlCommand("sp_ado_pos_data", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add('@skl_id', SqlDbType.Int).Value = 158;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
for (int i = 0; i < ds.Tables.Count; i++)
{
string datoteka = (string.Format(@"{0}tablea{1}.csv", direktorij, i));
DataTable tabela = ds.Tables[i];
CreateCSVFile(tabela,datoteka );
Console.WriteLine("Generišem tabelu {0}", datoteka);
}
Console.ReadKey();
}
}
}
question:-.DISPLAY EMPLOYEE NAME , HIS DATE OF JOINING, HIS MANAGER NAME & HIS MANAGER'S DATE OF JOINING. ANS:- select e1.ename Emp,e1.hiredate, e2.eName Mgr,e2.hiredate from emp e1, emp e2 where e1.mgr = e2.empno
Here is how I do (2018 version ?) :
const index = [...el.parentElement.children].indexOf(el);
Tadaaaam. And, if ever you want to consider raw text nodes too, you can do this instead :
const index = [...el.parentElement.childNodes].indexOf(el);
I spread the children into an array as they are an HTMLCollection (thus they do not work with indexOf).
Be careful that you are using Babel or that browser coverage is sufficient for what you need to achieve (thinkings about the spread operator which is basically an Array.from behind the scene).
Firstly, a code block that looks like (function(){})()
is merely a function that is executed in place. Let's break it down a little.
1. (
2. function(){}
3. )
4. ()
Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help
1. function(){ .. }
2. (1)
3. 2()
You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.
An example of how it would be used.
(function(doc){
doc.location = '/';
})(document);//This is passed into the function above
As for the other questions about the plugins:
Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.
Type 2: This is again not a plugin as it does not extend the $.fn
object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.
Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.
Building on Roland's answer, using tidyr
to reshape the data from wide to long:
library(tidyr)
library(ggplot2)
df <- read.table(text="Rank F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10", header=TRUE)
df %>%
gather(variable, value, F1:F3) %>%
ggplot(aes(x = Rank, y = value, fill = variable)) +
geom_bar(stat = "identity")
My domain was quite complex. I took the value returned by window.location.host
in the developer console and pasted that value in the recaptcha admin white list. Then I cleared the cache and reloaded the page.
You have two possibilities:
org.springframework.beans.factory.config.MethodInvokingFactoryBean
to invoke a static setter.In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.
public void setTheProperty(Object value) {
foo.bar.Class.STATIC_VALUE = value;
}
but in order to do this you need to have an instance of a bean that will expose this setter (its more like an workaround).
In the second case it would be done as follows:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Class.setTheProperty"/> <property name="arguments"> <list> <ref bean="theProperty"/> </list> </property> </bean>
On you case you will add a new setter on the Utils
class:
public static setDataBaseAttr(Properties p)
and in your context you will configure it with the approach exemplified above, more or less like:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/> <property name="arguments"> <list> <ref bean="dataBaseAttr"/> </list> </property> </bean>
Since this question was originally asked, Google's Guava library now includes a powerful and flexible cache. I would recommend using this.
see org.springframework.core.DefaultParameterNameDiscoverer class
DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
String[] params = discoverer.getParameterNames(MathUtils.class.getMethod("isPrime", Integer.class));
If you want to keep the keys of the initial array and also add an array that has keys, then use the function below:
function insertArrayAtPosition( $array, $insert, $position ) {
/*
$array : The initial array i want to modify
$insert : the new array i want to add, eg array('key' => 'value') or array('value')
$position : the position where the new array will be inserted into. Please mind that arrays start at 0
*/
return array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
}
Call example:
$array = insertArrayAtPosition($array, array('key' => 'Value'), 3);
You can target that div from your stylesheet in a number of ways.
Simply use
.col-md-6:first-child {
background-color: blue;
}
Another way is to assign a class to one div and then apply the style to that class.
<div class="col-md-6 blue"></div>
.blue {
background-color: blue;
}
There are also inline styles.
<div class="col-md-6" style="background-color: blue"></div>
Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary
class from the section and add you custom class to the div.
.blue {_x000D_
background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
<div class="col-xs-6">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
<div class="col-xs-6 blue">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</section>
_x000D_
Set a breakpoint as usual. Right click it. Click Condition.
In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
Sample JSON fetch request:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
You can simply hide the <td>
tag content by just including a style attribute: style = "display:none"
For e.g
<td style = "display:none" >
<p> I'm invisible </p>
</td>
With Winforms you can use Form.BackColor to do this.
From within the Form's code:
BackColor = Color.LightPink;
If you mean a WPF Window you can use the Background property.
From within the Window's code:
Background = Brushes.LightPink;
I know this answer is coming years after the fact and there is already a great JSP answer by Will Hartung, but there is Facelets, they are even mentioned in the answers from the linked question in the original question.
Facelets SO tag description
Facelets is an XML-based view technology for the JavaServer Faces framework. Designed specifically for JSF, Facelets is intended to be a simpler and more powerful alternative to JSP-based views. Initially a separate project, the technology was standardized as part of JSF 2.0 and Java-EE 6 and has deprecated JSP. Almost all JSF 2.0 targeted component libraries do not support JSP anymore, but only Facelets.
Sadly the best plain tutorial description I found was on Wikipedia and not a tutorial site. In fact the section describing templates even does along the lines of what the original question was asking for.
Due to the fact that Java-EE 6 has deprecated JSP I would recommend going with Facelets despite the fact that it looks like there might be more required for little to no gain over JSP.
I got this error when I tried to set a column as unique when there was already duplicate data in the column OR if you try to add a column and set it as unique when there is already data in the table.
I had a table with 5 rows and I tried to add a unique column and it failed because all 5 of those rows would be empty and thus not unique.
I created the column without the unique index set, then populated the data then set it as unique and everything worked.
try this
sudo chmod -R 0777 /opt/lampp/htdocs/testproject
Note that the C and C++ standards define two kinds of implementations: freestanding and hosted.
Allowed forms 1:
int main (void)
int main (int argc, char *argv[])
main (void)
main (int argc, char *argv[])
/*... etc, similar forms with implicit int */
Comments:
The former two are explicitly stated as the allowed forms, the others are implicitly allowed because C90 allowed "implicit int" for return type and function parameters. No other form is allowed.
Any form or name of main is allowed 2.
Allowed forms 3:
int main (void)
int main (int argc, char *argv[])
/* or in some other implementation-defined manner. */
Comments:
C99 removed "implicit int" so main()
is no longer valid.
A strange, ambiguous sentence "or in some other implementation-defined manner" has been introduced. This can either be interpreted as "the parameters to int main()
may vary" or as "main can have any implementation-defined form".
Some compilers have chosen to interpret the standard in the latter way. Arguably, one cannot easily state that they are not conforming by citing the standard in itself, since it is is ambiguous.
However, to allow completely wild forms of main()
was probably(?) not the intention of this new sentence. The C99 rationale (not normative) implies that the sentence refers to additional parameters to int main
4.
Yet the section for hosted environment program termination then goes on arguing about the case where main does not return int 5. Although that section is not normative for how main should be declared, it definitely implies that main might be declared in a completely implementation-defined way even on hosted systems.
Any form or name of main is allowed 6.
Allowed forms 7:
int main (void)
int main (int argc, char *argv[])
/* or in some other implementation-defined manner. */
Any form or name of main is allowed 8.
Note that int main()
was never listed as a valid form for any hosted implementation of C in any of the above versions. In C, unlike C++, ()
and (void)
have different meanings. The former is an obsolescent feature which may be removed from the language. See C11 future language directions:
6.11.6 Function declarators
The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.
Allowed forms 9:
int main ()
int main (int argc, char *argv[])
Comments:
Note the empty parenthesis in the first form. C++ and C are different in this case, because in C++ this means that the function takes no parameters. But in C it means that it may take any parameter.
The name of the function called at startup is implementation-defined. If it is named main()
it must follow the stated forms 10:
// implementation-defined name, or
int main ()
int main (int argc, char *argv[])
Allowed forms 11:
int main ()
int main (int argc, char *argv[])
Comments:
The text of the standard has been changed but it has the same meaning.
The name of the function called at startup is implementation-defined. If it is named main()
it must follow the stated forms 12:
// implementation-defined name, or
int main ()
int main (int argc, char *argv[])
References
The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined.
The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9) or in some other implementation-defined manner.
The behavior of the arguments to main, and of the interaction of exit, main and atexit (see §7.20.4.2) has been codified to curb some unwanted variety in the representation of argv strings, and in the meaning of values returned by main.
The specification of argc and argv as arguments to main recognizes extensive prior practice. argv[argc] is required to be a null pointer to provide a redundant check for the end of the list, also on the basis of common practice.
main is the only function that may portably be declared either with zero or two arguments. (The number of other functions’ arguments must match exactly between invocation and definition.) This special case simply recognizes the widespread practice of leaving off the arguments to main when the program does not access the program argument strings. While many implementations support more than two arguments to main, such practice is neither blessed nor forbidden by the Standard; a program that defines main with three arguments is not strictly conforming (see §J.5.1.).
If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;11) reaching the
}
that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.
In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined.
This section is identical to the C99 one cited above.
This section is identical to the C99 one cited above.
An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:
int main() { /* ... */ }
and
int main(int argc, char* argv[]) { /* ... */ }
It is implementation-defined whether a program in a freestanding environment is required to define a main function.
An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both
— a function of () returning int and
— a function of (int, pointer to pointer to char) returning int
as the type of main (8.3.5).
This section is identical to the C++03 one cited above.
Do a str.replace('; ', ', ')
and then a str.split(', ')
Location locaton;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
mMap.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
mMap.addMarker(mp);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});}}
use the include is the easiest way as per
http://www.vistax64.com/powershell/168315-get-childitem-filter-files-multiple-extensions.html
An alternative quick and hacky solution if you want to get an overview of all the produres there are, or run into the issue of only getting the procedure header shown by SHOW CREATE PROCEDURE:
mysqldump --user=<user> -p --no-data --routines <database>
It will export the table descriptions as well, but no data. Works well for sniffing around unknown or forgotten schemas... ;)
Just reading the file into an array, one line per element, is trivial:
open my $handle, '<', $path_to_file;
chomp(my @lines = <$handle>);
close $handle;
Now the lines of the file are in the array @lines
.
If you want to make sure there is error handling for open
and close
, do something like this (in the snipped below, we open the file in UTF-8 mode, too):
my $handle;
unless (open $handle, "<:encoding(utf8)", $path_to_file) {
print STDERR "Could not open file '$path_to_file': $!\n";
# we return 'undefined', we could also 'die' or 'croak'
return undef
}
chomp(my @lines = <$handle>);
unless (close $handle) {
# what does it mean if close yields an error and you are just reading?
print STDERR "Don't care error while closing '$path_to_file': $!\n";
}
*Using Robot class you can do this, Try following code:
Actions action = new Actions(driver);
action.contextClick(WebElement).build().perform();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
[UPDATE]
CAUTION: Your Browser should always be in focus i.e. running in foreground while performing Robot Actions, other-wise any other application in foreground will receive the actions.
This looks like a homework question, so I'll just give you a few pointers:
Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.
You're not using Scanner for anything, and it's not needed here, get rid of it.
Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0;
may return true or false, depending on the value of a. But return fileName;
will just return the value of fileName, which is a String.
You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).
System.out.println("First Name: " + firstname);
System.out.println("Last Name: " + lastname);
or
System.out.println(String.format("First Name: %s", firstname));
System.out.println(String.format("Last Name: %s", lastname));
Hello friends if your getting any not class found exception in hibernate code it is the problem of jar files.here mainly two problems
1.I mean to say your working old version of hibernate may be 3.2 bellow.So if u try above 3.6 it will works fine
2.first checkes database connection.if it database working properly their was a mistake in ur program or jar file.
please check these two prioblems if it also not working you tried to IDE . I am using netbeanside 6.9 version.here hibernate working fine.you dont get any error from class not founnd exception..
I hope this one helps more
Please add below jQuery Migrate Plugin
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-1.4.1.min.js"></script>
The last line should read
cbh.appendChild(document.createTextNode(cap));
Appending the text (label?) to the same container as the checkbox, not the checkbox itself
Prints pubkey
and avoid the changed status by adding changed_when: False
to cat
task:
- name: Generate SSH keys for vagrant user
user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
- name: Check SSH public key
command: /bin/cat $home_directory/.ssh/id_rsa.pub
register: cat
changed_when: False
- name: Print SSH public key
debug: var=cat.stdout
- name: Wait for user to copy SSH public key
pause: prompt="Please add the SSH public key above to your GitHub account"
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.
If occurs during a postback: markup:
<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>
code:
try
{
do something
}
catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}
An update, several years later
This answer is old, and R has moved on. Tweaking read.table
to run a bit faster has precious little benefit. Your options are:
Using vroom
from the tidyverse package vroom
for importing data from csv/tab-delimited files directly into an R tibble. See Hector's answer.
Using fread
in data.table
for importing data from csv/tab-delimited files directly into R. See mnel's answer.
Using read_table
in readr
(on CRAN from April 2015). This works much like fread
above. The readme in the link explains the difference between the two functions (readr
currently claims to be "1.5-2x slower" than data.table::fread
).
read.csv.raw
from iotools
provides a third option for quickly reading CSV files.
Trying to store as much data as you can in databases rather than flat files. (As well as being a better permanent storage medium, data is passed to and from R in a binary format, which is faster.) read.csv.sql
in the sqldf
package, as described in JD Long's answer, imports data into a temporary SQLite database and then reads it into R. See also: the RODBC
package, and the reverse depends section of the DBI
package page. MonetDB.R
gives you a data type that pretends to be a data frame but is really a MonetDB underneath, increasing performance. Import data with its monetdb.read.csv
function. dplyr
allows you to work directly with data stored in several types of database.
Storing data in binary formats can also be useful for improving performance. Use saveRDS
/readRDS
(see below), the h5
or rhdf5
packages for HDF5 format, or write_fst
/read_fst
from the fst
package.
The original answer
There are a couple of simple things to try, whether you use read.table or scan.
Set nrows
=the number of records in your data (nmax
in scan
).
Make sure that comment.char=""
to turn off interpretation of comments.
Explicitly define the classes of each column using colClasses
in read.table
.
Setting multi.line=FALSE
may also improve performance in scan.
If none of these thing work, then use one of the profiling packages to determine which lines are slowing things down. Perhaps you can write a cut down version of read.table
based on the results.
The other alternative is filtering your data before you read it into R.
Or, if the problem is that you have to read it in regularly, then use these methods to read the data in once, then save the data frame as a binary blob with save
saveRDS
, then next time you can retrieve it faster with load
readRDS
.
You might need to clarify a bit. What are you really trying to accomplish? If you really want to find out the column names that only contain null values, then you will have to loop through the scheama and do a dynamic query based on that.
I don't know which DBMS you are using, so I'll put some pseudo-code here.
for each col
begin
@cmd = 'if not exists (select * from tablename where ' + col + ' is not null begin print ' + col + ' end'
exec(@cmd)
end
Your .mobile
div has the following styles on it:
.mobile {
display: none !important;
visibility: hidden !important;
}
Therefore you need to override the visibility
property with visible
in addition to overriding the display
property with block
. Like so:
.visible-sm {
display: block !important;
visibility: visible !important;
}
So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:
val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x
But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:
val x: Any = 5
def f[T](v: T) = v match {
case _: Int => "Int"
case _: String => "String"
case _ => "Unknown"
}
f(x)
Here it doesn't matter what is the type of the variable, Any
. What matters, what is checked is the type of 5
, the value. In fact, T
is useless -- you might as well have written it def f(v: Any)
instead. Also, this uses either ClassTag
or a value's Class
, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_]
(List
of something), but not whether it is, for example, a List[Int]
or List[String]
.
Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag
or a TypeTag
. For example:
val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"
A ClassTag
will also let you use type parameters you received on match
. This won't work:
def f[A, B](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
But this will:
val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)
Here I'm using the context bounds syntax, B : ClassTag
, which works just like the implicit parameter in the previous ClassTag
example, but uses an anonymous variable.
One can also get a ClassTag
from a value's Class
, like this:
val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
val B = ClassTag(b.getClass)
ClassTag(a.getClass) match {
case B => "a is the same class as b"
case _ => "a is not the same class as b"
}
}
f(x, y) == f(y, x) // true, a is the same class as b
A ClassTag
is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag
for List[Int]
and List[String]
is the same, List
. If you need type parameters, then you must use a TypeTag
instead. A TypeTag
however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.
Examples with TypeTag
can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:
import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int
Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag
, so I'll stop here.
Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:
val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it
It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.
What about forking the parseInt method?
It's easy, just copy-paste the contents to a new utility that returns Integer
or Optional<Integer>
and replace throws with returns. It seems there are no exceptions in the underlying code, but better check.
By skipping the whole exception handling stuff, you can save some time on invalid inputs. And the method is there since JDK 1.0, so it is not likely you will have to do much to keep it up-to-date.
Safe way without PDO:
$ids = array_filter(array_unique(array_map('intval', (array)$ids)));
if ($ids) {
$query = 'SELECT * FROM `galleries` WHERE `id` IN ('.implode(',', $ids).');';
}
(array)$ids
Cast $ids
variable to arrayarray_map
Transform all array values into integersarray_unique
Remove repeated valuesarray_filter
Remove zero valuesimplode
Join all values to IN selectionIf you are using Oracle 10g, you can use the DECODE
function to pivot the rows into columns:
CREATE TABLE doc_tab (
loan_number VARCHAR2(20),
document_type VARCHAR2(20),
document_id VARCHAR2(20)
);
INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533663', 'Pan card', 'CHXPS5522D');
INSERT INTO doc_tab VALUES('992452533663', 'Drivers licence', 'DL-0420110141769');
COMMIT;
SELECT
loan_number,
MAX(DECODE(document_type, 'Voters ID', document_id)) AS voters_id,
MAX(DECODE(document_type, 'Pan card', document_id)) AS pan_card,
MAX(DECODE(document_type, 'Drivers licence', document_id)) AS drivers_licence
FROM
doc_tab
GROUP BY loan_number
ORDER BY loan_number;
Output:
LOAN_NUMBER VOTERS_ID PAN_CARD DRIVERS_LICENCE ------------- -------------------- -------------------- -------------------- 992452533663 XPD0355636 CHXPS5522D DL-0420110141769
You can achieve the same using Oracle PIVOT
clause, introduced in 11g:
SELECT *
FROM doc_tab
PIVOT (
MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);
SQLFiddle example with both solutions: SQLFiddle example
Read more about pivoting here: Pivot In Oracle by Tim Hall
All the above replies are correct, but might be missing one crucial step, you need to edit the imported key and "ultimately trust" that key
gpg --edit-key (keyIDNumber)
gpg> trust
Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)
1 = I don't know or won't say
2 = I do NOT trust
3 = I trust marginally
4 = I trust fully
5 = I trust ultimately
m = back to the main menu
and select 5 to enable that imported private key as one of your keys
From my understanding, the currently accepted answer only changes the order of the factor levels, not the actual labels (i.e., how the levels of the factor are called). To illustrate the difference between levels and labels, consider the following example:
Turn cyl
into factor (specifying levels would not be necessary as they are coded in alphanumeric order):
mtcars2 <- mtcars %>% mutate(cyl = factor(cyl, levels = c(4, 6, 8)))
mtcars2$cyl[1:5]
#[1] 6 6 4 6 8
#Levels: 4 6 8
Change the order of levels (but not the labels itself: cyl is still the same column)
mtcars3 <- mtcars2 %>% mutate(cyl = factor(cyl, levels = c(8, 6, 4)))
mtcars3$cyl[1:5]
#[1] 6 6 4 6 8
#Levels: 8 6 4
all(mtcars3$cyl==mtcars2$cyl)
#[1] TRUE
Assign new labels to cyl
The order of the labels was: c(8, 6, 4), hence we specify new labels as follows:
mtcars4 <- mtcars3 %>% mutate(cyl = factor(cyl, labels = c("new_value_for_8",
"new_value_for_6",
"new_value_for_4" )))
mtcars4$cyl[1:5]
#[1] new_value_for_6 new_value_for_6 new_value_for_4 new_value_for_6 new_value_for_8
#Levels: new_value_for_8 new_value_for_6 new_value_for_4
Note how this column differs from our first columns:
all(as.character(mtcars4$cyl)!=mtcars3$cyl)
#[1] TRUE
#Note: TRUE here indicates that all values are unequal because I used != instead of ==
#as.character() was required as the levels were numeric and thus not comparable to a character vector
More details:
If we were to change the levels of cyl
using mtcars2
instead of mtcars3
, we would need to specify the labels differently to get the same result. The order of labels for mtcars2
was: c(4, 6, 8), hence we specify new labels as follows
#change labels of mtcars2 (order used to be: c(4, 6, 8)
mtcars5 <- mtcars2 %>% mutate(cyl = factor(cyl, labels = c("new_value_for_4",
"new_value_for_6",
"new_value_for_8" )))
Unlike mtcars3$cyl
and mtcars4$cyl
, the labels of mtcars4$cyl
and mtcars5$cyl
are thus identical, even though their levels have a different order.
mtcars4$cyl[1:5]
#[1] new_value_for_6 new_value_for_6 new_value_for_4 new_value_for_6 new_value_for_8
#Levels: new_value_for_8 new_value_for_6 new_value_for_4
mtcars5$cyl[1:5]
#[1] new_value_for_6 new_value_for_6 new_value_for_4 new_value_for_6 new_value_for_8
#Levels: new_value_for_4 new_value_for_6 new_value_for_8
all(mtcars4$cyl==mtcars5$cyl)
#[1] TRUE
levels(mtcars4$cyl) == levels(mtcars5$cyl)
#1] FALSE TRUE FALSE
If you encounter the problem with missing MS VC 14 Build tools while trying pip install mysqlclient
a possible solution for this may be https://stackoverflow.com/a/51811349/1552410
I have been banging my head against the wall with a similar problem. The only thing that helped is following the steps in this post.
Waqas Raja's answer with some LINQ lambda fun:
List<int> listValues = new List<int>();
Request.Form.AllKeys
.Where(n => n.StartsWith("List"))
.ToList()
.ForEach(x => listValues.Add(int.Parse(Request.Form[x])));
While LIKE
is suitable for this case, a more general purpose solution is to use instr
, which doesn't require characters in the search string to be escaped. Note: instr
is available starting from Sqlite 3.7.15.
SELECT *
FROM TABLE
WHERE instr(column, 'cats') > 0;
Also, keep in mind that LIKE
is case-insensitive, whereas instr
is case-sensitive.
In ES6:
const ID_LENGTH = 36
const START_LETTERS_ASCII = 97 // Use 64 for uppercase
const ALPHABET_LENGTH = 26
const uniqueID = () => [...new Array(ID_LENGTH)]
.map(() => String.fromCharCode(START_LETTERS_ASCII + Math.random() * ALPHABET_LENGTH))
.join('')
Example:
> uniqueID()
> "bxppcnanpuxzpyewttifptbklkurvvetigra"
Check your content-type in the header. I was having issue with this sending raw JSON and my content-type as application/json in the POSTMAN header.
my php was seeing jack all in the request post. It wasn't until i change the content-type to application/x-www-form-urlencoded with the JSON in the RAW textarea and its type as JSON, did my PHP app start to see the post data. not what i expected when deal with raw json but its now working for what i need.
Perform the following steps:
regedit
in the Run window.HKEY_LOCAL_MACHINE\SOFTWARE\ODBC
.Following width worked well in HTML5: -
<table >
<tr>
<th style="min-width:120px">Month</th>
<th style="min-width:60px">Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
Please note that
Adding autocomplete="new-password"
to the password field did the trick. Removed auto filling of both user name and password fields in Chrome.
<input type="password" name="whatever" autocomplete="new-password" />
Mine had to do with forgetting the curly braces around props being sent to a presentational component:
Before:
const TypeAheadInput = (name, options, onChange, value, error) => {
After
const TypeAheadInput = ({name, options, onChange, value, error}) => {
...
$array = array(
1 => 'Awaiting for Confirmation',
2 => 'Asssigned',
3 => 'In Progress',
4 => 'Completed',
5 => 'Mark As Spam',
);
return array_values($array);
...
Correct syntax looks like this. See MSDN.
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS
There is an open-source library that has such a function, and it has cross-platform implementations: https://github.com/OpenHFT/Java-Thread-Affinity
It may be overkill just to get the PID, but if you want other things like CPU and thread id, and specifically thread affinity, it may be adequate for you.
To get the current thread's PID, just call Affinity.getAffinityImpl().getProcessId()
.
This is implemented using JNA (see arcsin's answer).
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
Just FYI, if you want more than single digit numbers you can use sprintf:
char txt[16];
int myNum = 20;
sprintf(txt, "%d", myNum);
Then the first digit is in a char at txt[0], and so on.
(This is the C approach, not the C++ approach. The C++ way would be to use stringstreams.)
Lets seperate your question, you are asking about two different things:
1.
I'm trying to write a validation which alerts the user when he tries to close the browser window.
2.
I want to pop up a message when the user clicks on v1 that "he's about to leave from v1, if he wishes to continue" and same on clicking on v2.
For the first question, do it this way:
window.onbeforeunload = function (event) {
var message = 'Sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
And for the second question, do it this way:
You should handle the $locationChangeStart
event in order to hook up to view transition event, so use this code to handle the transition validation in your controller/s:
function MyCtrl1($scope) {
$scope.$on('$locationChangeStart', function(event) {
var answer = confirm("Are you sure you want to leave this page?")
if (!answer) {
event.preventDefault();
}
});
}
You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.
One way around this is to use JSONP. This allows cross-site requests.
In JSON, you are returned:
{a: 5, b: 6}
In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.
callback({a: 5, b: 6})
You need to edit your REST service to accept a parameter called callback
, and then to use the value of that parameter as the function name. You should also change the content-type
to application/javascript
.
For example: http://localhost:8080/restws/json/product/get?callback=process
should output:
process({a: 5, b: 6})
In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=?
to the URL.
$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
function(data) {
alert(data);
});
If you use $.ajax
, it will auto append the ?callback=?
if you tell it to use jsonp
.
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/restws/json/product/get",
success: function(data){
alert(data);
}
});
Modulo in C# works bad for -1mod7 (should be 6, c# returns -1) so... "oneliner" solution to this will look like this :)
private static DateTime GetFirstDayOfWeek(DateTime date)
{
return date.AddDays(-(((int)date.DayOfWeek - 1) - (int)Math.Floor((double)((int)date.DayOfWeek - 1) / 7) * 7));
}
From main/php.h
of PHP version 7.1.1 and version 5.6.30:
#ifdef PHP_WIN32
# include "tsrm_win32.h"
# include "win95nt.h"
# ifdef PHP_EXPORTS
# define PHPAPI __declspec(dllexport)
# else
# define PHPAPI __declspec(dllimport)
# endif
# define PHP_DIR_SEPARATOR '\\'
# define PHP_EOL "\r\n"
#else
# if defined(__GNUC__) && __GNUC__ >= 4
# define PHPAPI __attribute__ ((visibility("default")))
# else
# define PHPAPI
# endif
# define THREAD_LS
# define PHP_DIR_SEPARATOR '/'
# define PHP_EOL "\n"
#endif
As you can see PHP_EOL
can be "\r\n"
(on Windows servers) or "\n"
(on anything else). On PHP versions prior 5.4.0RC8, there were a third value possible for PHP_EOL
: "\r"
(on MacOSX servers). It was wrong and has been fixed on 2012-03-01 with bug 61193.
As others already told you, you can use PHP_EOL
in any kind of output (where any of these values are valid - like: HTML, XML, logs...) where you want unified newlines. Keep in mind that it's the server that it's determining the value, not the client. Your Windows visitors will get the value from your Unix server which is inconvenient for them sometimes.
I just wanted to show the possibles values of PHP_EOL
backed by the PHP sources since it hasn't been shown here yet...
If you want to ignore '.pyc' files globally (i.e. if you do not want to add the line to .gitignore file in every git directory), try the following:
$ cat ~/.gitconfig
[core]
excludesFile = ~/.gitignore
$ cat ~/.gitignore
**/*.pyc
[Reference]
https://git-scm.com/docs/gitignore
Patterns which a user wants Git to ignore in all situations (e.g., backup or temporary files generated by the user’s editor of choice) generally go into a file specified by core.excludesFile in the user’s ~/.gitconfig.
A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".
If you use FluentNHibernate you can use following configuration code:
private ISessionFactory createSessionFactory()
{
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.UsingFileWithPassword(filename, password))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<DBManager>())
.ExposeConfiguration(this.buildSchema)
.BuildSessionFactory();
}
private void buildSchema(Configuration config)
{
if (filename_not_exists == true)
{
new SchemaExport(config).Create(false, true);
}
}
Method UsingFileWithPassword(filename, password) encrypts a database file and sets password.
It runs only if the new database file is created. The old one not encrypted fails when is opened with this method.
Instead of writing:
Select top 1 ParLngId from T_Param where ParStrNom = 'Extranet Client'
Write:
Select top 1 ParLngId from T_Param where ParStrNom IN 'Extranet Client'
i.e. replace '='
sign by 'IN'
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
1- Stop other applications that are using port 80. 2- run application with port 80 :
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
PHPSESSID is an auto generated session cookie by the server which contains a random long number which is given out by the server itself
If you have more than one version of python installed, run the respective pip command.
For example for python3.6 run the following
pip3.6 install beautifulsoup4
To check the available command/version of pip and python on Mac run
ls /usr/local/bin
You can do it like this (with a slightly modified array to show it works for non-square arrays):
long[,] arr = new long[5, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } };
int rowLength = arr.GetLength(0);
int colLength = arr.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", arr[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.ReadLine();
As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC
, you may end up with something like this:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t
Or, if you prefer to use getConnection(url, "sa", "s3cr3t")
:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
EDIT: Regarding your Connection refused
error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.
SELECT RIGHT('0'
+ CONVERT(VARCHAR(2), Month( column_name )), 2)
FROM table
The issue you're having is with the type of quantifier. You're using a greedy quantifier in your first group (index 1 - index 0 represents the whole Pattern
), which means it'll match as much as it can (and since it's any character, it'll match as many characters as there are in order to fulfill the condition for the next groups).
In short, your 1st group .*
matches anything as long as the next group \\d+
can match something (in this case, the last digit).
As per the 3rd group, it will match anything after the last digit.
If you change it to a reluctant quantifier in your 1st group, you'll get the result I suppose you are expecting, that is, the 3000 part.
Note the question mark in the 1st group.
String line = "This order was placed for QT3000! OK?";
Pattern pattern = Pattern.compile("(.*?)(\\d+)(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println("group 1: " + matcher.group(1));
System.out.println("group 2: " + matcher.group(2));
System.out.println("group 3: " + matcher.group(3));
}
Output:
group 1: This order was placed for QT
group 2: 3000
group 3: ! OK?
More info on Java Pattern
here.
Finally, the capturing groups are delimited by round brackets, and provide a very useful way to use back-references (amongst other things), once your Pattern
is matched to the input.
In Java 6 groups can only be referenced by their order (beware of nested groups and the subtlety of ordering).
In Java 7 it's much easier, as you can use named groups.
Try over-riding CSS using !important
like this
.icon-bar {
background-color:#FF0000 !important;
}
prop_cycle
color_cycle
was deprecated in 1.5 in favor of this generalization: http://matplotlib.org/users/whats_new.html#added-axes-prop-cycle-key-to-rcparams
# cycler is a separate package extracted from matplotlib.
from cycler import cycler
import matplotlib.pyplot as plt
plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b'])))
plt.plot([1, 2])
plt.plot([2, 3])
plt.plot([3, 4])
plt.plot([4, 5])
plt.plot([5, 6])
plt.show()
Also shown in the (now badly named) example: http://matplotlib.org/1.5.1/examples/color/color_cycle_demo.html mentioned at: https://stackoverflow.com/a/4971431/895245
Tested in matplotlib 1.5.1.
From the docs:
You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:
var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.
You can use something like
y[::max(1, len(y)-1)]
if you really want to use slicing. The advantage of this is that it cannot give index errors and works with length 1 or 0 lists as well.
You can very easily create an EXE (for Windows) without using any cryptic build commands. You can do it right in Visual Studio.
I've adjusted the answer of kd7 a little bit because elem.selectionStart will evaluate to false when the selectionStart is incidentally 0.
function setCaretPosition(elem, caretPos) {
var range;
if (elem.createTextRange) {
range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
elem.focus();
if (elem.selectionStart !== undefined) {
elem.setSelectionRange(caretPos, caretPos);
}
}
}
Suposed you saved a new file changes. (navbar.component.html for example)
Run:
ng status
modified: src/app/components/shared/navbar/navbar.component.html
If you want to upload those changes for that file you must run:
git add src/app/components/shared/navbar/navbar.component.html
And then:
git commit src/app/components/shared/navbar/navbar.component.html -m "new navbar changes and fixes"
And then:
git push origin [your branch name, usually "master"]
Or if you want to upload all your changes (several/all files):
git commit -a
And them this will appear "Please enter the commit message for your changes."
And then:
git push
And Viola!
First of all, you can't pass to alert
second argument, use concatenation instead
alert("Input is " + inputValue);
However in order to get values from input better to use states like this
var MyComponent = React.createClass({_x000D_
getInitialState: function () {_x000D_
return { input: '' };_x000D_
},_x000D_
_x000D_
handleChange: function(e) {_x000D_
this.setState({ input: e.target.value });_x000D_
},_x000D_
_x000D_
handleClick: function() {_x000D_
console.log(this.state.input);_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<input type="text" onChange={ this.handleChange } />_x000D_
<input_x000D_
type="button"_x000D_
value="Alert the text input"_x000D_
onClick={this.handleClick}_x000D_
/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
<MyComponent />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
Convert.ToIntXX doesn't like being passed strings of decimals.
To be safe use
Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))
ActionListener gets fired first, with an option to modify the response, before Action gets called and determines the location of the next page.
If you have multiple buttons on the same page which should go to the same place but do slightly different things, you can use the same Action for each button, but use a different ActionListener to handle slightly different functionality.
Here is a link that describes the relationship:
You can use NSValue
for this. An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids.
Example:
CGPoint cgPoint = CGPointMake(10,30);
NSLog(@"%@",[NSValue valueWithCGPoint:cgPoint]);
OUTPUT : NSPoint: {10, 30}
Hope it helps you.
I've recently been struggling with a related issue, discussed at length here: Order of legend entries in ggplot2 barplots with coord_flip() .
As it happens, the reason I had a hard time explaining my issue clearly, involved the relation between (the order of) factors and coord_flip(), as seems to be the case here.
I get the desired result by adding + xlim(rev(levels(x$variable)))
to the ggplot statement:
ggplot(x, aes(x=variable,y=value)) + geom_bar() +
scale_y_continuous("",formatter="percent") + coord_flip()
+ xlim(rev(levels(x$variable)))
This reverses the order of factors as found in the original data frame in the x-axis, which will become the y-axis with coord_flip(). Notice that in this particular example, the variable also happen to be in alphabetical order, but specifying an arbitrary order of levels within xlim()
should work in general.
Unfortunately, vicont's answer did not work for me, so I searched for another solution which is as elegant and works for nested attributes in the ng-model as well. It uses $parse and accesses the ng-model through the attrs in the linking function instead of requiring it:
myApp.directive('myDatepicker', function ($parse) {
return function (scope, element, attrs, controller) {
var ngModel = $parse(attrs.ngModel);
$(function(){
element.datepicker({
...
onSelect:function (dateText, inst) {
scope.$apply(function(scope){
// Change binded variable
ngModel.assign(scope, dateText);
});
}
});
});
}
});
Source: ANGULAR.JS BINDING TO JQUERY UI (DATEPICKER EXAMPLE)
You should be malloc'ing strlen(ptr), not strlen(buf). Also, your count2 should be limited to the number of words. When you get to the end of your string, you continue going over the zeros in your buffer and adding zero size strings to your array.
Assuming a list like below - and assuming some of the options were selected ... (this is a multi select, but this will also work on a single select.
<select multiple='multiple' id='selectListName'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
In some function called based on some event, the following code would clear all selected options.
$("#selectListName").prop('selectedIndex', -1);
DROP TABLE deletes the table.
TRUNCATE TABLE empties it, but leaves its structure for future data.
First a bit of info in epoch from man gmtime
The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When inter-
preted as an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
Time (UTC).
to understand how epoch should be.
>>> time.time()
1347517171.6514659
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)
just ensure the arg you are passing to time.gmtime()
is integer.
Use "&
" instead of "&".
you can simply use onBackPressed();
or if you are using fragment you can use getActivity().onBackPressed()
You can pass the container by reference in order to modify it in the function. What other answers haven’t addressed is that std::vector
does not have a push_front
member function. You can use the insert()
member function on vector
for O(n) insertion:
void do_something(int el, std::vector<int> &arr){
arr.insert(arr.begin(), el);
}
Or use std::deque
instead for amortised O(1) insertion:
void do_something(int el, std::deque<int> &arr){
arr.push_front(el);
}
the plus works just fine, i personally prefer using the concat function.
var s = string.Concat(string 1, string 2, string, 3, etc)
def count_text_file_lines(path):
with open(path, 'rt') as file:
line_count = sum(1 for _line in file)
return line_count
ChronoUnit.YEARS.between(
LocalDate.of( 2010 , 1 , 1 ) ,
LocalDate.now( ZoneId.of( "America/Montreal" ) )
)
The old date-time classes really are bad, so bad that both Sun & Oracle agreed to supplant them with the java.time classes. If you do any significant work at all with date-time values, adding a library to your project is worthwhile. The Joda-Time library was highly successful and recommended, but is now in maintenance mode. The team advises migration to the java.time classes.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
LocalDate start = LocalDate.of( 2010 , 1 , 1 ) ;
LocalDate stop = LocalDate.now( ZoneId.of( "America/Montreal" ) );
long years = java.time.temporal.ChronoUnit.YEARS.between( start , stop );
Dump to console.
System.out.println( "start: " + start + " | stop: " + stop + " | years: " + years ) ;
start: 2010-01-01 | stop: 2016-09-06 | years: 6
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
I compiled a small Bash script for Mac (easily can be ported to Linux) to retrieve all CPU features and apply some of them to build TF. Im on TF master and use kinda often (couple times in a month).
https://gist.github.com/venik/9ba962c8b301b0e21f99884cbd35082f
The height of list view items are adjusted based on its contents. In first image, no content. so height is very minimum. In second image, height is increased based on the size of the text. Because, you specified android:layout_height="wrap_content".
Go to the parent folder, right-click and select Properties. Select the Security tab, edit the permissions and Add. Click on Advanced and the Find Now. Select IIS_IUSRS and click OK and OK again. Make sure you have check Write. Click OK and OK again.
Job done!
You can use MongoDB_DataObject wrapper to perform such query like below:
$model = new MongoDB_DataObject('orders');
$model->whereAdd('MONTH(created) = 4 AND YEAR(created) = 2016');
$model->find();
while ($model->fetch()) {
var_dump($model);
}
OR, similarly, using direct query string:
$model = new MongoDB_DataObject();
$model->query('SELECT * FROM orders WHERE MONTH(created) = 4 AND YEAR(created) = 2016');
while ($model->fetch()) {
var_dump($model);
}
rules: {
cname: {
required: true,
minlength: 2
}
},
messages: {
cname: {
required: "<li>Please enter a name.</li>",
minlength: "<li>Your name is not long enough.</li>"
}
}
Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.
Download zip file and extract it, with in that you will find mysql-connector-XXX.jar
file
If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java
Select the version you want to use and add the dependency in your pom.xml
file
The service :
import 'rxjs/add/operator/map';
import { Http } from '@angular/http';
import { Observable } from "rxjs/Rx"
import { Injectable } from '@angular/core';
@Injectable()
export class ItemService {
private api = "your_api_url";
constructor(private http: Http) {
}
toSaveItem(item) {
return new Promise((resolve, reject) => {
this.http
.post(this.api + '/items', { item: item })
.map(res => res.json())
// This catch is very powerfull, it can catch all errors
.catch((err: Response) => {
// The err.statusText is empty if server down (err.type === 3)
console.log((err.statusText || "Can't join the server."));
// Really usefull. The app can't catch this in "(err)" closure
reject((err.statusText || "Can't join the server."));
// This return is required to compile but unuseable in your app
return Observable.throw(err);
})
// The (err) => {} param on subscribe can't catch server down error so I keep only the catch
.subscribe(data => { resolve(data) })
})
}
}
In the app :
this.itemService.toSaveItem(item).then(
(res) => { console.log('success', res) },
(err) => { console.log('error', err) }
)
For me it got fixed with:
Go to: Window -> Preferences -> C/C++ -> Build -> Environment
Then press "Add..."
Name: MINGW_HOME
Value: C:\MinGW
(yours might be different if you choose a custom path)
Hit "Apply and Close"
Now, it shoud work if you did everything correctly
You can use GroupBy
with anonymous type, and then get First
:
list.GroupBy(e => new {
empLoc = e.empLoc,
empPL = e.empPL,
empShift = e.empShift
})
.Select(g => g.First());
You will love this framework.
And you will love this tool.
For learning about JSON you might like this resource.
And you'll probably love this tutorial.
I think the best way to do this is to use event.preventDefault()
because if some exception is raised in the handler, then the return false
statement will be skipped and the behavior will be opposite to what you want.
But if you are sure that the code won't trigger any exceptions, then you can go with any of the method you wish.
If you still want to go with the return false
, then you can put your entire handler code in a try catch block like below:
$('a').click(function (e) {
try{
your code here.........
}
catch(e){}
return false;
});
With Eloquent it is easy to create multiple where check:
First: (Use simple where)
$users = User::where('name', $request['name'])
->where('surname', $request['surname'])
->where('address', $request['address'])
...
->get();
Second: (Group your where inside an array)
$users = User::where([
['name', $request['name']],
['surname', $request['surname']],
['address', $request['address']],
...
])->get();
You can also use conditional (=, <>, etc.) inside where like this:
$users = User::where('name', '=', $request['name'])
->where('surname', '=', $request['surname'])
->where('address', '<>', $request['address'])
...
->get();
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* @param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
@Override
public void onErrorResponse(VolleyError error) {
}
@Override
public void onResponse(String response) {
//Your response here
}
}
Here is a super simple way to do these kind of conversions. No parsing, or extra libraries required. It is clean, simple, and fast.
import datetime
import time
################################################
#
# Takes the time (in seconds),
# and returns a string of the time in ISO8601 format.
# Note: Timezone is UTC
#
################################################
def TimeToISO8601(seconds):
strKv = datetime.datetime.fromtimestamp(seconds).strftime('%Y-%m-%d')
strKv = strKv + "T"
strKv = strKv + datetime.datetime.fromtimestamp(seconds).strftime('%H:%M:%S')
strKv = strKv +"Z"
return strKv
################################################
#
# Takes a string of the time in ISO8601 format,
# and returns the time (in seconds).
# Note: Timezone is UTC
#
################################################
def ISO8601ToTime(strISOTime):
K1 = 0
K2 = 9999999999
K3 = 0
counter = 0
while counter < 95:
K3 = (K1 + K2) / 2
strK4 = TimeToISO8601(K3)
if strK4 < strISOTime:
K1 = K3
if strK4 > strISOTime:
K2 = K3
counter = counter + 1
return K3
################################################
#
# Takes a string of the time in ISO8601 (UTC) format,
# and returns a python DateTime object.
# Note: returned value is your local time zone.
#
################################################
def ISO8601ToDateTime(strISOTime):
return time.gmtime(ISO8601ToTime(strISOTime))
#To test:
Test = "2014-09-27T12:05:06.9876"
print ("The test value is: " + Test)
Ans = ISO8601ToTime(Test)
print ("The answer in seconds is: " + str(Ans))
print ("And a Python datetime object is: " + str(ISO8601ToDateTime(Test)))