_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d4001 | train | You can do it as follows:
Simply take the top-level view where all of the sub-views have been composited, and then:
+ (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
{
//This only works on iOS7
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
}
else
{
//For iOS before version 7, use the following instead
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
}
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
} | unknown | |
d4002 | train | Your code doesn't set the device context's text foreground color for DrawText(), although the default is black. See SetTextColor().
SetBkMode(..., TRANSPARENT) just sets the background color/mode for the DrawText() rect, not the entire window.
A: You are asking about how to draw the window so it is transparent, but the problem isn't with the drawing at all.
The answer is essentially that everything you have done so far towards making a transparent window is wrong. It looks like the window is transparent, but in fact it is not, as you can see from the behaviour you describe when you move and resize the window. That's the classic symptom.
In other words, you haven't made the window transparent, you have just stopped drawing the background. What you see as the background is just whatever happened to be underneath the window when it was first drawn.
You need make a Layered window. To find out how to make transparent windows, go here:
*
*http://msdn.microsoft.com/en-us/library/ms997507.aspx
A: Do you want Text/Check/Label be transparent on parent form?
You can Add WS_CLIPSIBLINGS and WS_EX_TRANSPARENT..
Use SetBkMode(hDC, TRANSPARENT) When WM_PAINT message | unknown | |
d4003 | train | Generally I think it's best to keep children elements within the bounds of their parents because of how tricky this can get. However if you need to use this layout you can try something like:
margin-left: calc((-1 * 960px * .25) - (50vw - (.5 * 960px)));
I'm sure that can be shortened, but I wanted to leave the full calculation in place for clarity's sake. The first part, -1 * 960px *.25 moves the magenta box to align its left edge with the grid's left edge. The second part 50vw - (.5 * 960px) then moves the magenta box further so that its left edge aligns with the browser's left edge.
The problem with this is it's somewhat brittle. It depends very heavily on the exact width of both the 'grid' element and the percent width of the left column.
CSS Tricks has a good post about centering items that are wider than their parents. It's solutions don't directly apply to this case, but it's a good resource to better understand your options and I used it to develop the calc statement I used | unknown | |
d4004 | train | There is no easy way to do this. Typically, you need to map an open-generic abstraction to an open-generic implementation, like this:
services.AddTransient(typeof(IEventConsumer<>), typeof(CustomerEvent<>));
This, however, will not work in your case because MS.DI is unable to figure out how the generic type argument for IEventCustomer<T> should maps to the generic type argument of CustomerEvent<TEntity>. When resolving an IEventCustomer<EntityInsertedEvent<Order>>, for instance, it will try to create a CustomerEvent<EntityInsertedEvent<Order>>, while it should have been creating a CustomerEvent<Order>.
This is not a limitation of .NET or the CLR, but a limitation that is specific to the MS.DI DI Container, because some other DI Containers are actually able to make these kinds of mappings.
Unfortunately, with MS.DI, there is no easy way out. The only thing you can do is making all possible closed-generic registrations explicitly, e.g.:
s.AddTransient<IEventConsumer<EntityInsertedEvent<Order>>, CustomerEvent<Order>>();
s.AddTransient<IEventConsumer<EntityInsertedEvent<Customer>>, CustomerEvent<Customer>>();
s.AddTransient<IEventConsumer<EntityInsertedEvent<Product>>, CustomerEvent<Product>>();
s.AddTransient<IEventConsumer<EntityInsertedEvent<Employee>>, CustomerEvent<Employee>>();
s.AddTransient<IEventConsumer<EntityInsertedEvent<etc>>, CustomerEvent<etc>>(); | unknown | |
d4005 | train | your binding isn't well written. instead of writing views:CarView.Status="{Binding Status}" you should write only Status="{Binding Status}"
A: It seems that your Control is binding to itself.
Status is looked for in CarView.
You should have a line of code in your control CodeBehind like :
this.DataContext = new ViewModelObjectWithStatusPropertyToBindFrom();
Regards | unknown | |
d4006 | train | Double quotes "" works
spring:
application:
name: app
profiles:
active: DEV
config:
import: "configserver:" | unknown | |
d4007 | train | In your view model, you'll want to hook into your router by creating a computed that listens to the value of the current instruction:
var ko = require('knockout');
var router = require('plugins/router');
function viewModel() {
this.currentRoute = ko.computed(function() {
return router.activeInstruction().fragment;
});
}
Then you can reference this variable using the visible binding in your view.
<!-- home route only -->
<div data-bind="visible: currentRoute() == 'home'></div>
<!-- non-home routes -->
<div data-bind="visible: currentRoute() != 'home'></div>
If you need more complicated logic, you can create a special computed function that does specific testing against the current route and reference that variable instead. For example:
this.isSpecialRoute = ko.computed(function() {
var re = /matchspecialroute/;
return re.test(this.currentRoute());
}, this); | unknown | |
d4008 | train | It seems like you have to use dd start wrt ..got, i.e. reference the global offset table instead of the procedure linkage table. The latter would only work with something like call start wrt ..plt, i.e. an real instruction. In this case you are using dd, i.e. storing an immediate value in the output. | unknown | |
d4009 | train | First off, to run nginx in debug you need to run the nginx-debug binary, not the normal nginx, as described in the nginx docs. If you don't do that, it won't mater if you set the error_log to debug, as it won't work.
If you want to find out WHY it is a 2 step process, I can't tell you why exactly the decision was made to do so.
Debug spits out a lot of logs, fd info and so much more, so yes it can slow down your system for example as it has to write all that logs. On a dev server, that is fine, on a production server with hundreds or thousands of requests, you can see how the disk I/O generated by that log can cause the server to slow down and other services to get stuck waiting on some free disk I/O. Also, disk space can run out quickly too.
Also, what would be the reason to run always in debug mode ? Is there anything special you are looking for in those logs ? I guess i'm trying to figure out why would you want it.
And it's maybe worth mentioning that if you do want to run debug in production, at least use the debug_connection directive and log only certain IPs. | unknown | |
d4010 | train | Your question is a bit unclear, however if you are asking about user access controls, whereby you can give certain users certain permissions, TwinCAT does have a built-in user management system. However, it relies on Beckhoff's HMI software products (Either HMI or HMI Web).
If you are using a different HMI solution, you would need to implement this functionality yourself. | unknown | |
d4011 | train | Found it. Data Studio doesn't like spaces in column aliases, yet it won't show any error for them. The working is the same with all spaces in aliases replaced by underscore | unknown | |
d4012 | train | This is a perfectly reasonable model. True, you can take the approach of creating a join table for a 1:1 relationship (or, somewhat better, you could put user_id in the profile_picture table), but unless you think that very few users will have profile pictures then that's likely a needless complication.
Readability is an important component in relational design. Do you consider the profile picture to be an attribute of the user, or the user to be an attribute of the profile picture? You start from what makes logical sense, then optimize away the intuitive design as you find it necessary through performance testing. Don't prematurely optimize.
A: "NULL is bad" is a rather poor excuse for a reason to do (or not do) something.
That said, you may want to model this as a dependent table, where the user_id is both the primary key and a foreign key to the existing table.
Something like this:
Users UserPicture Picture
---------------- -------------------- -------------------
| User_Id (PK) |__________| User_Id (PK, FK) |__________| Picture_Id (PK) |
| ... | | Picture_Id (FK) | | ... |
---------------- -------------------- -------------------
Or, if pictures are dependent objects (don't have a meaningful lifetime independent of users) merge the UserPicture and Picture tables, with User_Id as the PK and discard the Picture_Id.
Actually, looking at it again, this really doesn't gain you anything - you have to do a left join vs. having a null column, so the other scenario (put the User_Id in the Picture table) or just leave the Picture_Id right in the Users table both make just as much sense.
A: NULL isn't "bad". It means "I don't know." It's not wrong for you or your schema to admit it.
A: Your user table should not have a nullable field called profile_picture_id. It would be better to have a user_id column in the profile_picture table. It should of course be a foreign key to the user table.
A: Since when is a nullable foreign key relationship "bad?" Honestly introducing another table here seems kind of silly since there's no possibility to have more than one profile picture. Your current schema is more than acceptable. The "null is bad" argument doesn't hold any water in my book.
If you're looking for a slightly better schema, then you could do something like drop the "profile_picture_id" column from the users table, and then make a "user_id" column in the pictures table with a foreign key relationship back to users. Then you could even enforce a UNIQUE constraint on the user_id foreign key column so that you can't have more than one instance of a user_id in that table.
EDIT: It's also worth noting that this alternate schema could be a little bit more future-proof should you decide to allow users to have more than one profile picture in the future. You can simply drop the UNIQUE constraint on the foreign key and you're done.
A: It is true that having many columns with null values is not recommended. I would suggest you make the picture table a weak entity of user table and have an identifying relationship between the two. Picture table entries would depend on user id.
A: Make the profile picture a nullable field on the user table and be done with it. Sometimes people normalize just for normalization sake. Null is perfectly fine, and in DB2, NULL is a first class citizen of values with NULL being included in indices.
A: I agree that NULL is bad. It is not relational-database-style.
Null is avoided by introducing an extra table named UserPictureIds. It would have two columns, UserId and PictureId. If there's none, it simply would not have the respective line, while user is still there in Users table.
Edit due to peer pressure
This answer focuses not on why NULL is bad - but, on how to avoid using NULLs in your database design.
For evaluating (NULL==NULL)==(NULL!=NULL), please refer to comments and google. | unknown | |
d4013 | train | Unfortunately, the port for ACI to exposed to the Internet should be a unique one, it means the port only can appear one time. And I know that you want the port 53 allowing both TCP and UDP protocol, but it does not support in ACI currently.
If you do not mind, the VM can help you achieve your purpose. | unknown | |
d4014 | train | The relevant errors here are:
Unable to look up TXT record for host discord-y3bzo.mongodb.net
DNS error
java.net.SocketTimeoutException: Receive timed out
This suggests that you are using a mongodb+srv style connection string, and the DnsClient library is timing out trying to query the DNS server for the TXT record in needs in order to connect.
That is to say, this looks a lot like an issue with DNS resolver confguration, the DNS server, or the network connection to the DNS server. | unknown | |
d4015 | train | Moya returns MoyaError enum in error block which you can handle by extracting the error type using switch on MoyaError and then using statusCode to convert to NetworkError enum
func logInRequest(tokenType: accessTokenTypeEnum, token: String, secondKey: String, client: String) -> Observable<LoginModel> {
return sharedProvider.rx
.request(WebServiceAPIs.getAccessToken(tokenType: tokenType.rawValue, token: token, secondKey: secondKey, client: client))
.filterSuccessfulStatusCodes()
.catchError({ [weak self] error -> Observable<NetworkError> in
guard let strongSelf = self else { return Observable.empty() }
if let moyaError = error as? MoyaError {
let networkError = self?.createNetworkError(from: moyaError)
return Observable.error(networkError)
} else {
return Observable.error(NetworkError.somethingWentWrong(error.localizedDescription))
}
})
.map(LoginModel.self, atKeyPath: nil, using: JSONDecoder(), failsOnEmptyData: true).asObservable()
}
func createNetworkError(from moyaError: MoyaError) -> NetowrkError {
switch moyaError {
case .statusCode(let response):
return NetworkError.mapError(statusCode: response.statusCode)
case .underlying(let error, let response):
if let response = response {
return NetworkError.mapError(statusCode: response.statusCode)
} else {
if let nsError = error as? NSError {
return NetworkError.mapError(statusCode: nsError.code)
} else {
return NetworkError.notConnectedToInternet
}
}
default:
return NetworkError.somethingWentWrong("Something went wrong. Please try again.")
}
}
You can create your custom NetworkError enum like below which will map statusCode to custom NetworkError enum value. It will have errorDescription var which will return custom description to show in error view
enum NetworkError: Swift.Error {
case unauthorized
case serviceNotAvailable
case notConnectedToInternet
case somethingWentWrong(String)
static func mapError(statusCode: Int) -> NetworkError {
switch statusCode {
case 401:
return .unauthorized
case 501:
return .serviceNotAvailable
case -1009:
return .notConnectedToInternet
default:
return .somethingWentWrong("Something went wrong. Please try again.")
}
}
var errorDescription: String {
switch self {
case .unauthorized:
return "Unauthorised response from the server"
case .notConnectedToInternet:
return "Not connected to Internet"
case .serviceNotAvailable:
return "Service is not available. Try later"
case .somethingWentWrong(let errorMessage):
return errorMessage
}
}
}
A: In my experience, '.materialize()' operator is the perfect solution for handling HTTP errors.
Instead of separate events for success and error you get one single wrapper event with either success or error nested in it. | unknown | |
d4016 | train | The WHERE clause of your query contains a comparison of a literal numeric value with a string (column id).
When it needs to compare values of different type, MySQL uses several rules to convert one or both of the values to a common type.
Some of the type conversion rules are not intuitive. The last rule is the only one that matches a comparison of an integer number with a string:
In all other cases, the arguments are compared as floating-point (real) numbers.
When they are converted to floating-point (real) numbers, 1 (integer), '1', '0001' and '0000001' are all equal.
In order to get an exact match the literal value you put in the query must have the same type as the column id (i.e string). The query should be:
SELECT * FROM products WHERE id = '1'
A: Numbers in MySQL (and the real world) don't have leading zeros. Strings do.
So, you just need to make the comparison using the right type:
SELECT *
FROM products
WHERE id = '1';
What happens with your original query is that the id is converted to a number. And '1', '001' and '0000001' are all converted to the same integer -- 1. Hence, all three pass the filter.
A: The problem is that you are looking by a varchar type using an integer cast.
Try to add quotes to the id parameter:
SELECT * FROM products WHERE id = '1';
If you want to add integer ids with with leading zeros, I recommend you to use the zerofill option:
https://dev.mysql.com/doc/refman/5.5/en/numeric-type-attributes.html
If you want to use use alphanumeric values then keeps the ID type as varchar, but remember to enclose the search param into quotes. | unknown | |
d4017 | train | Following is an option:
Upload a file temporarily to your server. Once uploaded to localhost, use curl to upload the file to remote server.
For password protection you can use an access token which expires every 1 hour or so. Pass access_token as a variable with your upload request. Remote server verifies that access_token exists and has not expired before accepting the upload.
Set a username and password for the access. If access token does not exist or has expired use curl to post username and password to remote server, which will verify if username and password are valid and returns new access_token.
A: Try in via ftp
http://php.net/manual/de/book.ftp.php
A: I think I have ever experience this problem. If I am not wrong to understand your issue, my issue is like this. I create upload.php in server A and receive in server A too, let's say the file is receive.php (it works normally). Then I upload the receive file (receive.php) to server B, and modify the upload.php in server A (which is the upload.php destination's is server B).
Is it the issue? If the issue like this, it might be firewall issue. But the server that I use both of them is centos. What I do then is, I switch off selinux, and use firehol to adjust the firewall in my centos. Then it's work fine.
Other option, you can still receive file in your server A. Then in your receive you transfer the file via ftp to server B, but I think this need more effort to do. Cause you need to adjust the ftp configuration (is it ftp, sftp, or sftp using pem / pkk). | unknown | |
d4018 | train | Yes you have to implement your own way of showing buttons on UITableViewCells by customizing the UITableViewCells.
As far as your requirement is concerned, I dont think its a good idea to show the "edit" button below the "delete" button, as accommodating both buttons vertically one-by-one may disappoint the user to make desired touch actions.
I mean to say, user may want to touch edit, but due to successive placing of custom edit/delete buttons, delete button may get clicked which is dangerous & not acceptable too. Of course,it will cause user to take proper care every-time making any of the edits. | unknown | |
d4019 | train | If I understood your goal correctly, you need a method that expects two string arguments.
And depending on the number of occurrences of the second string in the first string the method will return either the first string intact (if the target value is unique or not present in the first string), or will generate a new string by removing the first occurrence of the target value (the second string).
This problem can be addressed in the following steps:
*
*Create a list by splitting the given string.
*Count the number of occurrences of the target value.
*If the count is <= 1 (i.e. value is unique, or not present at all) return the same string.
*Otherwise remove the target value from the list.
*Combine list elements into a string.
It might be implemented like this:
public static String removeFirstIfDuplicate(String source, String target) {
List<String> sourceList = new ArrayList<>(Arrays.asList(source.split("[\\p{Punct}\\p{Space}]+")));
long targetCount = sourceList.stream()
.filter(str -> str.equals(target))
.count();
if (targetCount <= 1) {
return source;
}
sourceList.remove(target);
return sourceList.stream().collect(Collectors.joining(", "));
}
main()
public static void main(String[] args) {
System.out.println(removeFirstIfDuplicate("A, A, C", "A"));
System.out.println(removeFirstIfDuplicate("A, A, C", "C"));
}
Output
A, C
A, A, C | unknown | |
d4020 | train | Per the VFP documentation, the ActiveRow Property "Specifies the row that contains the active cell in a Grid control. Not available at design time; read-only at run time".
I would do something like this.
IF EOF("TableAlias) = .F.
SKIP 1 IN "TableAlias"
ENDIF | unknown | |
d4021 | train | In your routes file, you can specify the mapping this way:
mount CustomerApp, :at => '/customer'
Now, inside your sinatra application, you can specify your routes without the /customer part.
Dont't forget to require your sinatra application somewhere (you can do it directly in the route file)
A: You need to add an additional route to match the different URL:
match '/customer/(:string)/edit' => CustomerApp | unknown | |
d4022 | train | PrimeFaces supports lazyloading for the datatable. The feature that you can do lazy loading (no need to fully load all data upfront), is actually provided by actually giving you full control of any aspect of sorting, paging and filtering.
Normally you would filter, sort and then page, but that could be done in any order.
So it is very simple to just sort after you e.g. loaded the data for the right page with the right filter instead of doing the sorting before the paging.
That way you achieve the behaviour you want. | unknown | |
d4023 | train | RegEx is a poor choice for dates. You could look for : and examine the remaining tokens:
Sub Foo()
Dim result() As Variant
result = GetDates("Previous Month: 9/1/2015 - 9/30/2015")
If UBound(result) Then
Debug.Print result(0)
Debug.Print result(1)
End If
End Sub
Function GetDates(str As String) As Variant()
Dim tokens() As String
tokens = Split(Mid$(str, InStr(str & ": ", ":")), " ")
If (UBound(tokens) = 3) Then
If IsDate(tokens(1)) And IsDate(tokens(3)) Then
GetDates = Array(CDate(tokens(1)), CDate(tokens(3)))
Exit Function
End If
End If
ReDim GetDates(0)
End Function
A: Try this:
([1-9]|1[012])[/]([1-9]|[1-2][0-9]|3[01])[/](19|20)[0-9]{2}
A: search a commandtext string for dates and then replace them with a new date
dim regex as object
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "\d{1,2}[-/]\d{1,2}[-/]\d{2,4}"
regex.Global = True
Set regexMatches = regex.Execute(CommandText)
for i=0 to regexMatches.Count()
date1 = regexMatches(i)
next | unknown | |
d4024 | train | For any argument except an empty list, the second case always fires:
rem1 ys _ = ys
It says "whatever the arguments are, always return the first argument". So it does.
You were probably thinking about the second case "in comparison" with the third case: the third case matches on (:), and the second case matches "when there is no (:)".
But that's not how pattern matching works. A pattern like ys matches anything, anything at all, regardless of whether it's the (:) constructor or not. So your second case matches any parameter.
To fix, just remove the second case. You don't need it. | unknown | |
d4025 | train | You need to assign the binding you defined to an endpoint you create. Here's an example:
<bindings>
<basicHttpBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
transferMode="Buffered"
messageEncoding="Text"
textEncoding="utf-8"
bypassProxyOnLocal="false"
useDefaultWebProxy="true" >
<security mode="None" />
<readerQuotas maxDepth="2147483647"
maxArrayLength="2147483647"
maxStringContentLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service>
<endpoint address="/Service.svc" binding="basicHttpBinding"
bindingCongifuration="basicHttp"
contract="service.IService"/>
</service>
</services>
A couple of things to note - in your comment, your service endpoint was using wsHttpBinding, but you defined basicHttpBinding in your <bindings> section. Also, the bindingConfiguration attribute must be the name assigned to the binding defined. My example above is based on the original posted config file.
Alternatively, if you are using .NET 4.0 or later, you can define a binding in the <bindings> setting and set it as the default definition for that binding by omitting the name attribute on the <binding> element.
By default, .NET 4.0+ uses basicHttpBinding for http. You can change this in the config file in the <protocolMapping> section (which is contained in the <system.serviceModel> section). For example, if you wanted to use wsHttpBinding for all http requests, you would do this:
<protocolMapping>
<add binding="wsHttpBinding" scheme="http" />
</protocolMapping>
Added Client Example
The client side would look very similar, except you'd have a <clients> section instead of a <services> section. Note that some of the settings on the binding apply to the machine (client or server) the application is on, and setting them on one side of the client-server relationship will have no effect on the other side (like maxReceivedMessageSize, for example). Generally the binding type and security have to agree, and in practice it's usually easier to just use the same bindings on both ends, but it is possible to have a scenario where one side would have different buffers or other items.
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" allowCookies="true"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
transferMode="Buffered"
messageEncoding="Text"
textEncoding="utf-8"
bypassProxyOnLocal="false"
useDefaultWebProxy="true" >
<security mode="None" />
<readerQuotas maxDepth="2147483647"
maxArrayLength="2147483647"
maxStringContentLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="localhost:3724/Service.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService"
contract="ServiceReference1.IService"
name="BasicHttpBinding_IService" />
</client> | unknown | |
d4026 | train | I'm not sure it's a bug.
I guess when you register your interpreter, you uncheck the checkbox : "Accept file as argument"
This mean LDT will not manage the file to launch (that's why the Launch script is disabled)
The standard lua interpreter support file as argument and -e option, so the two check box should be checked. (It's the default value)
A: It looks like a bug ... Would you mind filing it in the Koneki bug tracker? | unknown | |
d4027 | train | The problem is that you are locking out yourself.
With
Thread.sleep(x * 2);
you are blocking the EventDispatchThread that would run your ActionListener. Still the timer internally keeps a flag that the timeout occured and that it should run your ActionListener at the next possible time.
But
TIMER.stop();
is resetting the TIMER, so that the notification is lost. | unknown | |
d4028 | train | You were close with your first attempt--it looks like you forgot to URI encode the = sign as %3D. Try this instead:
&fq=(prefix+field%3Dclaimedgalleryid+'')
I highly recommend using the "test search" feature to work out the kinks in your query syntax. You can see the results right there, and then use the "View Raw: JSON" link to copy the full request URL and see how characters get escaped and such. | unknown | |
d4029 | train | Use this
Dim xmlDoc As XDocument = <?xml version="1.0" encoding="utf-16"?>
<!-- This is comment by you -->
<Employees>
<Employee id="EMP001">
<name>Wriju</name>
<![CDATA[ ~~~~~~~...~~~~~~~~]]>
</Employee>
</Employees>
'it assume that /youfolder is in the root and it has read and write permission
xmlDoc.Save(Server.MapPath("/yourfolder/somefile.xml")) | unknown | |
d4030 | train | You define the clock period in ns and the synt/PR-tools tries to place the logic so this time constraint is fulfilled. If it fails you will get a timing error.
If it is not finished within 1 clk the result is undefined. | unknown | |
d4031 | train | Don't use not in with a subquery. It doesn't work the way you expect with NULL values. If any value returned by the subquery is NULL, then no rows are returned at all.
Instead, use not exists. This has the semantics that you expect:
select wpb.[ID number]
from [Fact].[REPORT].[WPB_LIST_OF_IDS] wpb
where not exists (select 1
from MasterData.Dimension.Customer dc
where wpb.[ID number] = dc.IdNumber
);
Of course, the left join method also works. | unknown | |
d4032 | train | Try disabling csrf token in your configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**")
.permitAll()
.antMatchers("/js/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout()
.permitAll()
.and().csrf().disable();
}
A: fortunately you add "modal" inside thymeleaf each loop, so edit your html from according my code ....
<form id="deleteForm" th:action="${'/products/delete/' + theProductId}" th:method="DELETE">
<button type="submit" class="btn btn-danger">Delete Employee</button>
</form>
this is tested code ...working fine ..
you just miss "th:action" for that it dose not work as thymeleaf form. so thymeleaf dose not provide hidden "_csrf" field; | unknown | |
d4033 | train | I think what you really need is ManyToMany relationship.
Because in your case, one Tournament can have many Member(s), and Member can follow many Tournament(s).
If you use OneToMany, the JPA provider will check if the Member already has Tournament assigned, and will fail to add if it true | unknown | |
d4034 | train | what is the problem here?
The problem is that you don't terminate your strings.
C requires strings to be null terminated:
The length of a C string is found by searching for the (first) NUL byte. This can be slow as it takes O(n) (linear time) with respect to the string length. It also means that a string cannot contain a NUL character (there is a NUL in memory, but it is after the last character, not "in" the string).
#include <stdio.h>
#include<string.h>
int main() {
char a[50],b[50];// same sized arrays
for(int j =0;j<50;j++){
b[j]='b';a[j]='a';// initializing with the same number of elements
}
// Terminate strings
a[49] = b[49] = 0;
printf("the size of a is %ld,",strlen(a));
printf("the size of B is %ld",strlen(b));
return 0;
}
Gives the correct result. | unknown | |
d4035 | train | If you are not the original developer (logged in with the same account) XAP installation through SD Card or download will still require you buy the application. If you have already bought it in the past it will not ask again as it will verify that with the Windows Phone Store.
Is that your question?
If you are asking how to check from one app if another one has been bought the best option is to check the list of installed apps:
InstallationManager.FindPackagesForCurrentPublisher method
To check if license is still active you can check in the code:
bool hasBeenBought = Windows.ApplicationModel.Store.CurrentApp.LicenseInformation.IsActive; | unknown | |
d4036 | train | A circle, is the geometric position of all the points whose distance from a central point is equal to some number "R".
You want to find the points whose distance is less than or equal to that "R", our radius.
The distance equation in 2d euclidean space is d(p1,p2) = root((p1.x-p2.x)^2 + (p1.y-p2.y)^2).
Check if the distance between your p and the center of the circle is less than the radius.
Let's say I have a circle with radius r and center at position (x0,y0) and a point (x1,y1) and I want to check if that point is in the circle or not.
I'd need to check if d((x0,y0),(x1,y1)) < r which translates to:
Math.sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)) < r
In JavaScript.
Now you know all these values (x0,y0) being bubble.x and bubble.y and (x1,y1) being x and y.
A: Just calculate the distance between the mouse pointer and the center of your circle, then decide whether it's inside:
var dx = x - bubble.x,
dy = y - bubble.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < bubble.r) {
alert('hello');
}
Demo
As mentioned in the comments, to eliminate Math.sqrt() you can use:
var distsq = dx * dx + dy * dy,
rsq = bubble.r * bubble.r;
if (distsq < rsq) {
alert('HELLO');
}
A: To test if a point is within a circle, you want to determine if the distance between the given point and the center of the circle is smaller than the radius of the circle.
Instead of using the point-distance formula, which involves the use of a (slow) square root, you can compare the non-square-rooted (or still-squared) distance between the points. If that distance is less than the radius squared, then you're in!
// x,y is the point to test
// cx, cy is circle center, and radius is circle radius
function pointInCircle(x, y, cx, cy, radius) {
var distancesquared = (x - cx) * (x - cx) + (y - cy) * (y - cy);
return distancesquared <= radius * radius;
}
(Not using your code because I want to keep the function general for onlookers who come to this question later)
This is slightly more complicated to comprehend, but its also faster, and if you intend on ever checking point-in-circle in a drawing/animation/object moving loop, then you'll want to do it the fastest way possible.
Related JS perf test:
http://jsperf.com/no-square-root
A: An alternative (not always useful meaning it will only work for the last path (re)defined, but I bring it up as an option):
x = e.pageX - canvas.getBoundingClientRect().left
y = e.pageY - canvas.getBoundingClientRect().top
if (ctx.isPointInPath(x, y)) {
alert("HELLO!")
}
Path can btw. be any shape.
For more details:
http://www.w3.org/TR/2dcontext/#dom-context-2d-ispointinpath | unknown | |
d4037 | train | enumerate() returns a generator object; you only printed the representation of the object, then discard it again. The second line then reused the same memory location for a now object.
You can just refer directly to the temp_buffer object without enumerate() here:
for i, word in enumerate(temp_buffer):
print(temp_buffer[i])
print(temp_buffer[-1])
but temp_buffer[i] is the same thing as word in that loop. temp_buffer[-1] is the last word in your list.
If you wanted to know how many more words there are to process, use len(temp_buffer) - i, the length of the temp_buffer list, subtracting the current position.
A: You should count the number of items beforehand:
words = len(temp_buffer)
in your code this would look like
import codecs
with codecs.open("C:\\dna_chain.txt",'r', "utf-8") as file:
for line in file:
temp_buffer = line.split()
words = len(temp_buffer)
for i,word in enumerate(temp_buffer):
print(i, word, words-i-1)
this will print the index i, the word word and the number of remaining items in this row words-i-1. | unknown | |
d4038 | train | You can always use classMap or styleMap directives for the dynamic styling in the Lit Component. More information available at Dynamic classes and styles.
import { html, css, LitElement } from 'lit-element';
import { classMap } from 'lit/directives/class-map.js';
class SinDrawer extends LitElement {
static get styles() {
return css`
nav {
display: flex;
padding: 8px;
background-color: var(--main-color);
}
`;
}
static get properties() {
return {
_show: { state: true },
};
}
constructor() {
super();
this._show = false;
}
show() {
this._show = !this._show;
}
render() {
return html`
<nav>
<div class="nav-brand">
<a href="#/home">
<img src="./icons/icon_512.png" alt="sr-brand" height="50" title="Sinfor-Resto" />
</a>
</div>
<div class="nav-link ${classMap({ show: this._show })}">
<a href="#/home" class="nav-anchor">Beranda</a>
<a href="#/favorite" class="nav-anchor">Favorite</a>
<a href="#/about" class="nav-anchor">Tentang</a>
</div>
<button id="hamb-btn" @click=${this.show}>☰</button>
</nav>
`;
}
}
customElements.define('sin-drawer', SinDrawer);
A: This can be done in 3 simple steps.
*
*Add a property ‘newClass’ as follows and initialise this.newClass as “” in constructor.
static get properties(){
return{
newClass: String
}
}
*Add ‘newClass’ to the div as follows
<div class="nav-link ${this.newClass}">
*On click of the button, this.newClass will contain the new class name.
<button id="hamb-btn" @click=${e=>this.newClass =”newClassName”}>☰</button>
Since this.newClass is added to properties of the element, it will rerender the DOM and update the div with class=”nav-link newClassName” | unknown | |
d4039 | train | In my opinion the way you want to avoid is very appropriate. There must be a piece of such code somewhere.
If you can't put that method in the target class just put it somewhere else (some factory). You should additionaly make your method static.
Take a look at Factory method pattern.
2nd option would be extending B and place this method as factory static method in that new class. But this solution seems to be more complicated for me. Then you could call NewB.fromA(A). You should be able then use your NewB instead of B then.
A: The good practice is to have a factory class which "produces" the instances of B.
public class BFactory {
public B createBFromA(A a) { ... }
}
You have to write the code of the factory method as there is no standard way of creating a child class based on its parent class. It's always specific and depends on the logic of your classes.
However, consider if it is really what you need. There are not many smart use cases for instantiating a class based on the instance of its parent. One good example is ArrayList(Collection c) - constructs a specific list ("child") containing the elements of the generic collection ("base").
Actually, for many situation there is a pattern to avoid such strange constructs. I am aware it's probably not applicable to your specific case as you wrote that your Base and Child are 3rd party classes. However your question title was generic enough so I think you may find the following useful.
*
*Create an interface IBase
*Let the class Base implement the interface
*Use composition instead of inheritance - let Child use Base instead of inheriting it
*Let Child implement IBase and delegate all the methods from IBase to the instance of Base
Your code will look like this:
public interface IBase {
String getName();
int getAge();
}
public class Base implements IBase {
private String name;
private int age;
// getters implementing IBase
}
public class Child implements IBase {
// composition:
final private IBase base;
public Child(IBase base) {
this.base = base;
}
// delegation:
public String getName() {
return base.getName();
}
public int getAge() {
return base.getAge();
}
}
After you edited your question, I doubt even stronger that what you want is good. Your question looks more like an attempt of a hack, of violating (or not understanding) the principles of class-based object oriented concept. Sounds to me like someone coming from the JavaScript word and trying to keep the JavaScript programming style and just use a different syntax of Java, instead of adopting a different language philosophy.
Fun-fact: Instantiating a child object with parent object is possible in prototype-based languages, see the example in JavaScript 1.8.5:
var base = {one: 1, two: 2};
var child = Object.create(base);
child.three = 3;
child.one; // 1
child.two; // 2
child.three; // 3
A: You could do it via reflection:
public static void copyFields(Object source, Object target) {
Field[] fieldsSource = source.getClass().getFields();
Field[] fieldsTarget = target.getClass().getFields();
for (Field fieldTarget : fieldsTarget)
{
for (Field fieldSource : fieldsSource)
{
if (fieldTarget.getName().equals(fieldSource.getName()))
{
try
{
fieldTarget.set(target, fieldSource.get(source));
}
catch (SecurityException e)
{
}
catch (IllegalArgumentException e)
{
}
catch (IllegalAccessException e)
{
}
break;
}
}
}
}
*Above code copied from online tutorial | unknown | |
d4040 | train | You can do it this way:
SELECT T1.ColA, T2.ColB, T1.Rank
FROM TableName T2 JOIN
(SELECT ColA,MAX(Rank) as Rank
FROM TableName
GROUP BY ColA) T1 ON T1.ColA=T2.ColA AND T1.Rank=T2.Rank
Explanation:
*
*Inner query (T1) selects records with highest rank for each values of ColA.
*Outer query (T2) is used to select ColB with respect to the values of ColA and Rank from T2.
Result:
ColA ColB Rank
--------------------
1 3 1
2 1 0
3 2 1
See result in SQL Fiddle | unknown | |
d4041 | train | If they are not properties then you will have to implement a getter method to access them.
-(String*)getiVar{
return iVar;
}
A: Finally, the solution is to use NS_ENUM.
Like that:
typedef NS_ENUM(NSUInteger, shape) {
rectangle = 0,
triangle = 1,
square = 1,
...
};
-(void)changeShape:(shape)newShape; | unknown | |
d4042 | train | The math behind a Bézier path is actually "just":
start⋅(1-t)3 + 3⋅c1⋅t(1-t)2 + 3⋅c2⋅t2(1-t) + end⋅t3
This means that if you know, the start, the end and both control points (c1 and c2), then you can calculate the value for any t (from 0 to 1).
It the values are points (like in the image below) then you can do these calculations separately for x and y.
This is form my explanation of Bézier paths here and the code to update the orange circle as the slider changes (in Javascript) is simply this (it shouldn't be too hard to translate into Objective-C or simply C but I was too lazy):
var sx = 190; var sy = 80; // start
var ex = 420; var ey = 250; // end
var c1x = -30; var c1y = 350; // control point 1
var c2x = 450; var c2y = -20; // control point 2
var t = (x-minSliderX)/(maxSliderX-minSliderX); // t from 0 to 1
var px = sx*Math.pow(1-t, 3) + 3*c1x*t*Math.pow(1-t, 2) + 3*c2x*Math.pow(t,2)*(1-t) + ex*Math.pow(t, 3);
var py = sy*Math.pow(1-t, 3) + 3*c1y*t*Math.pow(1-t, 2) + 3*c2y*Math.pow(t,2)*(1-t) + ey*Math.pow(t, 3);
// new point is at (px, py)
A: If you already have the control points to the bezier curve you would like to use for the timing function (of what I presume to be CAAnimation), then you should use the following function to get the appropriate timing function:
[CAMediaTimingFunction functionWithControlPoints:(float)c1x :(float)c1y :(float)c2x :(float)c2y]
However, if what you are trying to do is calculate the Y-locaiton of a bezier curve for a given X-location, you will have to calculate that yourself. Here is a reference for how to do so: Bezier Curves
A: Point location calculation from CGPath (Swift 4).
extension Math {
// Inspired by ObjC version of this code: https://github.com/ImJCabus/UIBezierPath-Length/blob/master/UIBezierPath%2BLength.m
public class BezierPath {
public let cgPath: CGPath
public let approximationIterations: Int
private (set) lazy var subpaths = processSubpaths(iterations: approximationIterations)
public private (set) lazy var length = subpaths.reduce(CGFloat(0)) { $0 + $1.length }
public init(cgPath: CGPath, approximationIterations: Int = 100) {
self.cgPath = cgPath
self.approximationIterations = approximationIterations
}
}
}
extension Math.BezierPath {
public func point(atPercentOfLength: CGFloat) -> CGPoint {
var percent = atPercentOfLength
if percent < 0 {
percent = 0
} else if percent > 1 {
percent = 1
}
let pointLocationInPath = length * percent
var currentLength: CGFloat = 0
var subpathContainingPoint = Subpath(type: .moveToPoint)
for element in subpaths {
if currentLength + element.length >= pointLocationInPath {
subpathContainingPoint = element
break
} else {
currentLength += element.length
}
}
let lengthInSubpath = pointLocationInPath - currentLength
if subpathContainingPoint.length == 0 {
return subpathContainingPoint.endPoint
} else {
let t = lengthInSubpath / subpathContainingPoint.length
return point(atPercent: t, of: subpathContainingPoint)
}
}
}
extension Math.BezierPath {
struct Subpath {
var startPoint: CGPoint = .zero
var controlPoint1: CGPoint = .zero
var controlPoint2: CGPoint = .zero
var endPoint: CGPoint = .zero
var length: CGFloat = 0
let type: CGPathElementType
init(type: CGPathElementType) {
self.type = type
}
}
private typealias SubpathEnumerator = @convention(block) (CGPathElement) -> Void
private func enumerateSubpaths(body: @escaping SubpathEnumerator) {
func applier(info: UnsafeMutableRawPointer?, element: UnsafePointer<CGPathElement>) {
if let info = info {
let callback = unsafeBitCast(info, to: SubpathEnumerator.self)
callback(element.pointee)
}
}
let unsafeBody = unsafeBitCast(body, to: UnsafeMutableRawPointer.self)
cgPath.apply(info: unsafeBody, function: applier)
}
func processSubpaths(iterations: Int) -> [Subpath] {
var subpathArray: [Subpath] = []
var currentPoint = CGPoint.zero
var moveToPointSubpath: Subpath?
enumerateSubpaths { element in
let elType = element.type
let points = element.points
var subLength: CGFloat = 0
var endPoint = CGPoint.zero
var subpath = Subpath(type: elType)
subpath.startPoint = currentPoint
switch elType {
case .moveToPoint:
endPoint = points[0]
case .addLineToPoint:
endPoint = points[0]
subLength = type(of: self).linearLineLength(from: currentPoint, to: endPoint)
case .addQuadCurveToPoint:
endPoint = points[1]
let controlPoint = points[0]
subLength = type(of: self).quadCurveLength(from: currentPoint, to: endPoint, controlPoint: controlPoint,
iterations: iterations)
subpath.controlPoint1 = controlPoint
case .addCurveToPoint:
endPoint = points[2]
let controlPoint1 = points[0]
let controlPoint2 = points[1]
subLength = type(of: self).cubicCurveLength(from: currentPoint, to: endPoint, controlPoint1: controlPoint1,
controlPoint2: controlPoint2, iterations: iterations)
subpath.controlPoint1 = controlPoint1
subpath.controlPoint2 = controlPoint2
case .closeSubpath:
break
}
subpath.length = subLength
subpath.endPoint = endPoint
if elType != .moveToPoint {
subpathArray.append(subpath)
} else {
moveToPointSubpath = subpath
}
currentPoint = endPoint
}
if subpathArray.isEmpty, let subpath = moveToPointSubpath {
subpathArray.append(subpath)
}
return subpathArray
}
private func point(atPercent t: CGFloat, of subpath: Subpath) -> CGPoint {
var p = CGPoint.zero
switch subpath.type {
case .addLineToPoint:
p = type(of: self).linearBezierPoint(t: t, start: subpath.startPoint, end: subpath.endPoint)
case .addQuadCurveToPoint:
p = type(of: self).quadBezierPoint(t: t, start: subpath.startPoint, c1: subpath.controlPoint1, end: subpath.endPoint)
case .addCurveToPoint:
p = type(of: self).cubicBezierPoint(t: t, start: subpath.startPoint, c1: subpath.controlPoint1, c2: subpath.controlPoint2,
end: subpath.endPoint)
default:
break
}
return p
}
}
extension Math.BezierPath {
@inline(__always)
public static func linearLineLength(from: CGPoint, to: CGPoint) -> CGFloat {
return sqrt(pow(to.x - from.x, 2) + pow(to.y - from.y, 2))
}
public static func quadCurveLength(from: CGPoint, to: CGPoint, controlPoint: CGPoint, iterations: Int) -> CGFloat {
var length: CGFloat = 0
let divisor = 1.0 / CGFloat(iterations)
for idx in 0 ..< iterations {
let t = CGFloat(idx) * divisor
let tt = t + divisor
let p = quadBezierPoint(t: t, start: from, c1: controlPoint, end: to)
let pp = quadBezierPoint(t: tt, start: from, c1: controlPoint, end: to)
length += linearLineLength(from: p, to: pp)
}
return length
}
public static func cubicCurveLength(from: CGPoint, to: CGPoint, controlPoint1: CGPoint,
controlPoint2: CGPoint, iterations: Int) -> CGFloat {
let iterations = 100
var length: CGFloat = 0
let divisor = 1.0 / CGFloat(iterations)
for idx in 0 ..< iterations {
let t = CGFloat(idx) * divisor
let tt = t + divisor
let p = cubicBezierPoint(t: t, start: from, c1: controlPoint1, c2: controlPoint2, end: to)
let pp = cubicBezierPoint(t: tt, start: from, c1: controlPoint1, c2: controlPoint2, end: to)
length += linearLineLength(from: p, to: pp)
}
return length
}
@inline(__always)
public static func linearBezierPoint(t: CGFloat, start: CGPoint, end: CGPoint) -> CGPoint{
let dx = end.x - start.x
let dy = end.y - start.y
let px = start.x + (t * dx)
let py = start.y + (t * dy)
return CGPoint(x: px, y: py)
}
@inline(__always)
public static func quadBezierPoint(t: CGFloat, start: CGPoint, c1: CGPoint, end: CGPoint) -> CGPoint {
let x = QuadBezier(t: t, start: start.x, c1: c1.x, end: end.x)
let y = QuadBezier(t: t, start: start.y, c1: c1.y, end: end.y)
return CGPoint(x: x, y: y)
}
@inline(__always)
public static func cubicBezierPoint(t: CGFloat, start: CGPoint, c1: CGPoint, c2: CGPoint, end: CGPoint) -> CGPoint {
let x = CubicBezier(t: t, start: start.x, c1: c1.x, c2: c2.x, end: end.x)
let y = CubicBezier(t: t, start: start.y, c1: c1.y, c2: c2.y, end: end.y)
return CGPoint(x: x, y: y)
}
/*
* http://ericasadun.com/2013/03/25/calculating-bezier-points/
*/
@inline(__always)
public static func CubicBezier(t: CGFloat, start: CGFloat, c1: CGFloat, c2: CGFloat, end: CGFloat) -> CGFloat {
let t_ = (1.0 - t)
let tt_ = t_ * t_
let ttt_ = t_ * t_ * t_
let tt = t * t
let ttt = t * t * t
return start * ttt_
+ 3.0 * c1 * tt_ * t
+ 3.0 * c2 * t_ * tt
+ end * ttt
}
/*
* http://ericasadun.com/2013/03/25/calculating-bezier-points/
*/
@inline(__always)
public static func QuadBezier(t: CGFloat, start: CGFloat, c1: CGFloat, end: CGFloat) -> CGFloat {
let t_ = (1.0 - t)
let tt_ = t_ * t_
let tt = t * t
return start * tt_
+ 2.0 * c1 * t_ * t
+ end * tt
}
}
Usage:
let path = CGMutablePath()
path.move(to: CGPoint(x: 10, y: 10))
path.addQuadCurve(to: CGPoint(x: 100, y: 100), control: CGPoint(x: 50, y: 50))
let pathCalc = Math.BezierPath(cgPath: path)
let pointAtTheMiddleOfThePath = pathCalc.point(atPercentOfLength: 0.5) | unknown | |
d4043 | train | You Can use Java Script Regular Expression to validate input following code will do what you want
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9\b _ _%]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Here is a working js fiddle example
Validation Js Fiddle
A: Try this example:
script
$(function(){
$("input.rejectSpecial").on('input', function(){
this.value = this.value.replace(/(\>|\<|\(|\)|\"|\'|\\|\/|\*|;|\:|\=|\{|\}|`|%|\+|\^|\!|\-)/g, '');
});
})
html
<input type="text" placeholder="special letters not allowed" size="30" class="rejectSpecial"/>
<input type="text" placeholder="does nothing" size="30"/>
<input type="text" placeholder="special letters not allowed" size="30" class="rejectSpecial"/> | unknown | |
d4044 | train | It is really impossible to do those navigation steps with the phantomjs engine. It seems that the QtWebkit fork of phantom (version 1.9.7) is not up to the task anymore. Although your code works fine as is with slimerjs. You can comfortably install slimerjs through npm:
npm install -g slimerjs
and run your script with
casperjs --engine=slimerjs script.js
I tried several things with phantomjs that did not work. I added casper.on listeners for remote.message and resource.error, but those didn't show any errors when running the script in phantom. logLevel: "debug" also didn't show anything.
First: Using a casperjs function.
casper.thenClick("div.talk-sharing__tools a.rate-button");
Second: Trying to explicitly show the modal for the button (specific to the page).
casper.then(function(){
var name = this.evaluate(function(){
var modal = document.querySelectorAll(".modal-wrapper > .modal")[0];
modal.className += " modal--show";
return modal.className;
});
this.echo("name: "+name); // null
});
casper.waitUntilVisible(".modal__head__title");
Third: Let jQuery do the work.
var casper = require('casper').create({
remoteScripts: [ "http://code.jquery.com/jquery-1.11.1.min.js" ]
});
casper.waitForSelector(selector, function() {
this.evaluate(function() {
jQuery("a.rate-button").click();
});
});
A: Encountered similar issue today. After executing this.click() on start page (which I verified that PhantomJS is executing - by hooking into resource.requested and resource.received events), current page remained on start page (and it should go to clicked link page).
Solution was to update to the latest PhantomJS (1.9.8 at this moment).
Please note that I had PhantomJS 1.9.7 when the above described problem occurred. | unknown | |
d4045 | train | Downcasting is the act of casting a
reference of a base class to one of
its derived classes.
http://en.wikipedia.org/wiki/Downcasting
No, you do not downcast, since double and int are not classes.
A: No, you are not down casting. You are just casting, and you're chopping off anything after the decimal.
Down casting doesn't apply here. The primitives int and double are not objects in C++ and are not related to each other in the way two objects in a class hierarchy are. They are separate and primitive entities.
Down casting refers to the act of casting one object into another object that derives from it. It refers to the act of moving down from the root of the class hierarchy. It has nothing to do with the sizes of types in question.
A: int and double are both primitives and not classes, so the concepts of classes don't apply to them.
Yes, it is a conversion from a "larger" to a "smaller" type (in terms of numerical size), but it's just a "cast" and not a "downcast"
A: The two aren't so much opposite as simply unrelated. In the example case, we're taking a value of one type, and the cast takes that and produces a similar value of a type that's vaguely similar, but completely unrelated.
In the case of traversing an inheritance tree with something like dynamic_cast, we're taking a pointer (or reference) to an object, and having previously decided to treat it as a pointer to some other type of object, we're basically (attempting to) treat it as (something closer to) the original type of object again. In particular, however, we're not creating a new or different value at all -- we're simply creating a different view of the same value (i.e., the same actual object).
A: You aren't casting -- you're converting. Different thing entirely. | unknown | |
d4046 | train | Try using mysqli_query instead of mysql_query.
I think mysqli_connect returns an object and mysql_query needs a string. | unknown | |
d4047 | train | You can use UNION to combine two queries that have same structure , also you should select from combined result and then order them
SELECT * FROM (
SELECT fecha_salida, COUNT(*) AS agencia
FROM ventas
WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00'
and ventas.eliminado = 0
AND ventas.cliente_id = 2
GROUP BY fecha_salida
UNION
SELECT fecha_salida, COUNT(*) AS agencia
FROM ventas
WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00'
and ventas.eliminado = 0
AND ventas.cliente_id != 2
GROUP BY fecha_salida
) RESULT
ORDER BY agencia | unknown | |
d4048 | train | The compiler message makes the error clear: There is no method ToDictionary which can accept the arguments and types specified.
The mistake here is in specifying the type arguments on ToDictionary. The MSDN documentation defines the extension method as ToDictionary<TKey, TSource>. The source in your example is IEnumerable<AnonymousType#1>, but you have specified a type of List<string>.
To correct the error, omit the type arguments; the compiler will infer the correct types. You can additionally combine the Select and ToDictionary transformations into a single statement:
var contacts = dr.mktDoctorContacts
.GroupBy(x => x.ContactType)
.ToDictionary(
y => y.Key,
y => y.Select(x => x.Contact).ToList());
A: Rewrote your code (and added .AsEnumerable()):
var dictionary = dr.mktDoctorContacts
.GroupBy(x => x.ContactType)
.AsEnumerable()
.ToDictionary(
i => i.Key,
i => i.Select(x => x.Contact).ToList()
)
);
A: Don't run that group operation in the database, it'll cause the elements of each group to be fetched in separate roundtrips.
ILookup<string, string> contacts = dr.mktDoctorContacts
.ToLookup<Contact, string, string>(x => x.ContactType, x => x.Contact); | unknown | |
d4049 | train | official documentations explains everything (for android)
You can see that H.265 main profile is supported by 5.0+ devices. Also some other profiles are supported by some devices, but their support is implemented by the manufacturers. The documentation lists the formats that are granted to be played. All other formats may be playable, or not depending on the device model and manufacturer. So if you want to support at least most part of the devices, you'll have to follow that table. | unknown | |
d4050 | train | GNU is not a compiler. It is an Operating System and a collection of free software made to be "Unix like" without using Unix.
(GNU stands for "GNU's not Unix!")
GCC stands for "GNU Compiler Collection" and is a piece of GNU software that includes a compiler with frontends for multiple languages:
The standard compiler releases since 4.6 include front ends for C
(gcc), C++ (g++), Objective-C, Objective-C++, Fortran (gfortran), Java
(gcj), Ada (GNAT), and Go (gccgo).
MinGW stands for "Minimalist GNU for Windows" It is essentially a tool set that includes some GNU software, including a port of GCC.
In summary, MinGW contains GCC which is in the collection of GNU free software.
Further Reading Below:
GNU - https://en.wikipedia.org/wiki/GNU
GCC - https://en.wikipedia.org/wiki/GNU_Compiler_Collection#cite_note-39
MinGW - http://www.mingw.org/ | unknown | |
d4051 | train | yes , it works with AgroalDataSource
A: Fixed with latest (2.2.3.Final) version. | unknown | |
d4052 | train | Separation of concerns: you don't want to muddy your nice clean implementation of fib with all the bookkeeping required to make it more efficient. Let fib compute Fibonacci numbers, and let Memoize worry about memoizing fib (or any other function). | unknown | |
d4053 | train | Tested on Chrome, and it scrolls just fine.
Scrolling is controlled by your mouse settings, so maybe something changed with your scroll wheel? | unknown | |
d4054 | train | You have to use [SyncVars] Attribute. In short what it does is it synchronize a variable from client to the server. Here is a simple example from Unity3d Documentation.
[SyncVar]
int health;
public void TakeDamage(int amount)
{
if (!isServer)
return;
health -= amount;
}
another way to do this is by using custom WebSocket implementation for Unity3D. There a few very good ones in GitHub.Also please take a look at the documentation Unity3d | unknown | |
d4055 | train | You'll need JavaScript for this. HTML's target can't target the window's parent (opener) window.
The following will open the page in the parent window if JavaScript is enabled, and open it in a new window if it is disabled. Also, it will react gracefully if the current page does not have an opener window.
<a href="page.php"
onclick="if (typeof window.opener != 'undefined') // remove this line break
window.opener.location.href = this.href; return false;"
target="_blank">
Click
</a>
MDC Docs on window.opener
A: Use parent.location.href if it's on the same page in an iframe. Use opener.location.href if it's another entire tab/window.
A: Use window.opener.location.href in javascript
For example,
<a href="javascript:void(0);" onclick="window.opener.location.href='linkedFile.html';">Click me!</a> | unknown | |
d4056 | train | You need to send some headers so the browser knows how to handle the thing you are streaming. In particular:
Response.ContentType = "image/png"
Response.ContentType = "image/jpg"
etc.
Also note that for anything different than PDF, you are setting the content-disposition to "Content-Disposition", "application; filename=" + FileName) which will force a download. | unknown | |
d4057 | train | It just deletes the struct -in your case node- it points to, you can still use that pointer -make it point to another node-, in fact there's no way delete the pointer itself since it's allocated on the stack. it's automatically "deleted" when you leave the function.
p.s: no need to set current->next to null
A: Delete just free's the memory pointed to. This has the following implications:
*
*You are not allowed to access the memory at this location (use after free)
*The amount of memory you needed for your Node object is free, meaning your program would use less RAM.
*The pointer itself points either to a non-valid location or NULL, if you follow best practise and set it to NULL manually.
*The data at the memory location where your object was can be overwritten by any other task that has a valid pointer on this location. So technically the Node data still remains in memory as long as nobody else overwrites it.
A: Assuming that you have allocated your object using new delete on a pointer does the following:
*
*calls the destructor of the object
*request that the memory is free ( when that happens is actually implementation dependent )
At some point the memory manager will free and mark it as non-accessible by the process.
Thus it is up to you to set the pointer after calling delete to an agreed value. The best practice it to set it as nullptr for the latest compilers.
A: delete p causes the object pointed to by p to cease to exist. This means that
1, If the object has a destructor, it is called; and
2. p becomes an invalid pointer, so that any attempt to dereference it is undefined behaviour.
Generally, the memory occupied by said object becomes available to the program again, though this is really an implementation detail.
The phrase "delete the pointer" is normally a sloppy shorthand for "delete the object pointed-to by the pointer".
A: It does delete the actual structure pointed to by current. Pointers remain intact. No need for defining destructor.
The delete operator is to be applied to pointer to object. The pointer is an address of memory on heap allocated by calling new. Internally there is just table of addresses allocated by new. So the key to free such memory is just that address. In your case such address is stored in variable of type pointer to Node named current.
There are few problems in your code. The problematic one is that you have no posibility to tell whether node stored in current is actually allocated on heap. It might happen that current node is allocated on stack. E.g.
void someFunction(LinkedList &list) {
Node myLocalNode(10);
list.add(&myLocalNode);
list.remove(10); //<-- disaster happens here
}
The same applies to statically allocated global variables.
You must take care of extreme cases. Think about what happens when deleted object is the first one, pointed by variable head. By deleteing its memory you end up with dangling pointer in head, pointing to either unallocated memory or memory used by someone else.
My third objection is to writing such structure at all. I hope it is just some school excercise, because in any other cases you should (almost must) use some existing list like std::list from C++ STL.
A: Whenever you call delete on a pointer variable, the object to which it is pointing to gets deleted from the memory, however the 4 bytes allocated to the actual pointer variable (in your case, the current variable), the 4 bytes will be freed only when the variable will go out of scope, ie At the end of the function | unknown | |
d4058 | train | Too nice a challenge to pass.
Pretty sure not achievable via CSS alone, I expected it to be easier with JS.
Ended up as a bit of both:
class zoomFactor {
constructor(el) {
this.el = this.query(el, document);
this.update();
this.query('input').addEventListener('input', () => this.update());
window.addEventListener('resize', () => this.update())
}
query(s, el = this.el) {
return el.querySelector(s);
}
value() {
return this.query('input') ?
this.query('input').value :
parseFloat(this.el.dataset('scale')) || 1;
}
update() {
let val = this.value(),
z1 = this.query('z-1'),
z2 = this.query('z-2'),
z3 = this.query('z-3');
z1.style = z2.style = z3.style = '';
z2.style.width = z1.clientWidth * val + 'px';
z1.style.width = z2.style.width;
z3.style.transform = 'scale(' + val + ')';
z3.style.width = z2.clientWidth / val + 'px';
z1.style.height = z3.clientHeight * val + 'px';
}
}
new zoomFactor('zoom-factor');
.range {
display: flex;
justify-content: center;
}
.range input {
width: 70%;
}
zoom-factor {
position: relative;
display: block;
}
z-1,
z-2,
z-3 {
display: block;
color: white;
}
z-1 {
width: 50%;
float: left;
overflow: hidden;
position: relative;
margin: 1em 1em .35em;
}
z-2 {
position: absolute;
width: 100%;
background-color: red;
}
z-3 {
transform-origin: left top;
background-color: blue;
}
z-3 p {
text-align: justify;
}
p,
h3 {
padding-right: 1em;
padding-left: 1em;
}
h3 {
margin-top: 0;
padding-top: 1em;
}
z-3>*:last-child {
padding-bottom: 1em;
}
<zoom-factor>
<div class="range">
<input type="range" value=".8" min="0.05" max="1.95" step="0.01">
</div>
<z-1>
<z-2>
<z-3>
<h3>Transformed content</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Elit ut aliquam purus sit amet. Non pulvinar neque laoreet suspendisse interdum consectetur libero. Sed euismod nisi porta
lorem mollis aliquam ut. Mattis nunc sed blandit libero volutpat. Bibendum at varius vel pharetra vel. Nibh situs amet commodo nulla facilisi nullam vehicula ipsum. Metus aliquam eleifend mi in nulla posuere sollicitudin. Dolor morbi non arcu
risus. Venenatis urna cursus eget nunc.</p>
<p>In tellus integer feugiat scelerisque varius morbi enim nunc faucibus. Urna molestie at elementum eu facilisis sed odio. Arcu risus quis varius quam quisque. Lorem ipsum dolor sit amet. Fringilla est ullamcorper eget nulla facilisi etiam dignissim
diam quis. Arcu bibendum at varius vel pharetra vel turpis. Consectetur a erat nam at lectus urna. Faucibus pulvinar elementum integer enim neque volutpat ac tincidunt. Diam quam nulla porttitor massa id neque aliquam vestibulum. Nam libero
justo laoreet sit amet cursus sit amet dictum. Imperdiet sed euismod nisi porta lorem. Varius vel pharetra vel turpis nunc eget lorem dolor. Vitae auctor eu augue ut lectus arcu bibendum at varius. Aliquet enim tortor at auctor urna nunc id
cursus metus. Non curabitur gravida arcu ac tortor.</p>
</z-3>
</z-2>
</z-1>
<h3>Normal content</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Elit ut aliquam purus sit amet. Non pulvinar neque laoreet suspendisse interdum consectetur libero. Sed euismod nisi porta lorem
mollis aliquam ut. Mattis nunc sed blandit libero volutpat. Bibendum at varius vel pharetra vel. Nibh sit amet commodo nulla facilisi nullam vehicula ipsum. Metus aliquam eleifend mi in nulla posuere sollicitudin. Dolor morbi non arcu risus. Venenatis
urna cursus eget nunc.</p>
<p>In tellus integer feugiat scelerisque varius morbi enim nunc faucibus. Urna molestie at elementum eu facilisis sed odio. Arcu risus quis varius quam quisque. Lorem ipsum dolor sit amet. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam
quis. Arcu bibendum at varius vel pharetra vel turpis. Consectetur a erat nam at lectus urna. Faucibus pulvinar elementum integer enim neque volutpat ac tincidunt. Diam quam nulla porttitor massa id neque aliquam vestibulum. Nam libero justo laoreet
sit amet cursus sit amet dictum. Imperdiet sed euismod nisi porta lorem. Varius vel pharetra vel turpis nunc eget lorem dolor. Vitae auctor eu augue ut lectus arcu bibendum at varius. Aliquet enim tortor at auctor urna nunc id cursus metus. Non curabitur
gravida arcu ac tortor.</p>
<p>In metus vulputate eu scelerisque felis. Quam quisque id diam vel quam elementum pulvinar etiam. Porttitor leo a diam sollicitudin tempor id eu nisl. Feugiat in fermentum posuere urna nec tincidunt praesent semper feugiat. Mattis rhoncus urna neque
viverra. Euismod elementum nisi quis eleifend quam adipiscing. Enim diam vulputate ut pharetra sit amet. Adipiscing tristique risus nec feugiat in fermentum posuere urna nec. Risus sed vulputate odio ut. Augue interdum velit euismod in pellentesque.
Consequat interdum varius sit amet mattis vulputate enim nulla aliquet. At quis risus sed vulputate odio ut enim. In egestas erat imperdiet sed euismod nisi porta.</p>
<p>In arcu cursus euismod quis viverra nibh. Adipiscing commodo elit at imperdiet. Consectetur adipiscing elit duis tristique sollicitudin. Dui ut ornare lectus sit amet est placerat in. Felis eget nunc lobortis mattis. Pellentesque dignissim enim sit
amet. Senectus et netus et malesuada. A lacus vestibulum sed arcu non odio. Congue quisque egestas diam in arcu cursus euismod quis viverra. Nisi scelerisque eu ultrices vitae auctor eu augue. Sapien faucibus et molestie ac feugiat sed. Ullamcorper
a lacus vestibulum sed arcu.</p>
<p>Varius vel pharetra vel turpis nunc eget lorem. Odio ut enim blandit volutpat maecenas volutpat. Tellus in hac habitasse platea dictumst vestibulum rhoncus est. Sed sed risus pretium quam. Vel pharetra vel turpis nunc eget lorem dolor. Sit amet porttitor
eget dolor morbi. Mattis nunc sed blandit libero volutpat sed. Sit amet nulla facilisi morbi tempus iaculis urna id volutpat. Maecenas ultricies mi eget mauris pharetra et ultrices neque. Congue nisi vitae suscipit tellus. Accumsan tortor posuere
ac ut consequat semper viverra. In fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Sed velit dignissim sodales ut. Tempus urna et pharetra pharetra massa massa ultricies. Ornare aenean euismod elementum nisi quis eleifend quam.
Aliquet nibh praesent tristique magna sit amet purus gravida. Euismod lacinia at quis risus sed vulputate. Ultrices mi tempus imperdiet nulla.</p>
</zoom-factor>
Most likely you won't want the input[type="range"] and want to control the scale from outside. You can simply pass <zoom-factor> a data-scale attribute and init it:
const zFactor = new zoomFactor('zoom-factor');
You don't really need to store it in a const, but it's useful for changing the scale:
zFactor.el.dataset('scale') = 0.5;
zFactor.update();
I'll probably wrap it up as a plugin, but I want to test it cross-browser and provide a few more options (i.e. allow changing the transform origin to center or right, create an auto-init method, etc...), to make it more flexible. | unknown | |
d4059 | train | One way you can do this is using children routes. This will help you load components inside of another component. You will need to add the router outlet tag inside the parent component for this to work. Let me know if that helps. | unknown | |
d4060 | train | I would personally simplify the design like this:
Table: person
*
*person_id (primary key)
*...
Table: name
*
*name_id (primary key)
*name
*name_type
*parent_name_id (foreign key of itself)
*person_id (foreign key of person table)
The table name has a recursive relationship where parent_name_id contains the name_id of the main name of the person. Note that for the main name name_id=parent_name_id. In the column name_type you can store the type of name (phonetic, ideogram, kanji, etc.). You can possibly normalize further the name_type into a dedicated table if you wish to have pure third normal form.
I would say the main benefit of this design is that it greatly simplifies your query when querying for names of any type. You can simply run something like this:
Select distinct b.person_id, b.name as main_name
From name a
Inner join name b on a.parent_name_id=b.name_id
Where a.name like ‘%...%’
In addition you can store as many names as you want for a single person.
If you want to return several names from different types you can do like this:
Select distinct b.person_id,
b.name as main_name,
c.name as kanji_name,
d.name as katakana_name
From name a
Inner join name b on a.parent_name_id=b.name_id
Left join name c on b.parent_name_id=c.parent_name_id and c.name_type=‘kanji’
Left join name d on b.parent_name_id=d.parent_name_id and d.name_type=‘katakana’
Etc...
Where a.name like ‘%...%’ | unknown | |
d4061 | train | Not sure if you still running into this issue or not but your on an older release of Intel's HAXM. The current release is: HAX 1.0.8 Download
I saw your post and kept getting a crash.
When tailing the /var/log/system.log on Mac OSX 10.9 I would see your above messages. When I tried to reinstall the HAX I would see the below:
Aug 19 12:03:55 3c15c2cf84fe kernel[0]: haxm_error: -------- HAXM release 1.0.7 --------
Aug 19 12:03:55 3c15c2cf84fe kernel[0]: haxm_error: This log collects runnging status of HAXM driver.
Aug 19 12:03:55 3c15c2cf84fe kernel[0]: haxm_error: set memlimit 0x80000000
I was able to resolve my issue by removing all of the AVD's that I created with Android Studio. From the AVD (Android Virtual Devices) just "Delete" all the emulators in your Virtual devices. Then start over.
If you get the below ERROR:
Do the following:
*
*Open up a Terminal Window.
*Type: ~/.android/avd
*From here remove everything by this command: rm -rf .
*NOTE: you will delete everything in the path that you run it from. All ways good to do: pwd <-- Print working directory so see what you will be removing.
*Start up the AVD again and recreate the devices you want.
I hope that helps someone.
A: Please make sure that the memory you allocate for the emulator during install is always greater than the memory you specify while creating an instance of the emulator.
A: I would want to check that there are no faults with the RAM on the machine. If the memory is faulty, it could mean that data is lost and the emulator doesn't know how to cope with this situation. CNET cover how to test memory on a Mac in this recent article http://www.cnet.com/uk/how-to/how-to-test-the-ram-on-your-mac/
It will take a long while to do the extended test, but it does need ruling out if you want to find the problem here. | unknown | |
d4062 | train | git merge-base --is-ancestor A B
if [ $? -eq 0 ]
then
# it's an ancestor
else
# it's not an ancestor
fi
This is obviously working on the commits that the branches point to. Git doesn't really track branch lineage the way something like Clearcase does though, so it's quite possible that you could have had A first, then branched off B, and then as a result of some merging end up with B as an ancestor to A. | unknown | |
d4063 | train | The RedisMessageStore does not have any expiration features. And technically it must not. The point of this kind of store is too keep data until it is used. Look at it as persistent storage. The RedisMetadataStore is based on the RedisProperties object, so it also cannot use expiration feature for particular entry.
You probably talk about a MessageGroupStoreReaper, which really calls a MessageGroupStore.expireMessageGroups(long timeout), but that's already an artificial, cross-store implementation provided by the framework. The logic relies on the group.getTimestamp() and group.getLastModified(). So, still not that auto-expiration Redis feature.
The MessageGroupStoreReaper is a process needed to be run in your application: nothing Redis-specific.
See more info in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/message-routing.html#reaper | unknown | |
d4064 | train | Here is how I by-pass the issue:
In the IMPORT A LOCALIZATION PACK form, uncheck Currency.
Import the pack, and create the currency manually. | unknown | |
d4065 | train | No, there's not. The point is that you're not rebuilding the sources, you're rebuilding binaries.
What you can do is build an intermediate .o consisting only of the shared sources, and then use that in your tests, and binaries. | unknown | |
d4066 | train | After an actual 2 hours of googling here's a rule that can use the fill handle to satisfy this
=IF($A:$A<=5, true)
And then adapt for between / greater than. | unknown | |
d4067 | train | Actually when you set the variable to c='0', it means that the value of c is now the ascii value of '0' and that is = 48.
Since you are setting the value of c to 48 but the array size is 10, your code will get a runtime exception because you are trying to access an index that doesn't even exist.
Remember when you use '0' it means character. So setting this value to an int variable makes the value equals to the ascii value of that character. Instead you can use c=0 directly.
A: Because the character '4' (for example) is usually not equal to the integer 4. I.e. '4' != 4.
Using the most common character encoding scheme ASCII, the character '4' has the value 52, and the character '0' has the value 48. That means if you do e.g. '4' - '0' you in practice to 52 - 48 and get the result 4 as an integer. | unknown | |
d4068 | train | The following fiddle demonstrates how to call functions when repeating over items. You could also just pass in an id to the remove function.
<input value="Remove From Room" type="button" ng-click="removeStudent(student)"/>
</div>
$scope.removeStudent = function(student) {
angular.forEach($scope.studentList, function(checkStudent, index) {
if (checkStudent.id === student.id) {
$scope.studentList.splice(index,1);
}
});
};
http://jsfiddle.net/houston88/ab23r/1/ | unknown | |
d4069 | train | there are some little errors in you code, I fixed them and pointed them with arrows (◄■■■) :
.stack 100h ;◄■■■ PROCEDURES REQUIERE STACK.
.data
S dw ? ;◄■■■ DW, NOT BYTE, BECAUSE AX IS TYPE DW.
.code
main proc
call ven
;call outdec
MOV AH,4ch
INT 21h
main endp
ven proc
MOV S,0
L1:
INC S ;◄■■■ S+1
CMP S,20 ;◄■■■ IF S > 20...
JA ter ;◄■■■ ...JUMP TO TER.
MOV AX,S
MOV bl,2
DIV bl
CMP AH,0
JE EVE
JNE ODD
EVE:
MOV AH,2
MOV DL,AL ;◄■■■ HERE YOU PRINT "AL", BUT THE NUMBER
INT 21h ;◄■■■ TO PRINT IS "S". USE "CALL OUTDEC".
jmp L1
ODD:
MOV AH,2
MOV DL,AL ;◄■■■ HERE YOU PRINT "AL", BUT THE NUMBER
INT 21h ;◄■■■ TO PRINT IS "S". USE "CALL OUTDEC".
jmp L1
ter:
RET
ven ENDP
END MAIN | unknown | |
d4070 | train | Simply wrap the output in an <a> tag
<td><font face="Arial, Helvetica, sans-serif"><a href="http://sitename.com/<?php echo $f5; ?>"><?php echo $f5; ?></a></font></td>
A: The following will print a link containing the fixed URL.
<?php
$url = 'http://www.' . $_SERVER['SERVER_NAME'] . '/' . $f1;
echo '<a href="' . $url . '">Click here to download the file!</a>';
On the off-chance that $_SERVER['SERVER_NAME'] is not correct for your website, you can simply replace it with the correct domain name. | unknown | |
d4071 | train | Change to this and check again.
if(first_name.length() == 0)
{
Toast.makeText(NameOfYourActivity.this, "Please fill Name", Toast.LENGTH_SHORT).show();
Utilities.writeIntoLog("Please fill Name");
}
A: just post the google code link here.
Since Jelly Bean, users can disable notifications for a given app via "app details" settings.
A very bad and unwanted side effect is that once notifs are disabled, Toast messages are also disabled, even when the user is running the app!
You encourage to use Toast in your design guidelines, but who will want to use it if the users have the possibility to remove them, especially if the toasted message is an important feedback to display to the user...
I understand at least that Toasts could be disabled when the app is in background, but not if it is the foreground Activity.
A: Toast was not showing with me in Android 4.1 because Show Notifications was checked off in my app's settings. I just went to Settings->Manage Applications->[My App] and toggled on Show Notifications and Toasts started to appear.
A: Toast is working fine in all the version of Android. There can be couple of issues in your code like
*
*Your context is not wrong
*You are trying to display toast in the background thread instead of worker thread.
Edit
In your custom toast don't set the parent in your layout inflater for example use like below
View layout = inflater.inflate(R.layout.toast_layout,null);
A: I had the same problem. When I invoked the code on UI thread the issue resolved for me
public void showToastMessage(final String msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(BaseActivity.this, msg, Toast.LENGTH_LONG).show();
}
});
} | unknown | |
d4072 | train | TextBlock MyText = new TextBlock();
Binding binding = new Binding();
binding.Path = new PropertyPath("Name"); //Name of the property in Datacontext
BindingOperations.SetBinding(MyText,TextBlock.TextProperty , binding);
If you want to bind to property of some other object you will need to set binding.Source to that object.
A: The other answers are technically more correct to this particular question given you are trying to create the binding in code, but usually people perform these simple bindings through xaml.
Xaml View:
<TextBox Text="{Binding MyTextPropertyFromViewModel}" />
C# ViewModel:
public String MyTextPropertyFromViewModel
{ get; set; }
A: That should be the target property of the binding, ie your TextBlock.TextProperty
See:
http://msdn.microsoft.com/en-us/library/system.windows.data.bindingoperations.setbinding.aspx | unknown | |
d4073 | train | As @danben mentioned, there is a difference between S3 and EC2.
One thing that may be interesting for people looking to host a website on Amazon, specially if they want to start small is that Amazon started offering a free tier some months ago. Together with services like BitNami Cloud Hosting (disclaimer, I helped design it, so it is a bit like my baby :) means you can get your site on the Amazon cloud in just minutes, for basically 0 dollars. You still need to give credit card info to Amazon, but it will not be charged if you stay within the limits of their free tier.
One thing to consider too is that at the time of writing this (Jul 2011), Amazon restricts you to one IP address per server. If you need to host multiple domains, you may need to use name-based virtual hosts or some tricks using their Elastic Load Balancer (which will cost you more). But all in all, it is worth a try if you are a bit technical and want more control than what shared hosting provides you
A: AWS = Amazon Web Services = a suite of different web services.
S3 (which you linked to) is an object store. You can't host a web service on S3.
EC2, also under the AWS umbrella, is virtualized compute space. You CAN host a web service on EC2. It is just like having a server in a rack somewhere, except that when you shut down an instance, it is gone forever. But using EBS, which is like a virtualized hard drive, will prevent you from losing your data when the EC2 instance shuts down.
See http://aws.amazon.com/ec2/ and http://aws.amazon.com/ebs/
A: EDIT: Aug 12, 2016 they have a dedicated section on how to get started hosting a website on AWS. Please note S3 only allows STATIC websites but AWS provides SDKs in case you want to run PHP, ASP.NET, etc on your instance. See the links for more details.
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html
https://aws.amazon.com/websites/
So guess what I just found while doing some Google searches for hosting on AWS?! A blog post by the AWS stating that you can (now) host a website on S3. (Funny enough, the StackOverflow and the AWS post were right next to each other in the SERPs!)
http://aws.typepad.com/aws/2011/02/host-your-static-website-on-amazon-s3.html
A: Yes it is completely possible to host websites on AWS in 2 ways:
1.) Easy - S3 (Simple Storage Solution) is a bucket storage solution that lets you serve static content e.g. images but has recently been upgraded so you can use it to host flat .html files and your site will get served by a default Apache installation with very little configuration on your part (but also little control).
2.) Trickier - You can use EC2 (Elastic Compute Cloud) and create a virtual Linux instance then install Apache/NGinx (or whatever) on that to give you complete control over serving whatever/however you want. You use SecurityGroups to enable/disable ports for individual machines or groups of them.
@danben your EC2 instance does not have a constant public IP by default. Amazon makes you use a CNAME - not an A record as your IP may change under load. You have to pay for an ElasticIP to get a consistent public IP for your setup (or use some sort of DynDNS)
A: At reinvent 2018, AWS launched the Amplify Console, a continuous deployment and hosting service for single page and static apps with serverless backends. Check it out: http://console.amplify.aws
A: Yes! You can easily host your website on AWS.
There are two ways;
*
*One with Native AWS - This is a tricky method that requires expertise and a series of commands to run. You need to manage security, DNS, SSL, server protocols, and more by yourself.
*Managed Cloud Platforms like Cloudways - You can easily launch an AWS server and host your website with a few clicks. Moreover, you can quickly manage your server protocols, packages, security firewalls, DNS, and more from its intuitive platform. | unknown | |
d4074 | train | Your entire trigger's code should be something like this:
MERGE INTO Table3 t
USING (SELECT TId,CASE WHEN COUNT(*) > 1 THEN 1 ELSE 3 END as C32
FROM deleted
GROUP BY TId) u
ON t.TId = u.TId
WHEN MATCHED THEN UPDATE SET C32 = 1
WHEN NOT MATCHED AND u.TId is not null THEN
INSERT (TId,C32,C33) VALUES (u.TId, u.C32, GETUTCDATE());
Which will insert a new row but decide whether to set C32 to 1 or 3, depending on how many rows in DELETED are for the same TId, and just update C32 to 1 if a row already existed.
This is all about thinking in sets. You weren't accounting for the fact that deleted could contain multiple rows, some or all of which may have the same TId value. You don't write IF/ELSE blocks that can only make a single decision for all rows in deleted1.
1E.g. if deleted had contained 4 rows total, 2 for TId 6 and 2 for TId 8, and Table3 had contained a row for TId 6 but no row for TId 8, your trigger would have found some matching rows in Table3 and just performed the UPDATE. | unknown | |
d4075 | train | I have 4 errors concerning lib/Varien/Crypt/Mcrypt.php
Warning: mcrypt_generic_init(): Key size is 0 in /lib/Varien/Crypt/Mcrypt.php on line 94
Warning: mcrypt_generic_init(): Key length incorrect in /lib/Varien/Crypt/Mcrypt.php on line 94
Warning: mcrypt_generic_deinit(): 495 is not a valid MCrypt resource in /lib/Varien/Crypt/Mcrypt.php on line 135
Warning: mcrypt_module_close(): 495 is not a valid MCrypt resource in /lib/Varien/Crypt/Mcrypt.php on line 136
I thought it was relative to a module is missing in PHP Mcrypt on my server (https://magento.stackexchange.com/a/35888). But it's not the case as by installing a fresh CE 1.9.3.1 in a folder in the root of the same Magento installation is doing its job properly with the same server configuration and Mcrypt.php. Moreover, the password set during registration with form (?and using the same encryption?), is set properly.
I'll open a new post with more precisions.
@urfusion, thank you for advice, I was looking at the wrong end of system.log (thought it was writing on the top...)
Edit
I got it, the solution's here:
https://stackoverflow.com/a/42474835/7553582 | unknown | |
d4076 | train | Used the following lodash functions:
Get the name of fruits using _.map.
uniqueFruitNames = Get the unique names by _.uniq and then sort them.
data2013 and data2014 = Use _.remove to get fruits of particular year and sort them respectively.
Use _.zipObject to zip uniqueFruitsName and data2013
uniqueFruitsName and data2014
Then _.merge the two zipped Objects.
var dataSeries = _.map(mergedData, function(asset,key) {
return {
name: key,
data: [fruit[0].amount, fruit[1].amount]
}
}); | unknown | |
d4077 | train | Use this flag when you are opening the C acitivity.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This will clear all the activities on top of C.
A: Since A is your root (starting) activity, consider using A as a dispatcher. When you want to launch C and finish all other activities before (under) it, do this:
// Launch ActivityA (our dispatcher)
Intent intent = new Intent(this, ActivityA.class);
// Setting CLEAR_TOP ensures that all other activities on top of ActivityA will be finished
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add an extra telling ActivityA that it should launch ActivityC
intent.putExtra("startActivityC", true);
startActivity(intent);
in ActivityA.onCreate() do this:
super.onCreate();
Intent intent = getIntent();
if (intent.hasExtra("startActivityC")) {
// Need to start ActivityC from here
startActivity(new Intent(this, ActivityC.class));
// Finish this activity so C is the only one in the task
finish();
// Return so no further code gets executed in onCreate()
return;
}
The idea here is that you launch ActivityA (your dispatcher) using FLAG_ACTIVITY_CLEAR_TOP so that it is the only activity in the task and you tell it what activity you want it to launch. It will then launch that activity and finish itself. This will leave you with only ActivityC in the stack. | unknown | |
d4078 | train | Answering my own question:
seq = shape as_seq | attr seq
as_seq = (shape | attr)*
does the trick
(where shape and attr are defined elsewhere in the grammar.
e.g. shape = 'a' and attr = 'b'. Then 'a' 'ab' 'aaab' 'bbbab' will all match but 'b' 'bb' 'bbb..' etc will not) | unknown | |
d4079 | train | I think you may want to look at http://chocolat.insipi.de.
It's a free cross browser JavaScript library that handles switching images.
A: This is my favorite gallery and it's easy to use.
https://sachinchoolur.github.io/lightgallery.js/ | unknown | |
d4080 | train | Answered in comments, so reposting comment as answer Re: https://meta.stackexchange.com/questions/90263/unanswered-question-answered-in-comments
You may have a hidden character / line feed etc?
Just select and delete the entire work "username" (after the SELECT) and try retyping. | unknown | |
d4081 | train | An alternative to the object property and deletion methods is calling the showMaxMin method on the chart object itself:
chart.yAxis.showMaxMin(false);
A: After rendering the chart do:
d3.selectAll(".nv-axisMaxMin-y").remove(); //it will remove the max min
Working code here
Hope this helps!
A: set chart : {
yAxis: {
showMaxMin : false
}
} | unknown | |
d4082 | train | The OAuth Client ID is obtained so that your app can access the Google Fit API. As the SHA-1 of your certificate is already known by Google Fit, you do not need to enter the actual Client ID into your code. Your certificate is part of your app, and identifies the app to Google Fit.
https://developers.google.com/fit/android/get-api-key | unknown | |
d4083 | train | Just so you know, you are not supposed to ask people to give you a code in this site. You should try to make your own first, and if you get any problems then ask for help. But, as far as your a php script for questions, then here is a an entire source code, from elanman.
http://blog.elanman.com/elanzips/php-quiz.zip
You also have the famous hotscripts, check it out here:
http://www.hotscripts.com/category/scripts/php/scripts-programs/tests-quizzes/ | unknown | |
d4084 | train | Right might be a little late to answer this but someone else may benefit.
On the canvas or display object housing the TextFlow and sprite add a creationComplete functon.
I don't know if this step is necessary, but it works for me. Add a label with the text thats going to go into TextFlow (with the same font and fontSize), add a creation complete listener to that as well.
Get the height and width from the newly created label e.target.width e.target.height (in the function listening to the creation of label). Set the displayObjects (in the above case Canvas) height and width to these values, then proceed to add the sprite and textflow.
Note: this was a lazy way for me, label uses measureText which would be a more efficent way of doing this. | unknown | |
d4085 | train | I think you just forgot to set the onClickListener in your ViewHolder constructor:
public VendorHolder(View itemView)
{
//These pull as null
super(itemView);
Vvendor_image = (ImageView)itemView.findViewById(R.id.vendor_image2);
Vvendor_name = (TextView)itemView.findViewById(R.id.vendor_name2);
Vvendor_content =(TextView)itemView.findViewById(R.id.vendor_content2);
Vvendor_suburb = (TextView)itemView.findViewById(R.id.vendor_suburb2);
Vrating = (RatingBar) itemView.findViewById(R.id.MyRating2);
// If it should be triggered only when clicking on a specific view, replace itemView with the view you want.
itemView.setOnClickListener(this);
} | unknown | |
d4086 | train | After this line:
datalist <- Filter(length, datalist)
Do:
datalist <- lapply(datalist, function(x) {
if(any(!x %in% mc_answers))
c(x[x %in% mc_answers], paste(x[!x %in% mc_answers], collapse = ", "))
else
x[x %in% mc_answers]
})
Then run the rest of your code as-is so you end up with:
> (data_per_person <- do.call('rbind', data_long))
data id
A.1 oranges A
A.2 apples A
A.3 peaches A
A.4 cherries, pineapples, strawberries A
B.1 oranges B
B.2 peaches B
B.3 pears B
C.1 pears C
C.2 nectarines C
C.3 cherries (bing, rainier) C
D.1 apples D
D.2 peaches D
D.3 nectarines D
A: You could also try:
library(data.table)
library(devtools)
source_gist(11380733) ##
df1 <- cSplit(df, "data", sep=", ", "long")
indx <- df1$data %in% mc_answers
res <- rbindlist(list(df1[indx,], df1[!indx,][, list(data=paste(data, collapse=", ")), by=id]))[order(id)]
res
# id data
#1: A oranges
#2: A apples
#3: A peaches
#4: A cherries, pineapples, strawberries
#5: B oranges
#6: B peaches
#7: B pears
#8: C pears
#9: C nectarines
#10: C cherries (bing, rainier)
#11: D apples
#12: D peaches
#13: D nectarines
A: How about something like this
do.call(rbind, lapply(split(df, df$id), function(x) {
v<-unlist(strsplit(x$data, ",\\s?"))
v<-c(v[v %in% mc_answers], paste(v[!v %in% mc_answers], collapse=", "))
v<-v[nchar(v)>0]
if (length(v)>0) {
data.frame(id=x$id[1], data=v)
} else {
NULL
}
}))
Here we split to process each group separately and then do the string splitting. Then we collapse all those entries that aren't in the mc_answers vector. It returns
id data
A.1 A oranges
A.2 A apples
A.3 A peaches
A.4 A cherries, pineapples, strawberries
B.1 B oranges
B.2 B peaches
B.3 B pears
C.1 C pears
C.2 C nectarines
C.3 C cherries (bing, rainier)
D.1 D apples
D.2 D peaches
D.3 D nectarines | unknown | |
d4087 | train | My small 5 cents.
Cucumber is mostly used for acceptance tests (correct me if you use it for unit testing) and Robolectric is mostly used for unit testing.
As for me, it is overkill to write cucumber during TDD. And Robolectric is still not android and I would run acceptance tests on real device or at least emulator.
A: I'am facing the same problem, after some google work, I got a solution:
@RunWith(ParameterizedRobolectricTestRunner::class)
@CucumberOptions( features = ["src/test/features/test.feature","src/test/features/others.feature"], plugin = ["pretty"])
class RunFeatures(val index: Int, val name:String) {
companion object {
@Parameters(name = "{1}")
@JvmStatic
fun features(): Collection<Array<Any>> {
val runner = Cucumber(RunFeatures::class.java)
Cucumber()
val children = runner.children
return children.mapIndexed{index, feature ->
arrayOf(index,feature.name)
}
}
}
@Test
fun runTest() {
val core = JUnitCore()
val feature = Cucumber(RunFeatures::class.java).children[index]!!
core.addListener(object: RunListener() {
override fun testFailure(failure: Failure?) {
super.testFailure(failure)
fail("$name failed:\n"+failure?.exception)
}
})
val runner = Request.runner(feature)
core.run(runner)
}
}
but seems not an pretty solution for me, can somebody help me out these problem:
*
*must explicitly list all feature file path. but cannot use pattern such as *.feature
*when failed cannot know which step failed.
*parameter can only pass primitive type data,
I've get into cucumber source , but seems CucumberOptions inline Cucumber , I cannot pass it programmatically but can only use annotation . | unknown | |
d4088 | train | You'll want to use some sort of java library for Microsoft Office. Take a look at Apache POI for this. Here's an example of using Apache POI.
As a side note, I would also recommend that the user doesn't have to actually connect their device to the computer, but rather make an export feature which will create the Word Document and they can e-mail it or share it in some other way. This would improve your User Experience :) | unknown | |
d4089 | train | When you say this:
var x = 6;
The var x declaration will be hoisted to the top of the current scope. However, the assignment part will not be hoisted. The result is that you're saying this:
var x;
// Everything from the top of the scope to your `var x = 6` goes here.
x = 6;
In your case, you're doing this:
var Users = Backbone.Collection.extend({
url: 'index.php/users',
model: User
});
var User = Backbone.Model.extend({
urlRoot: 'index.php/users',
defaults: {
user_id: 1,
name: 'Nathan',
}
});
so var User is hoisted to the top of the scope but User = Backbone.Model.extend(...) happens after Users = Backbone.Collection.extend(...). Rearranging the code to match what really happens, we have:
var Users, User;
Users = Backbone.Collection.extend({
//...
model: User
});
User = Backbone.Model.extend({
//...
});
What do you think the value of User will be when it is used in the definition of Users? User will be undefined just like any other uninitialized variable.
Demo: http://jsfiddle.net/ambiguous/xYkmc/
You need to define your User before Users:
var User = Backbone.Model.extend({
urlRoot: 'index.php/users',
defaults: {
user_id: 1,
name: 'Nathan',
}
});
var Users = Backbone.Collection.extend({
url: 'index.php/users',
model: User
});
Demo: http://jsfiddle.net/ambiguous/E7V84/ | unknown | |
d4090 | train | To use environment variable in react you need to prefix the variable name with process.env.REACT_APP_. Documentation
So in your .env file you have:
REACT_APP_DS_API_URL=[http://url.com](http:url.com/)
Then to use:
const url = `${process.env.REACT_APP_DS_API_URL}/graph/tech-stack-by-role`
Update to answer question:
update your start script to use the .env file you want. in this case it is .env.localhost. You will also need to npm install or yarn install env-cmd:
"start": "env-cmd -f ./.env.localhost react-scripts start", | unknown | |
d4091 | train | str.format() I got too in my head about this.
A: bphi is right, use string formatting
e.g.
test1 = "I think {name} should be our {position}. Only {name} is experienced. Who else could be a {position}?"
test1.format(name="Bob", position="top cat")
> 'I think Bob should be our top cat. Only Bob is experienced. Who else could be a top cat?'
A: def ModString(s, name_replacement, position_replacement):
return s.replace("{name}",name_replacement).replace("{position}", position_replacement)
Then:
Test1 = ModString(Test1, "Mary", "boss")
Test2 = ModString(Test2, "Mary", "boss")
or you can just use .format(), which is recommended
def ModString(s, name_replacement, position_replacement):
return s.format(name=name_replacement, position=position_replacement)
A: You have to use replace() Method, for example, read here: https://www.tutorialspoint.com/python/string_replace.htm
Test1 = "I think {name} should be our {position}. Only {name} is experienced. Who else could be a {position}?"
Test2 = "{name} is the only qualified person to be our {position}."
def ModString(str, name, position):
str = str.replace("{name}", name)
str = str.replace("{position}", position)
return str
Test1 = replaceWord(Test1, "Mary", "boss")
Test2 = replaceWord(Test2, "Mary", "boss") | unknown | |
d4092 | train | Check out Customizing the Navigation Bar section of this page.
Change the navigation background image and hide navigation bar on push
Also set prefersLargeTitles of bar as true only in iOS 11 | unknown | |
d4093 | train | Replace the content of your removeFile() method with this:
(given that the files variable is an array)
methods: {
removeFile(key) {
this.files.splice(key, 1);
}
You can also use the Vue helper for removing items in an array or a property in an object:
methods: {
removeFile(key) {
this.$delete(this.files, key);
} | unknown | |
d4094 | train | If you simply want to enumerate through your enum type you can use this:
foreach (InstructionType type in Enum.GetValues(typeof(InstructionType)))
{
if (type.ToString() == "ADD")
//do sth here
}
Problem is your enum is private, so it's not realy a possibility. The only option you have is to write a public method in IWorks.svc.cs that will do what you need, f.e:
public void foreachType(Action<T> action) {
//action can be invoked so it should be exacly what you want
} | unknown | |
d4095 | train | *
*You have a $scope.newCompany variable which is a function, not an object.
*When you initialize $scope.companyData, you call id: $scope.newCompany.id, where $scope.newCompany is undefined. Try define it first with all its properties ($scope.newCompany = {
id : "",
...
})
*Call your submit function something else.
*Do not create a function whose name itself a 'function'. (function: $scope.newCompany.function). This is reserved as a keyword.
These steps may be close to the result you want to see, if not reply back. | unknown | |
d4096 | train | Here is a working example for you to start. This is a very basic implementation.
*
*In the test case the stored passwords are visible. You do not want to authenticate in this way. It is unsafe. You need to find a way to hash the passwords and match. There are some clues on Huidong Tian github link
*I implemented the majority of the ui.r code in server.r. Not sure if there is a workaround. The drawback I notice is too many lines of code. It will be nice to break each side tab into a separate file. Did not try it myself yet. However, here is @Dean Attali superb shiny resource to split code
ui.r
require(shiny)
require(shinydashboard)
header <- dashboardHeader(title = "my heading")
sidebar <- dashboardSidebar(uiOutput("sidebarpanel"))
body <- dashboardBody(uiOutput("body"))
ui <- dashboardPage(header, sidebar, body)
server.r
login_details <- data.frame(user = c("sam", "pam", "ron"),
pswd = c("123", "123", "123"))
login <- box(
title = "Login",
textInput("userName", "Username"),
passwordInput("passwd", "Password"),
br(),
actionButton("Login", "Log in")
)
server <- function(input, output, session) {
# To logout back to login page
login.page = paste(
isolate(session$clientData$url_protocol),
"//",
isolate(session$clientData$url_hostname),
":",
isolate(session$clientData$url_port),
sep = ""
)
histdata <- rnorm(500)
USER <- reactiveValues(Logged = F)
observe({
if (USER$Logged == FALSE) {
if (!is.null(input$Login)) {
if (input$Login > 0) {
Username <- isolate(input$userName)
Password <- isolate(input$passwd)
Id.username <- which(login_details$user %in% Username)
Id.password <- which(login_details$pswd %in% Password)
if (length(Id.username) > 0 & length(Id.password) > 0){
if (Id.username == Id.password) {
USER$Logged <- TRUE
}
}
}
}
}
})
output$sidebarpanel <- renderUI({
if (USER$Logged == TRUE) {
div(
sidebarUserPanel(
isolate(input$userName),
subtitle = a(icon("usr"), "Logout", href = login.page)
),
selectInput(
"in_var",
"myvar",
multiple = FALSE,
choices = c("option 1", "option 2")
),
sidebarMenu(
menuItem(
"Item 1",
tabName = "t_item1",
icon = icon("line-chart")
),
menuItem("Item 2",
tabName = "t_item2",
icon = icon("dollar"))
)
)
}
})
output$body <- renderUI({
if (USER$Logged == TRUE) {
tabItems(
# First tab content
tabItem(tabName = "t_item1",
fluidRow(
output$plot1 <- renderPlot({
data <- histdata[seq_len(input$slider)]
hist(data)
}, height = 300, width = 300) ,
box(
title = "Controls",
sliderInput("slider", "observations:", 1, 100, 50)
)
)),
# Second tab content
tabItem(
tabName = "t_item2",
fluidRow(
output$table1 <- renderDataTable({
iris
}),
box(
title = "Controls",
sliderInput("slider", "observations:", 1, 100, 50)
)
)
)
)
} else {
login
}
})
}
A: I recently wrote an R package that provides login/logout modules you can integrate with shinydashboard.
Blogpost with example app
Package repo
the inst/ directory in the package repo contains the code for the example app.
A: @user5249203's answer is very useful, but as is will produce a (non-breaking) due to the passwords being the same.
Warning in if (Id.username == Id.password) { :
the condition has length > 1 and only the first element will be used
A better (and simpler) solution may be to replace the 6 lines after:
Password <- isolate(input$passwd)
with
if (nrow(login_details[login_details$user == Username &
login_details$pswd == Password,]) >= 1) {
USER$Logged <- TRUE
} | unknown | |
d4097 | train | There is information found here to configure the endpoint for JSNLog. Take a look at the "Configuring JSNLog" Section of this page (http://jsnlog.com/Documentation/HowTo/Angular2Logging and http://jsnlog.com/Documentation/JSNLogJs/AjaxAppender/SetOptions).
But to summarize, just add this line to your app.module.ts before the @NgModule({...
// Set the endpoint for JSNLog.
JL().setOptions({ 'appenders': [JL.createAjaxAppender('example appender').setOptions({'url': [Your Desired Endpoint Address] + '/jsnlog.logger'})] });
@NgModule({
... | unknown | |
d4098 | train | This afflicts only the 32-bit compiler; x86-64 builds are not affected, regardless of optimization settings. However, you see the problem manifest in 32-bit builds whether optimizing for speed (/O2) or size (/O1). As you mentioned, it works as expected in debugging builds with optimization disabled.
Wimmel's suggestion of changing the packing, accurate though it is, does not change the behavior. (The code below assumes the packing is correctly set to 1 for WMatrix.)
I can't reproduce it in VS 2010, but I can in VS 2013 and 2015. I don't have 2012 installed. That's good enough, though, to allow us to analyze the difference between the object code produced by the two compilers.
Here is the code for mul1 from VS 2010 (the "working" code):
(Actually, in many cases, the compiler inlined the code from this function at the call site. But the compiler will still output disassembly files containing the code it generated for the individual functions prior to inlining. That's what we're looking at here, because it is more cluttered. The behavior of the code is entirely equivalent whether it's been inlined or not.)
PUBLIC mul1
_TEXT SEGMENT
_m$ = 8 ; size = 64
_f$ = 72 ; size = 4
mul1 PROC
___$ReturnUdt$ = eax
push esi
push edi
; WMatrix out = m;
mov ecx, 16 ; 00000010H
lea esi, DWORD PTR _m$[esp+4]
mov edi, eax
rep movsd
; for (unsigned int i = 0; i < 4; i++)
; {
; for (unsigned int j = 0; j < 4; j++)
; {
; unsigned int idx = i * 4 + j; // critical code
; *(&out._11 + idx) *= f; // critical code
movss xmm0, DWORD PTR [eax]
cvtps2pd xmm1, xmm0
movss xmm0, DWORD PTR _f$[esp+4]
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax], xmm1
movss xmm1, DWORD PTR [eax+4]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+4], xmm1
movss xmm1, DWORD PTR [eax+8]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+8], xmm1
movss xmm1, DWORD PTR [eax+12]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+12], xmm1
movss xmm2, DWORD PTR [eax+16]
cvtps2pd xmm2, xmm2
cvtps2pd xmm1, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+16], xmm1
movss xmm1, DWORD PTR [eax+20]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+20], xmm1
movss xmm1, DWORD PTR [eax+24]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+24], xmm1
movss xmm1, DWORD PTR [eax+28]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+28], xmm1
movss xmm1, DWORD PTR [eax+32]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+32], xmm1
movss xmm1, DWORD PTR [eax+36]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+36], xmm1
movss xmm2, DWORD PTR [eax+40]
cvtps2pd xmm2, xmm2
cvtps2pd xmm1, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+40], xmm1
movss xmm1, DWORD PTR [eax+44]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+44], xmm1
movss xmm2, DWORD PTR [eax+48]
cvtps2pd xmm1, xmm0
cvtps2pd xmm2, xmm2
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+48], xmm1
movss xmm1, DWORD PTR [eax+52]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+52], xmm1
movss xmm1, DWORD PTR [eax+56]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
cvtps2pd xmm0, xmm0
movss DWORD PTR [eax+56], xmm1
movss xmm1, DWORD PTR [eax+60]
cvtps2pd xmm1, xmm1
mulsd xmm1, xmm0
pop edi
cvtpd2ps xmm0, xmm1
movss DWORD PTR [eax+60], xmm0
pop esi
; return out;
ret 0
mul1 ENDP
Compare that to the code for mul1 generated by VS 2015:
mul1 PROC
_m$ = 8 ; size = 64
; ___$ReturnUdt$ = ecx
; _f$ = xmm2s
; WMatrix out = m;
movups xmm0, XMMWORD PTR _m$[esp-4]
; for (unsigned int i = 0; i < 4; i++)
xor eax, eax
movaps xmm1, xmm2
movups XMMWORD PTR [ecx], xmm0
movups xmm0, XMMWORD PTR _m$[esp+12]
shufps xmm1, xmm1, 0
movups XMMWORD PTR [ecx+16], xmm0
movups xmm0, XMMWORD PTR _m$[esp+28]
movups XMMWORD PTR [ecx+32], xmm0
movups xmm0, XMMWORD PTR _m$[esp+44]
movups XMMWORD PTR [ecx+48], xmm0
npad 4
$LL4@mul1:
; for (unsigned int j = 0; j < 4; j++)
; {
; unsigned int idx = i * 4 + j; // critical code
; *(&out._11 + idx) *= f; // critical code
movups xmm0, XMMWORD PTR [ecx+eax*4]
mulps xmm0, xmm1
movups XMMWORD PTR [ecx+eax*4], xmm0
inc eax
cmp eax, 4
jb SHORT $LL4@mul1
; return out;
mov eax, ecx
ret 0
?mul1@@YA?AUWMatrix@@U1@M@Z ENDP ; mul1
_TEXT ENDS
It is immediately obvious how much shorter the code is. Apparently the optimizer got a lot smarter between VS 2010 and VS 2015. Unfortunately, sometimes the source of the optimizer's "smarts" is the exploitation of bugs in your code.
Looking at the code that matches up with the loops, you can see that VS 2010 is unrolling the loops. All of the computations are done inline so that there are no branches. This is kind of what you'd expect for loops with upper and lower bounds that are known at compile time and, as in this case, reasonably small.
What happened in VS 2015? Well, it didn't unroll anything. There are 5 lines of code, and then a conditional jump JB back to the top of the loop sequence. That alone doesn't tell you much. What does look highly suspicious is that it only loops 4 times (see the cmp eax, 4 statement that sets flags right before doing the jb, effectively continuing the loop as long as the counter is less than 4). Well, that might be okay if it had merged the two loops into one. Let's see what it's doing inside of the loop:
$LL4@mul1:
movups xmm0, XMMWORD PTR [ecx+eax*4] ; load a packed unaligned value into XMM0
mulps xmm0, xmm1 ; do a packed multiplication of XMM0 by XMM1,
; storing the result in XMM0
movups XMMWORD PTR [ecx+eax*4], xmm0 ; store the result of the previous multiplication
; back into the memory location that we
; initially loaded from
inc eax ; one iteration done, increment loop counter
cmp eax, 4 ; see how many loops we've done
jb $LL4@mul1 ; keep looping if < 4 iterations
The code reads a value from memory (an XMM-sized value from the location determined by ecx + eax * 4) into XMM0, multiplies it by a value in XMM1 (which was set outside the loop, based on the f parameter), and then stores the result back into the original memory location.
Compare that to the code for the corresponding loop in mul2:
$LL4@mul2:
lea eax, DWORD PTR [eax+16]
movups xmm0, XMMWORD PTR [eax-24]
mulps xmm0, xmm2
movups XMMWORD PTR [eax-24], xmm0
sub ecx, 1
jne $LL4@mul2
Aside from a different loop control sequence (this sets ECX to 4 outside of the loop, subtracts 1 each time through, and keeps looping as long as ECX != 0), the big difference here is the actual XMM values that it manipulates in memory. Instead of loading from [ecx+eax*4], it loads from [eax-24] (after having previously added 16 to EAX).
What's different about mul2? You had added code to track a separate index in idx2, incrementing it each time through the loop. Now, this alone would not be enough. If you comment out the assignment to the bool variable b, mul1 and mul2 result in identical object code. Clearly without the comparison of idx to idx2, the compiler is able to deduce that idx2 is completely unused, and therefore eliminate it, turning mul2 into mul1. But with that comparison, the compiler apparently becomes unable to eliminate idx2, and its presence ever so slightly changes what optimizations are deemed possible for the function, resulting in the output discrepancy.
Now the question turns to why is this happening. Is it an optimizer bug, as you first suspected? Well, no—and as some of the commenters have mentioned, it should never be your first instinct to blame the compiler/optimizer. Always assume that there are bugs in your code unless you can prove otherwise. That proof would always involve looking at the disassembly, and preferably referencing the relevant portions of the language standard if you really want to be taken seriously.
In this case, Mystical has already nailed the problem. Your code exhibits undefined behavior when it does *(&out._11 + idx). This makes certain assumptions about the layout of the WMatrix struct in memory, which you cannot legally make, even after explicitly setting the packing.
This is why undefined behavior is evil—it results in code that seems to work sometimes, but other times it doesn't. It is very sensitive to compiler flags, especially optimizations, but also target platforms (as we saw at the top of this answer). mul2 only works by accident. Both mul1 and mul2 are wrong. Unfortunately, the bug is in your code. Worse, the compiler didn't issue a warning that might have alerted you to your use of undefined behavior.
A: If we look at the generated code, the problem is fairly clear. Ignoring a few bits and pieces that aren't related to the problem at hand, mul1 produces code like this:
movss xmm1, DWORD PTR _f$[esp-4] ; load xmm1 from _11 of source
; ...
shufps xmm1, xmm1, 0 ; duplicate _11 across floats of xmm1
; ...
for ecx = 0 to 3 {
movups xmm0, XMMWORD PTR [dest+ecx*4] ; load 4 floats from dest
mulps xmm0, xmm1 ; multiply each by _11
movups XMMWORD PTR [dest+ecx*4], xmm0 ; store result back to dest
}
So, instead of multiplying each element of one matrix by the corresponding element of the other matrix, it's multiplying each element of one matrix by _11 of the other matrix.
Although it's impossible to confirm exactly how it happened (without looking through the compiler's source code), this certainly fits with @Mysticial's guess about how the problem arose. | unknown | |
d4099 | train | its stuck in the loop because user cant guess the same num that randnum genertes
"while userguess !=a " it'll never be true | unknown | |
d4100 | train | Not knowing, what you really want to accomplish:
Did you have a look at the drawImage-method of the rendering-context?
Basically, it does the composition (as specified by the globalCompositeOperation-property) for you -- and it allows you to pass in a canvas element as the source.
So could probably do something along the lines of:
var offScreenContext = document.getCSSCanvasContext( "2d", "synthImage", width, height);
var pixelBuffer = offScreenContext.createImageData( tileWidth, tileHeight );
// do your image synthesis and put the updated buffer back into the context:
offScreenContext.putImageData( pixelBuffer, 0, 0, tileOriginX, tileOriginY, tileWidth, tileHeight );
// assuming 'ctx' is the context of the canvas that actually gets drawn on screen
ctx.drawImage(
offScreenContext.canvas, // => the synthesized image
tileOriginX, tileOriginY, tileWidth, tileHeight, // => frame of offScreenContext that get's drawn
originX, originY, tileWidth, tileHeight // => frame of ctx to draw in
);
Assuming that you have an animation you want to loop over, this has the added benefit of only having to generate the frames once into some kind of sprite-map so that in subsequent iterations you'll only ever need to call ctx.drawImage() -- at the expense of an increased memory footprint of course...
A: Why don't you use SVG?
If you have to use canvas, maybe you could implement drawing an image on a canvas yourself?
var red = oldred*(1-alpha)+imagered*alpha
...and so on...
A: getCSSCanvasContext seems to be WebKit only, but you could also create an offscreen canvas like this:
var canvas = document.createElement('canvas')
canvas.setAttribute('width',300);//use whatever you like for width and height
canvas.setAttribute('height',200);
Which you can then draw to and draw onto another canvas with the drawImage method. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.