text
stringlengths
64
81.1k
meta
dict
Q: Translate Object[] into Kotlin I have the following code that I translated into Kotlin: if (intent.action == SMS_RECEIVED) { // retrieves a map of extended data from the intent val dataBundle = intent.extras if (dataBundle != null) { val mypdu = dataBundle.get("mypdu") mypdu.length... (NOT WORKING) } } Specifically, the creationg of the variable mypdu was like so in Java: Object[] mypdu = (Object[]) dataBundle.get("mypdu"); And I cannot translate it into Kotlin. I cannot use the following: val mypdu = dataBundle.get("mypdu") as (Object[]) And it seems like the IDE wants me to define the variable as Any, and then I cannot access its length property like I want to. How can I translate this line into Kotlin? A: You can use this: val mypdu = dataBundle.get("mypdu") as Array<Any?> Note that I marked the elements of the Array as Any? because in Java we have no null safe compiler. That way you don't run into nasty NPEs later on. Also to access the length of an array, use the size property, like so: val length = mypdu.size
{ "pile_set_name": "StackExchange" }
Q: Creating a UITableView using 2 different objects I am stuck right now with how to create my UITableView. Right now it works fine with 1 object providing the data for it's rows and cells. The problem is, I have a 2nd object that I also want to use in the table view. Normally, this is very easy and I just create 2 sections in the UITableView and use one object for the first section, and use the second object for the second section. But for this UITableView, I only want to use 1 section. And I need to programatically populate the row's and cell's with text from BOTH of the objects. I have no idea how to do this though when only using 1 section. Here are all of my method implementations that help create my UITableView: - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1 ; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.messages count]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return @"Inbox Messages"; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"SettingsCell"; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier]; PFObject *message = [self.messages objectAtIndex:indexPath.row]; UIImage *selectMessageButtonImage = [UIImage imageNamed:@"SliderThumb-Normal-G"]; UIImage *selectMessageButtonImageHighlighted = [UIImage imageNamed:@"SliderThumb-Normal"]; UIButton *openMessageButton = [[UIButton alloc]init]; openMessageButton.frame = CGRectMake(237, -10, 64, 64); [openMessageButton setImage:selectMessageButtonImage forState:UIControlStateNormal]; [openMessageButton setImage:selectMessageButtonImageHighlighted forState:UIControlStateHighlighted]; [openMessageButton setImage:selectMessageButtonImageHighlighted forState:UIControlStateSelected]; [openMessageButton addTarget:self action:@selector(handleTouchUpInside:) forControlEvents:UIControlEventTouchUpInside]; openMessageButton.tag = indexPath.row; [cell.textLabel setText:[message objectForKey:@"senderName"]]; NSString *fileType = [message objectForKey:@"fileType"]; if([fileType isEqualToString:@"image"]) { cell.imageView.image = [UIImage imageNamed:@"icon_image"]; } else { //no image } [cell.detailTextLabel setText:@""]; [cell.contentView addSubview:openMessageButton]; return cell; } The object that I am currently using with this UITableView is called message. I want to create a 2nd object called message2 and place it's data in the UITableView as well. I realize that for the numberOfRowsInSection method implementation I could just return the added count's of both objects, but I don't know how to work the 2nd object into the rest of the code. A: Why not create one NSArray combining both of the msg arrays? If you are populating your second msg array from somewhere, just wait until that loading is done and then do: NSArray *bothArray = [msg1 arrayByAddingObjectsFromArray:msg2]; You can use bothArray as the datasource for the TableView, when you have only one populated msg array, bothArray will be just the elements from msg1, when you have populated msg2, just use the code above and then call: [self.tableView reloadData];
{ "pile_set_name": "StackExchange" }
Q: How to change the default delimiter in PostgreSQL 9.1.9 using SET? From within a bash script I tried to use a replace and a detection on a field containing a pipe like: IF position ('|' in var) IS NOT NULL THEN ... ...REPLACE(field, '|', '#') The data itself was loaded into the DB using the COPY statement e.g. COPY records FROM '$datasource' WITH DELIMITER AS ',' CSV HEADER NULL as ''; I am using psql (9.1.9) and the default field separator is pipe: #> \f #> Field separator is "|". Ideally I would like to SET the default limiter in a CREATE OR REPLACE function at runtime like: ... END; \$\$ LANGUAGE plpgsql SET config_param TO '#'; OR as a seperate statement just like SET config_param TO '#'; I searched the documentation and internet for the right name of the config parameter without luck. Any help appreciated. A: This: `IF position ('|' in var) IS NOT NULL` is assuming that the result of position('|' in 'nopipes') is NULL. It is not, it's zero. position returns null only on null input. regress=> select position('|' in 'abc|def|ghi'); position ---------- 4 (1 row) regress=> select position('|' in 'abcdefghi'); position ---------- 0 (1 row) regress=> select position('|' in null); position ---------- (1 row) ... so if you instead wrote: IF position ('|' in var) <> 0 it should work fine. The field separator \f in psql is irrelevant to this. It's only used to control how psql displays result sets. The server and functions on the server cannot see or be affected by this value. \f is just shorthand for \pset fieldsep, it's a psql-local control to choose the field separator for unaligned output: regress=> \pset format unaligned Output format is unaligned. regress=> SELECT 1,2,3; ?column?|?column?|?column? 1|2|3 (1 row) regress=> \pset fieldsep # Field separator is "#". regress=> SELECT 1,2,3; ?column?#?column?#?column? 1#2#3 (1 row)
{ "pile_set_name": "StackExchange" }
Q: How to deploy my Spring Boot project on Jenkins? I am trying to create a deploy job in Jenkins for my Spring Boot - Maven project. These are the steps i have followed until now: Click New Item Give a name, and choose Maven project Configuration page opens In Source Code Management, i have given my Git repository URL In Build section under Goals and options i have written "spring-boot:run" Saved and applied Now when i click "Build Now", it checks out the project, builds and deploys. But the job does not end. This is the last line in the console output screen: : Started Application in 4.737 seconds (JVM running for 16.297) What is my problem? I need a simple step by step guidance since i do not have any Jenkins experience. EDIT: I do not know what post build action is which is mentioned in the other post. I need a simple step by step guidance since i do not have any Jenkins experience. A: The job doesn't end because your application is up and running on embeeded Tomcat. It's normal behaviour and you should be able to use your application at this point. If you want to make another build, you should stop current build before starting a new one. To do this automaticaly (e.g. when your master branch is changed) you can create another one job. Example of a job that triggers build of a main job: Create a 'Freestyle project' in Jenkins; Fill 'Source Code Management': your Repository URL and Credentials, Branches to build - */master; Fill 'Build Triggers': select 'Poll SCM' and type H/2 * * * * in 'Shedule' to poll repository every 2 minutes; Fill 'Build': add build step 'Execute shell' and type next commands to stop current build and start a new one (don't forget to replace JENKINS_URL and JOB_NAME with your values) - curl -X POST http://JENKINS_URL/job/JOB_NAME/lastBuild/stop; curl -X POST http://JENKINS_URL/job/JOB_NAME/build; Save your job :)
{ "pile_set_name": "StackExchange" }
Q: iOS: How to draw a circle step by step with NSTimer I'd like to draw a circle without filling (only border of the circle) step by step (like animated timer). 1 spin is equal 1 day (24 hours). I really don't know what to do. Steps I've made 1) I've tried https://github.com/danielamitay/DACircularProgress (it's too wide line of progress) 2) I've tried to draw a circle with many arcs. Can you put me some code please. I really confused. Thanks in advance. EDIT I'd like to use NSTimer because I have a button which allow user to stop drawning a circle. If user touch a button again - drawning will have to continue. A: What I would do is to create a path that is a circle and use that with a CAShapeLayer and animate the strokeEnd similar to what I did in this answer. It would look something like this (but I didn't run this code so there may be typos and other mistakes): UIBezierPath *circle = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:0 endAngle:2.0*M_PI clockwise:YES]; CAShapeLayer *circleLayer = [CAShapeLayer layer]; circleLayer.bounds = CGRectMake(0, 0, 2.0*radius, 2.0*radius); circleLayer.path = circle.CGPath; circleLayer.strokeColor = [UIColor orangeColor].CGColor; circleLayer.lineWidth = 3.0; // your line width CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; drawAnimation.duration = 10.0; // your duration // Animate from no part of the stroke being drawn to the entire stroke being drawn drawAnimation.fromValue = @0; drawAnimation.toValue = @1; Just note that both the path and the shape layer has a position so the circle path should be defined relative to the origin of the shape layers frame. It might be clearer to define the shape layer first and then create an oval inside of its bounds: CAShapeLayer *circleLayer = [CAShapeLayer layer]; circleLayer.bounds = CGRectMake(0, 0, 2.0*radius, 2.0*radius); circleLayer.position = center; // Set center of the circle // Create a circle inside of the shape layers bounds UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:circleLayer.bounds]; circleLayer.path = circle.CGPath; // Same appearance configuration as before circleLayer.strokeColor = [UIColor orangeColor].CGColor; circleLayer.lineWidth = 3.0; // your line width
{ "pile_set_name": "StackExchange" }
Q: mongodb using less performant index I am using mongodb 2.6, and I have the following query: db.getCollection('Jobs').find( { $and: [ { RunID: { $regex: ".*_0" } }, { $or: [ { JobType: "TypeX" }, { JobType: "TypeY" }, { JobType: "TypeZ" }, { $and: [ { Info: { $regex: "Weekly.*" } }, { JobType: "YetAnotherType" } ] } ] } ] }) I have three different indexes: RunID, RunID + JobType, RunID + JobType + Info. Mongo is always using the index containing RunID only, although the other indexes seem more likely to produce faster results, it is even sometimes using an index consisting of RunID + StartTime while StartTime is not even in the list of used fields, any idea why is it choosing that index? A: Note1: You can drop your first 2 indexes, RunID and RunID + JobType. It is enough to use just the expanded compound index RunID + JobType + Info; this can be also used to query on RunID or RunID + JobType fields, info here: In addition to supporting queries that match on all the index fields, compound indexes can support queries that match on the prefix of the index fields. When you drop those indexes, mongo will choose the only remained index. Note2: You can always use hint, to tell mongo to use a specific index: db.getCollection('Jobs').find().hint({RunID:1, JobType:1, Info:1})
{ "pile_set_name": "StackExchange" }
Q: How to create a column in SQL Server to hold different types of value I have a Table which needs to store data from dynamic fields of a form. During the usage, the final user should say the type of data he will input (text, numeric, datetime, etc) and input the value. The UI is ready and when they decided the type, the input changes to the right format. Now, I want to know how can I store it into database. Should I have one column for each type and store the value only in the right column? Or can I have a column with a type like TEXT, store there and convert when read it back. ps: I will have another column to hold the type of the value stored, like a enumerator value. PPS: I'm using C# to read the data and to write it to SQL Server. Thanks A: I think best way is to serialize value and store it as text. Then u can make calculated property in your EF entity to deserialize it from text to correct type internal class Program { private static void Main(string[] args) { var myEntity = new MyEntity(); var someDateTime = DateTime.Now; myEntity.DynamicDataValue = someDateTime; var someDateTime2 = (DateTime) myEntity.DynamicDataValue; Console.WriteLine(someDateTime2.AddHours(1)); } public class MyEntity { public string DynamicData { get; set; } public string DynamicDataType { get; set; } [NotMapped] public object DynamicDataValue { get => JsonConvert.DeserializeObject(DynamicData, Type.GetType(DynamicDataType)); set { DynamicData = JsonConvert.SerializeObject(value); DynamicDataType = value.GetType().FullName; } } } }
{ "pile_set_name": "StackExchange" }
Q: How to enable Button control when TextBox control has some value? I do not understand why this is not working. The code is supposed to enable the Button1 if the textbox1 and textbox2 both contains some text but it does not work. Nothing happen after I type some text in both textboxes. The Button1 stays disabled. I even tried both operators || and &&. Here is my code: protected void Page_Load(object sender, EventArgs e) { } protected void TextBox1_TextChanged(object sender, EventArgs e) { if (TextBox1.Text == string.Empty || TextBox2.Text == string.Empty) { Button1.Enabled = false; } else { Button1.Enabled = true; } } protected void TextBox2_TextChanged(object sender, EventArgs e) { if (TextBox1.Text == string.Empty || TextBox2.Text== string.Empty) { Button1.Enabled = false; } else { Button1.Enabled = true; } } The above code is supposed to enable the Button1 if the textbox1 and textbox both contains some text but it does not work. A: Make sure you set AutoPostBack="true" to both TextBox1 and TextBox2: <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" OnTextChanged="TextBox1_TextChanged" /> <asp:TextBox ID="TextBox2" runat="server" AutoPostBack="true" OnTextChanged="TextBox2_TextChanged" />
{ "pile_set_name": "StackExchange" }
Q: Making a lookup readonly? I tried to make a lookup read only from page layout and tried it from profile. But I am not able to make it read only on my standard page. Is it possible to make a lookup read only. Because we have lookup from pick up a record and relate it with. So is it possible, then why is the business logic behind this. A: Please find solution at below link : https://developer.salesforce.com/forums/ForumsMain?id=906F00000008rSEIAY if you want to make this field readonly from all the interface for any or all the profiles then you need to go to field level security. Setup -> Security Controls-> Field Accessibility -> now select the object which contains this field. Then click on View by Fields. Now select your field from the drop down. Next to the profile for which you want this field to be read only click on editable or hidden. From the next page under Field level security select 'Read only'.
{ "pile_set_name": "StackExchange" }
Q: Optimize queries with list of image thumbnails I have a list of entries with a thumbnail (Image Asset) added to the entry. Within my entries loop I check if there's any image (thumbnail) added for the entry. {% set thumbnail = entry.thumbnail.first() %} Since each check requires one new query the queries keep adding up if the list has for example 100 entries. That's 100 queries just for displaying one thumbnail next to my entry. Is there a better way of doing this? Could I for example get the URL to the image asset some other way then running a query on the AssetModel? A: I think that's how it works and there's no way around this. That asset is related to your entry and to get the asset's URL property, Craft has to do a query to the database. That means: each page with lots of thumbnails should be cached. :(
{ "pile_set_name": "StackExchange" }
Q: Drive space hungry NoSQL's databases I've tested NoSQL databases like CouchDB, MongoDB and Cassandra and observed tendence to absorbing very large amount of drive space relative to inserted key-value pairs. When comparing CouchDB and MySQL schemaless databases CouchDB is consuming much more drive space than MySQL. I know about that key-value DBs by default are versioning and have long uuid and need key optimalisation - the comparison was between about 15 mln rows in MySQL and 1-5 mln documents listed NoSQL DB's. My question is : Is there any NoSQL with good compaction / compression of data? So that I can have NoSQL database with a size closer to 5GB than 50GB? A: Disk space is about the cheapest resource today, so if you can trade it for less seeks or less CPU used it is a good trade to make. That is what Cassandra does. A: MongoDB has a "database repair" function that also performs a compaction. However, such a compaction is not going to happen while the DB is running. But if DB space is a serious issue, then try setting up a MongoDB master/slave pair. As the data needs compaction, run the repair on the slave, allow it to "catch up" and then switch them over. You can now safely compact the master instead. But I have to echo jbellis's comment: you will probably need more space and most of these products are making the assumption that disk space is (relatively) cheap. If disk space is really tight, then you'll find that MongoDB is reasonably sized, but it's going to have a difficult time competing with tabular CSV data. Think of it this way, what's more space efficient? a CSV file with a million lines that same data formatted in JSON Obviously the JSON is going to be longer b/c you're repeating the field names every time. The only exception here is a CSV file with like 100 columns of which only a few are filled for each row. (but that's probably not your data)
{ "pile_set_name": "StackExchange" }
Q: How to handle a manager who thinks I will leave the company I work in a team of 8 persons. I'm happy with my job and I'm not looking for a new position at the moment. However, my manager thinks that I will resign in the near future and this is becoming a big problem. The background: Two weeks ago, my manager asked me for a personal talk (which is quite unusual). He asked me if I had any problems lately and if there is anything that I do not like about the company at the moment. He was quite insistent but when I asked about that he became evasive. As far as I know, I was the only person who had such a talk. Similar talks continued over the following days, and my manager suddenly became very interested in what I'm doing, asking me if I wanted other projects, other team members... He then instructed me to instruct some of my colleagues so they could replace me "if you should be ill or something". When I told him that everything is fine, he behaved as if he didn't believe me and went away sighing. Last week, a coworker told me confidentially that my manager thinks I will leave the company soon and that he (manager) is asking my colleagues if they have information about that. I have no idea why my manager would think I'll leave. Given his behavior (and my very good performance reviews) I don't think that he will get rid of me in any way. The whole thing is becoming a problem for me because A big project is coming up and it was planned that I be the project lead. If my manager thinks I'm leaving, he will select someone else. My company in general and my manager as well have pretty strong feelings about people who leave. You get the most boring jobs available. Any benefit that is not in your contract is revoked (e.g. access to company parking space). Getting payed days off becomes almost impossible. In general, people on notice are treated badly. (I work in Germany, my notice period would be four weeks and the employer cannot just fire you after you resign.) Even if I did not resign I'm afraid that this will happen to me. My question: How can I approach my manager, given that I officially do not know that he thinks I'm quitting? Is there anything I can do to show him that I'm happy at my current position? A: There is a risk that he's hinting that you might want to start looking before a "resource action" takes place. He'll never admit it if so. If you don't want to move, I'd try hitting him with : I get the impression that you're unsatisfied with my performance. What can I do to fix that? or What criteria do I need to work on in order to get promoted to the next level? Either says clearly that you're still thinking about a career with the current employer... and hopefully gets him on record as saying you're doing fine so they can't claim they have cause to fire you. A: You state that you are excited about being the lead in the new project. Tell him the exact same thing. In your case I see no drawbacks in being honest: Hi :manager, since your behavior towards me has changed these past few weeks, I get the impression you believe I am looking for a job elsewhere. To be frank, this is not true. As a matter of fact I'm very excited to be given the opportunity as the project lead. I'm very happy to be employed here and it would be a great miss if you would interpret my behavior in the wrong way. As such I hope we can be straightforward with each other.
{ "pile_set_name": "StackExchange" }
Q: Clean and reset table in mvc 4 Web application I am wanting to delete all data from a table and reset the id column to 1. I want to do this in my controller, but i want to know the best way to do that. I have tried the SQLConnection/SQLCommand route, but have been unable to connect to the database successfully to do that. Is there a way like running a db.Clean function or something like that? Updated Here is how far it gets in the code: string connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\\Webs\\MvcFFL\\MvcFFL\\App_Data\\Players.mdf;Integrated Security=True"; string queryString = "Truncate table Players;"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); <- Fails here opening the connection } Then when it hits the connection.Open() here is the error: An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) What can i do instead of this method? A: You have an unescaped \in (LocalDB)\v11.0 You can change it to (LocalDB)\\v11.0, or else change the whole connection string to @"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Webs\MvcFFL\MvcFFL\App_Data\Players.mdf;Integrated Security=True" (notice the @ and the lack of \\)
{ "pile_set_name": "StackExchange" }
Q: Add a unqiue ID by name and date in R I am doing some data cleaning/ formatting, and I would like to add a unique identifier to each record by name and then by date. For example, "Bob" may have four check-in dates, two of which are the same. For a case like this, I want to give him three different (sequential) ID numbers. Here is the closest I have gotten to my desired result: An example data set I created: tst <- data_frame( name = c("Bob", "Sam", "Roger", "Stacy", "Roger", "Roger", "Sam", "Bob", "Sam", "Stacy", "Bob", "Stacy", "Roger", "Bob"), date = as.Date(c("2009-07-03", "2010-08-12", "2009-07-03", "2016-04-01", "2002-01-03", "2019-02-10", "2005-04-17", "2009-07-03", "2010-09-21", "2012-11-12", "2015-12-31", "2014-10-10", "2015-06-02", "2003-08-21")), amount = round(runif(14, 0, 100), 2) ) Generating a check_in_number variable... tst2 <- tst %>% arrange(date) %>% group_by(name, date) %>% mutate(check_in_number = row_number()) The line above will generate check_in_number for Bob as 1, 1, 2, 1 in that order. I would instead like the output to be 1, 2, 2, 3. In other words. I would like check-in instances on the same date to be considered a single check-in. Is this possible with tidyverse? Am I overlooking a simple method for this? There is a similar question here, but I am leaving this up because the problem I had involved an ordered date variable on which I was arranging the data. In other words, my data required my new variable to be consecutive. How to number/label data-table by group-number from group_by? A: You need group_indices: library(tidyverse) tst <- tibble( name = c("Bob", "Sam", "Roger", "Stacy", "Roger", "Roger", "Sam", "Bob", "Sam", "Stacy", "Bob", "Stacy", "Roger", "Bob"), date = as.Date(c("2009-07-03", "2010-08-12", "2009-07-03", "2016-04-01", "2002-01-03", "2019-02-10", "2005-04-17", "2009-07-03", "2010-09-21", "2012-11-12", "2015-12-31", "2014-10-10", "2015-06-02", "2003-08-21")), amount = round(runif(14, 0, 100), 2) ) tst %>% arrange(name, date) %>% mutate(check_in_number = group_indices(., name, date)) #> # A tibble: 14 x 4 #> name date amount check_in_number #> <chr> <date> <dbl> <int> #> 1 Bob 2003-08-21 91.1 1 #> 2 Bob 2009-07-03 38.1 2 #> 3 Bob 2009-07-03 28.3 2 #> 4 Bob 2015-12-31 22.3 3 #> 5 Roger 2002-01-03 68.3 4 #> 6 Roger 2009-07-03 83.8 5 #> 7 Roger 2015-06-02 94.2 6 #> 8 Roger 2019-02-10 48.8 7 #> 9 Sam 2005-04-17 16.6 8 #> 10 Sam 2010-08-12 93.2 9 #> 11 Sam 2010-09-21 65.5 10 #> 12 Stacy 2012-11-12 92.6 11 #> 13 Stacy 2014-10-10 84.4 12 #> 14 Stacy 2016-04-01 7.43 13 If you need the numbering to restart on each name, you can rescale based on the first value in each name: tst %>% arrange(name, date) %>% mutate(check_in_number = group_indices(., name, date)) %>% group_by(name) %>% mutate(check_in_number = check_in_number - first(check_in_number) + 1) #> # A tibble: 14 x 4 #> # Groups: name [4] #> name date amount check_in_number #> <chr> <date> <dbl> <dbl> #> 1 Bob 2003-08-21 91.1 1 #> 2 Bob 2009-07-03 38.1 2 #> 3 Bob 2009-07-03 28.3 2 #> 4 Bob 2015-12-31 22.3 3 #> 5 Roger 2002-01-03 68.3 1 #> 6 Roger 2009-07-03 83.8 2 #> 7 Roger 2015-06-02 94.2 3 #> 8 Roger 2019-02-10 48.8 4 #> 9 Sam 2005-04-17 16.6 1 #> 10 Sam 2010-08-12 93.2 2 #> 11 Sam 2010-09-21 65.5 3 #> 12 Stacy 2012-11-12 92.6 1 #> 13 Stacy 2014-10-10 84.4 2 #> 14 Stacy 2016-04-01 7.43 3 Created on 2019-06-18 by the reprex package (v0.3.0)
{ "pile_set_name": "StackExchange" }
Q: PHP's dom->createTextNode escapes some characthers I am using dom->createTextNode() in PHP. I see that it automatically escapes characters e.g /"" etc. According to the PHP's manual this is a standard behavior. Is it possible that it doesn't escape any characters? Thanks. A: If some characters are not escaped, you might not get a valid XML file, in the end. If you don't want any character to be escaped, maybe using DOMDocument::createCDATASection, to get CDATA sections in your XML file, could help. Though, note that you will get that kind of things (well, CDATA sections) in your XML : <tag><![CDATA[<greeting>Hello, world!</greeting>]]></tag>
{ "pile_set_name": "StackExchange" }
Q: How to query the Entity Framework in a WCF Data Services OData Service from within the ServiceAuthorizationManager My FooData.svc.cs file looks like this: (Take note of the undeclared object CurrentDataSource.) public class FooData : DataService<FooEntities> { public static void InitializeService(DataServiceConfiguration config) { // init code } [WebGet] public IQueryable<someStoredProcedure_Result> someStoredProcedure(int param1, int param2) { return CurrentDataSource.someStoredProcedure(param1, param2).AsQueryable(); } } My Authorizer.cs file looks like this: public class Authorizer : System.ServiceModel.ServiceAuthorizationManager { protected override bool CheckAccessCore(OperationContext operationContext) { if (base.CheckAccessCore(operationContext)) { if (IsAuthorized()) return true; else return false; } else return false; } private bool IsAuthorized(OperationContext operationContext) { // some code here that gets the authentication headers, // etc from the operationContext // ********* // now, how do I properly access the Entity Framework to connect // to the db and check the credentials since I don't have access // to CurrentDataSource here } } Applicable section from Web.config, for good measure: <system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <serviceAuthorization serviceAuthorizationManagerType="MyNamespace.Authorizer, MyAssemblyName" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> So my question has to do with where you see all the asterisks in the code in Authorizer.cs. What is the recommended way to connect to the Entity Framework from within the ServiceAuthorizationManager since I don't have access to CurrentDataSource there? Do I just establish a separate "connection"? e.g. using (var db = new MyNamespace.MyEntityFrameworkDBContext()) { // linq query, stored proc, etc using the db object } To clarify, the above code works just fine. I'm just wondering if it's the correct way. By the way, this is a Visual Studio 2012 WCF Data Services project with .NET 4.5 and Entity Framework 5. A: I think you answered your own question. If you are concerned with the creation of DbContext for each IsAuthorized - then unless you are calling this functions hundreds of times during 1 request you should be fine. As mentioned here,here or here recreation of EF context is not only inexpensive operation but also recommended. EDIT: Please note that DataService constructor is called after IsAuthorized, therefore independent instance of DbContext is the most likely the way to go.
{ "pile_set_name": "StackExchange" }
Q: Jquery two api calls to retrieve different dynamic elements inside two nested $.each loops I have one api link that contains the top elements. From each element, I need to build the end of a second api call which will give me the rest of the elements I need and pull them out. Let say the first json is (urlphonebrands) that contains 3 phone brands (Apple, Samsung & Nokia). The second json call depends on each brand name, like urlphonebrands/Nokia, or urlphonebrands/Samsung or urlphonebrands/Apple built automatically. I need to loop through each brand name to get properties such as colors, battery life and size. But each color has another loop of choices, as for example, black, white, red. My end result will be, Apple battery life: 6h color: blue black Samsung: battery life: 6h color: blue black Nokia: battery life: 3h color: blue While I am able to loop through each top element successfully I can only retrieve the last color element of the first item, which indicates that I built the second loop incorrectly. Went a few hours through it and figured I could use some help. This is what I have, $.getJSON("urlphonebrands", function(data){ var brandBlock = data[0]['name']; $.each(data, function(index, brandBlock){ var brand = brandBlock.name; $('#table').append('<tr><td>' + brand + '</td></tr>'); //It works fine until this point $.getJSON("phonebrandsurl" + brand, function(data){ $.each(brand, function (index2, brand){ var color = data[0].name[0].color; $('#table').append('<tr><td>' + color + '</td></tr>'); }); }); }); }); Which gives me something like, Apple blue blue Samsung blue blue Nokia blue This is the console.log output after the second api call, [Object] 0: Object brand: Array[17] 0: Object battery life: "6h" colors: Object color: "blue" A: try wrap second getJSON into anonymous function and pass brand as param:: (function(brand){ $.getJSON('phonebrandsurl' + brand, function(data){ // ... }(brand))
{ "pile_set_name": "StackExchange" }
Q: Should my answer be more succinct or more verbose? I often wonder whether my short, concise answers are more appropriate than answers that are more long-winded and explanatory. Should I answer the question and explain why, or should I simply answer the question? I understand that every question is different, and I often provide very long answers with explanations, even as the short answers are pouring through the flood gates. But as a general rule, when faced with the two options, which is considered more appropriate? There is definitely value in being concise, right? A: As you answer, think to yourself: is there any ambiguity or lack of detail in my answer that could be misunderstood or misinterpreted? You can also guage the level of the OP's knowledge from their question and answer accordingly. You should remember that not only are you answering the question for the current OP, you are potentially providing an answer to many people in the future who will have the same or a related question. While the FGITW answers may pick up some immediate upvotes, a well thought out answer will continue to generate upvotes into the future. A good person to use is an example is Jon Skeet - he gives the answer and invariably he will provide a bit of detail as well. So he picks up rep (not that it matters to him) both for his technical knowledge and his answer style - people understand why the answer is the answer. A: Make it as long as necessary, but no longer. I'm not sure there's a single right answer to this; it really depends on the question itself. Some questions require nothing more than a code snippet to be well-answered. Others need something along the lines of a mini-essay. That said, I always favor answers with more detail when voting. If there are two answers which both present the same solution to a problem (1 2), but one answerer has taken the trouble to provide background, explanation, and context, I will upvote that one in preference to the other. As long as the answer is well-written, more information should equate to more value for future readers. So personally, even in a case where a single link might constitute a useful answer,* I try to include some background info, even if it's a bit trivial. Links to relevant documentation pretty much always add usefulness to an answer. *Although see "Are answers that just contain links really 'Good answers'?"
{ "pile_set_name": "StackExchange" }
Q: Spotting the matrix representation of the quantum AND operation https://people.maths.bris.ac.uk/~csxam/teaching/qc2020/lecturenotes.pdf Applying the above construction to AND we get the map $(x1,x2,y) \rightarrow (x1,x2,y⊕(x1∧x2))$ for $x1,x2,y \in \{0,1\}$. The unitaryoperator which implements this is then simply the map $|x1〉|x2〉|y> \rightarrow |x1〉|x2〉|y \oplus (x1∧x2)〉$. Written as a matrix with respect to the computational basis this is $$\begin{bmatrix} 1&0&0&0&0&0&0&0\\0&1&0&0&0&0&0&0\\0&0&1&0&0&0&0&0\\0&0&0&1&0&0&0&0\\0&0&0&0&1&0&0&0\\0&0&0&0&0&1&0&0\\0&0&0&0&0&0&0&1\\0&0&0&0&0&0&1&0 \end{bmatrix}$$ How can you just spot what the matrix is with respect to the computational basis? A: Each column of a quantum gate can be interpreted as the result from feeding in one of the standard 0-1 configurations of your system of qubits. For example, the configuration corresponding to the $5$th column is $|101\rangle$ (since $5$ is $101$ in binary), so that $x_1 = 1$, $x_2 = 0$, $y = 1$. With that, we see that the corresponding output should be $$ |x_1 \rangle |x_2 \rangle |y \oplus (x_1 \land x_2) \rangle = |1 \rangle |0 \rangle |1 \oplus (1 \land 0) \rangle = |101\rangle. $$ This is represented by the vector with a $1$ in the $5$th spot and $0$s elsewhere. Repeat this for the remaining columns. In other words, finding the matrix associated with the gate is as easy as filling out a truth table. In this case, we could save a bit of time if we notice that the input remains unchanged except in the case where $x_1 = x_2 = 1$, which tells us that we must have a leading identitity matrix up until the bottom right $2 \times 2$ corner.
{ "pile_set_name": "StackExchange" }
Q: Hoax LIMIT value Is there a value that used with a LIMIT clause means nothing or no limit? I'd expected that 0 would be that value but it obviously isn't: SELECT * FROM items LIMIT 0 -- returns 0 rows A: Use a value far outside the number of records you're actually retrieving: LIMIT 0, 18446744073709551615 Quote: To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter.
{ "pile_set_name": "StackExchange" }
Q: Using a semaphore I would like to know how can i make those thread work one after the other, and how to make the first one always run after the second one. I created a semaphore, but i not sure about how to use it. public class A extends Thread { private int i; public A(int x) { i = x; }@ Override public void run() { System.out.println(i); } } /** IN MAIN **/ A c1 = new A(5); A c2 = new A(6); Semaphore s = new Semaphore(1, true); c1.start(); c2.start(); new Thread(new Runnable() { public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(100); } catch (InterruptedException e) {} System.out.println("+"); } } }).start(); new Thread(new Runnable() { public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(70); } catch (InterruptedException e) {} System.out.println("*"); } } }).start(); A: I would like to know how can i make those threads work one after the other, and how to make the first one always run after the second one. I created a semaphore, but i not sure about how to use it. You could use join() in your case if you want thread to finish before calling thread c2. Like so (the threads are called in thread of main): c1.start(); // Start thread `c1` first c1.join(); // `main` now waits for `c1` to finish c2.start(); // Start thread `c2` next c2.join(); // `main` now waits for `c2` to finish That should answer your question. I little bit about semaphores. In general you cannot use a semaphore to control the order of execution of threads. A semaphore is a lock for a one or more resources. The threads that want to access the resources are competing with each other, you cannot control to whom the semaphore will grant access next. I am aware of the "trick" in the other answer. I did not test it and it might work, but I don't think that is the right way to do it. Here is an example that works without a sempahore: import java.util.concurrent.Semaphore; class A extends Thread { private int i; public A(int x) { i = x; } public void run() { System.out.println(i); } public static void main(String[] args) throws Exception { A thread1 = new A(5); A thread2 = new A(6); thread1.start(); thread1.join(); thread2.start(); thread2.join(); } } If you want to use a semaphore (although I don't see why) then the example could look like this: import java.util.concurrent.Semaphore; class A extends Thread { private int i; final static Semaphore semaphore = new Semaphore(1, true); public A(int x) { i = x; } public void run() { try { /*thread stops here until it gets permit to go on*/ semaphore.acquire(); System.out.println(i); /*exception must be caught or thrown*/ } catch (InterruptedException e) { } //CRITICAL SECTION semaphore.release(); } public static void main(String[] args) throws Exception { A thread1 = new A(5); A thread2 = new A(6); thread1.start(); thread1.join(); thread2.start(); thread2.join(); } }
{ "pile_set_name": "StackExchange" }
Q: Which axiom makes a vector space flat? First of all, I'm not sure if this question even makes sense, i.e. is there a notion of curvature on a vector space structure. However, when dealing with vector spaces (here I am mostly thinking of tangent spaces on a manifold), we treat (and draw) them as flat. On the other hand, I don't see the flatness assumption (nor any kind of parallelism) in the vector space axioms. So, my question is, are and what makes vector spaces flat? What is the difference between the arrows in flat space and e.g. directed arcs of great circles on a 2-sphere? Don't they both satisfy the same axioms? A: I think it's not about curvature, there is something more fundamental that distinguishes $\mathbb{R}^n$ from any other manifold. For any $p\in\mathbb{R}^n$ there is a canonical isomorphism $T_p\mathbb{R}^n\to\mathbb{R}^n$. Any tangent vector $v\in T_p\mathbb{R}^n$ is represented by some path $\alpha$ with $\alpha(0)=p$. The isomorphism is given by $v\mapsto\dot{\alpha}(0)\in\mathbb{R}^n$. This isomorphism yields a canonical isomorphism between the tangent spaces at two distinct points, and this is something that does not exist on any other manifold. The concept of parallel transport is thus very simple on $\mathbb{R}^n$. Actually, a vector field on $\mathbb{R}^n$ can be constant, where the definition of constant is very clear. Intuitively speaking, curvature of a Riemannian manifold $M$ measures how much two vector fields don't commute. But in Euclidean space, having noticed that any tangent vector can be extended canonically to a constant vector field, the fact that every two tangent vectors commute is just the theorem of changing the order of differentiation: $$\frac{\partial^2}{\partial x\partial y}=\frac{\partial^2 f}{\partial y \partial x}.$$ Since every two tangent vectors (or vector fields) commute, the curvature is $0$.
{ "pile_set_name": "StackExchange" }
Q: Could a single impulse be classified as a sound wave? If not, how many counts(cycles) of impulses are needed before we can call it as sound(without 20-20000Hz limit)? A: Although sound is something we originally defined as a wave that could be sensed by some biological mechanism in some organisms, it has found a more specific meaning in physics as a wave that propagates energy through some type of media by compressing and rarifying the density of that media as it propagates. So sound then is most often thought about as a traveling, longitudinal compression wave that behaves in a cyclic manner. But the definition does not need to restrict itself to cyclic waves. And so a specific frequency range cannot really be used to define what is and what is not a sound wave. Short event disturbances in a medium can also propagate a solitary wave or soliton that can be detected by instrumentation or heard by organisms, if the mechanisms are capable of absorbing the energy of the soliton wave and generating a signal to the instrument or stimulating the brain of the organism. But unlike a cyclic sound wave, the instrument or brain cannot count or 'integrate' over a number of wave cycles to discern the presence of any frequency content. And in this case the solitary wave is rather sensed as an impulse - which the organism may refer to as a 'click' or 'pop'.
{ "pile_set_name": "StackExchange" }
Q: Proper Coding: When returning a new instance of a class Let's say I have a class called MyClass, which has two member variables (both being int) called firstNumber_ and secondNumber_. This class also has a method called clone( ) which creates a new instance of the object with the same values and returns that new instance. The question is, when returning a new instance of the class, do I return it as a pointer, a reference, or just the instance itself? // MyClass.h class MyClass { private: int firstNumber_; int secondNumber_; public: MyClass( int numA, int numB ) { firstNumber_ = numA; secondNumber_ = numB; } ~MyClass( ) { }; // This method creates a copy of the object and returns that object. // The ( ? ) is there because I am not sure what type the returned value is. MyClass ( ? ) clone( ) { // Do I just return the new instance? Or do I need to return a reference or a pointer of the new instance? return MyClass( firstNumber_, secondNumber_ ); } }; What's the proper way of achieving this? Note that MyClass does not inherit from any other classes. Thanks in advance. A: The method clone() is usually for returning a pointer to an instance of a polymorphic type, so you can call it on a pointer of the base type and get an pointer to an instance of the right derived type. For simple copying, in C++ you use the copy constructor, not a clone method. Clone method: struct Base{}; struct Foo : Base { Base* clone() const { return new Foo(*this); } }: Base * b1 = new Foo; ... Base * b2 = b1->clone(); // points to a Foo instance, copy of object pointed at by b1 Where the clone method us using the (compiler generated) copy constructor. Using copy constructor: Foo f1; Foo f2 = f1; // copy assignment In real code you should prefer smart pointers over the raw ones used in these examples. Concerning the return value, by default you should return by value, although in the polymorphic clone() example this would defeat the purpose by slicing the return object into a Base. So we return a pointer to an instance allocated dynamically. The intent and ownership has to be clear: in this case, the caller owns the pointer, and is responsible for deallocating it. Pre-c++11 you would have to rely on documentation to convey this. In C++11 you can use the smart pointer std::unique_ptr, which enforces the ownership and states it clearly.
{ "pile_set_name": "StackExchange" }
Q: Javascript/ajax/node.js/other framework CORS request using jsfiddle I am trying to use JQuery ajax call from fiddle to load a resource from this page My code is here: $('button').on('click', function() { $('#message').text(''); $.ajax({ url: "http://pool.burstcoin.ro/pending2.json", type: "GET", crossDomain: true, dataType: "json", success: function(response) { console.log(response); $('#message').text(response.message); }, error: function(xhr, status) { alert("error"); } }); }); I have created the fiddle just to see if I can get to any sort of response but I am getting this js error response: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have read some post on this and if I am not mistaken it's not possible to do anything on the front end to add the missing headers. Is it possible to add the right headers in Node.js (or some other javascript framework) to the response? If so, I would really appreciate an updated fiddle that demonstrates that because of my lack of knowledge to do it myself. A: Solved using Yahoo's YQL Fiddle function GetMessages() { $.getJSON("http://query.yahooapis.com/v1/public/yql", { q: "select * from json where url=\"http://pool.burstcoin.ro/pending2.json\"", format: "json" }, function (data) { if (data.query.results) { alert(data.query.results["pendingPaymentList"]["_00079785104091711"]); } else { alert('bad'); } } ); } GetMessages();
{ "pile_set_name": "StackExchange" }
Q: How to read snake case JSON request body in Go using Gin-Gonic I am using gin-gonic to create my first Go rest API server. My User struct is as follows type User struct { FirstName string `json: "first_name"` } I have the following route defined in my code route.POST("/test", func(c *gin.Context) { var user request_parameters.User c.BindJSON(&user) //some code here c.JSON(http.StatusOK, token) }) My POST request body is as follows { "first_name" : "James Bond" } The value of user.FirstName is "" in this case. But when I post my request body as { "firstName" : "James Bond" } The value of user.FirstName is "James Bond". How do I map the snake case variable "first_name" from the JSON request body to the corresponding variable in the struct? Am I missing something? A: You have a typo (a space in json: "first_name"). It should be: type User struct { FirstName string `json:"first_name"` }
{ "pile_set_name": "StackExchange" }
Q: The beauty of chess Many times one can read in chess magazines the world "beautiful". Comments like "that move/combination/execution/problem/solution was beautiful" are our daily bread when we read game analysis. What are the characteristics a move, combination, execution, position or other have to have for it to be considered beautiful? How the concept of aesthetically pleasing can be understood in chess? A: Aesthetics is a philosophical question, and hence the answer you get will depend greatly on the philosophical views of the person. As a scientific realist, I believe that our sense of aesthetic beauty is defined by how our brain processes respond to a sensual stimulus (in this case a chess problem/combination/tactic), which in turn is driven by our evolutionary history. So in this context, what properties make a chess problem "beautiful", and why those specific properties? Take all this with a massive heap of salt, since I'm not an evolutionary psychologist or philosopher of aesthetics: Efficiency: We prefer solutions that do not involve unnecessary moves, or wastage of resources. Intention: We prefer a solution that was intentionally planned to one that simply happened out of chance. This may be because we like to be in control of our actions. Harmony: We like solutions where pieces work together to achieve a goal - this can be related to a desire to use resources effectively, which in turn is also about efficiency. Perfect play: we prefer solutions where the opponent is not required to blunder in order to achieve our goal - this could be due to a desire to be clinical and leave nothing up to chance. Simplification: A sequence of moves that transposes a complex scenario into a simple advantage may relate to our need to take control of a situation.
{ "pile_set_name": "StackExchange" }
Q: What does "$<" & "$>" mean in Perl An example will be highly appreciated. Below is a sample of where I read it: $self->parameter( name => 'real_user', xpath => undef, default => scalar(getpwuid($<)) ); $self->parameter( name => 'production', xpath => '/config/production', default => $self->get('user_uid') == $> ); A: A $ followed by symbol? To perlvar! $< The real uid of this process. $> The effective uid of this process. Use them to find out what user is running the program. A: From perldoc: http://perldoc.perl.org/perlvar.html $< The real uid of this process. You can change both the real uid and the effective uid at the same time by using POSIX::setuid() . Since changes to $< require a system call, check $! after a change attempt to detect any possible errors. Mnemonic: it's the uid you came from, if you're running setuid. $> The effective uid of this process. For example: 1. $< = $>; # set real to effective uid2. ($<,$>) = ($>,$<); # swap real and effective uids You can change both the effective uid and the real uid at the same time by using POSIX::setuid() . Changes to $> require a check to $! to detect any possible errors after an attempted change. $< and $> can be swapped only on machines supporting setreuid() . Mnemonic: it's the uid you went to, if you're running setuid.
{ "pile_set_name": "StackExchange" }
Q: file upload | without page refresh | struts2 | no flash | Problem decription: I want to create a file upload screen using JSP. The screen will allow the user to select multiple files on the screen but there will be only one Upload button for all of them. On click of the upload button all the file objects should be obtained in the Action class. But the important thing is the page should not get refreshed after submitting. There will be other information displayed on the same screen which should not get changed during the file upload is in progress. My Attempts: I used the simple struts2 file upload feature which works fine. But it is refreshing the page on submitting. I used AJAX (JQuery) to resolve this. The problem I am facing with AJAX is that it is not setting the File object into the file property of Action class. Hence I am not able to obtain the file object in the Action class and process further. Can anyone please help me with this. I am attaching the code of whatever I have tried so far. JSP: <s:form action="fileUpload" method="post" enctype="multipart/form-data" > <s:file id="file" name="userImage" cssClass="fileUpload" cssStyle="fileUpload" /> <button id="px-submit">Upload</button> </s:form> <script type="text/javascript"> jQuery(function($){ $('.fileUpload').fileUploader(); }); </script> JQuery Plugin: This is the jquery plugin that I have used. Action Class: public class FileUploadAction extends ActionSupport{ private File userImage; public File getUserImage() { return userImage; } public void setUserImage(File userImage) { this.userImage = userImage; } public String execute() { try { System.out.println("file name: " + userImage.toString()); } catch(Exception e) { e.printStackTrace(); } return SUCCESS; } EDIT: Here is my struts config file. Struts.xml <action name="commonDataImportAction_*" class="xxx.Action"> <result name="SUCCESS" type="stream"> <param name="contentType">text/html</param> <param name="inputName">inputStream</param> </result> I get a nullpointer here as the file object is not getting set. Please help. thanks in advance. Gaurav A: I am using the same plugin and it is working fine for me. The first problem I see in your code is that you have not set the type of your upload button to submit. <button id="px-submit" type="submit">Upload</button> Hopefully, this should solve the null pointer excepton. Also, as mentioned in this plugin's docs, you need to return a json string <div id='message'>success message</div> on successfull upload. So you need to change your struts.xml mapping. Try this and then get back to me if you face any further problems. EDIT: Ok here is my code as you requested JSP <form action="uploadImage" method="post" enctype="multipart/form-data"> <input type="file" name="image" class="fileUpload" multiple/> <button id="px-submit" type="submit">Save all images</button> <button id="px-clear" type="reset">Clear all</button> </form> $('.fileUpload').fileUploader({ autoUpload: false, buttonUpload: '#px-submit', buttonClear: '#px-clear', }); Action class You need to return stream result. I am using a plugin (struts2 jquery plugin) which takes care of it vary nicely, but you dont have to use it only because of this one requirement, instead I am giving you a code to return stream result without using any plugin.(Taken from here) public class UploadImageAction extends ActionSupport{ private File image; private String imageContentType; private String imageFileName; //getter/setter for these public String execute() { String status=""; try{ //save file code here status="<div id='message'>successfully uploaded</div>"; //on success inputStream = new StringBufferInputStream(status); }catch(WhateverException e){ status="<div id='status'>fail</div><div id='message'>Your fail message</div>"; //on error inputStream = new StringBufferInputStream(status); //other code } return SUCCESS; } private InputStream inputStream; public InputStream getInputStream() { return inputStream; } } struts.xml <action name="fileUpload" class="com.xxx.action.UploadImageAction"> <result type="stream"> <param name="contentType">text/html</param> <param name="inputName">inputStream</param> </result> </action>
{ "pile_set_name": "StackExchange" }
Q: Pivot Table MySQL from mysql database I would like to make a pivot table that looks like the figure below from a mysql table: Year | 2018 | 2018 | 2018 | 2019 .... --------------------------------------------------------------- Month | Jan | Feb | Mar | Apr .... ---------------------------------------------------------------- Dolutegravir (DTG) 50mg Tabs| 10000 | 20000| xx | xx .... ----------------------------------------------------------------- xxxxxxxx | xx | xx | xxx | xx ....... ------------------------------------------------------------------- MySql schema and data can be found here http://sqlfiddle.com/#!9/678546/2 Your assistance is appreciated in advance A: Here's a partial example based on this question. The basic format is for each column you want in the end, you need to define another SUM(CASE(x)). This example currently outputs only 4 months, but you can build it out to include whichever months you need. http://sqlfiddle.com/#!9/678546/9 for a working example. SELECT P.`drug`, SUM( CASE WHEN P.`data_month`='Jan' AND P.`data_year` = 2018 THEN P.`dispensed_packs` ELSE 0 END ) AS '2018-01', SUM( CASE WHEN P.`data_month`='Feb' AND P.`data_year` = 2018 THEN P.`dispensed_packs` ELSE 0 END ) AS '2018-02', SUM( CASE WHEN P.`data_month`='Mar' AND P.`data_year` = 2018 THEN P.`dispensed_packs` ELSE 0 END ) AS '2018-03', SUM( CASE WHEN P.`data_month`='Apr' AND P.`data_year` = 2018 THEN P.`dispensed_packs` ELSE 0 END ) AS '2019-01' FROM tmp_pivot_dtg P GROUP BY P.`drug`;
{ "pile_set_name": "StackExchange" }
Q: How to specify a generic type's identifier type (for db queries) along with genric type I was thinking of implementing a per-object Repository (e.g. a Person repository, a State repository etc.) before deciding on a line of business Repository instead BUT I still have a question regarding the passing in of an ID (identifier) type with a generic. In a nutshell, a Person may have a GUID identifier, a State/County may have a int identifier, etc. With this in mind, how can I pass along a type that specifies the ID, er, type of the generic being passed in? Here's my attempt at the interface: public interface IRepository<T, TID> where T : class where TID : Type { T Get(TID id); IList<T> GetAll(); void Update(T entity); void Insert(T entity); void Delete(TID id); } You can see that T is the class (Person, State, etc.) and my intent is to have TID be the type that is used for the identifier, i.e. look at T Get(TID id). This craps out with the compilation error: "The type 'string' cannot be used as type parameter 'TID' in the generic type or method 'DumpWebApp.IRepository'. There is no implicit reference conversion from 'string' to 'System.Type'." Another way of doing it would be to pass the actual element into the Get and Delete methods, I guess, but that seems a bit clunky. Thanks for any suggestions - and incidentally, is returning IList acceptable for GetAll()? Why not IQueryable, or T[] ? Mike K. A: Just drop the where TID : Type constraint. That should do the trick.
{ "pile_set_name": "StackExchange" }
Q: save a modal message in database issue My main idea is to show data from database and beside each row, there is an accept and reject button .onClick, the value of the button gets passed to controller and saved to database.so far so good, the issue is when I tried to add a popup modal that has input text to add a note . it should appear only when I click the reject button only. I opened the developer tools and found it passes the double of the whole number of the data rows and i don't know how to pass the id of the row I'm in, the value of the rejected button and finally the message that is going to be written to the controller. I tried to pass the modal in the reject button method in the controller but it passes as null. what am I doing wrong? is my script part is organized or even accurate after I added the ajax or not? I appreciate any help. my view: @model AllmyTries.Models.fulfillmentVM <!-- page content --> @using (Html.BeginForm("Add_Fulfillment_Reject", "Feedback", FormMethod.Post)) { @Html.AntiForgeryToken() <td> <button id="btnReject" class="btn btn-lg btn-danger" name="button" data-toggle="modal" data-target="#exampleModal" type="submit" onclick="reject(0)" value="0">Reject</button> @Html.Hidden("Request_ID", Model._Requests[i].Request_ID) @Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" }) </td> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">New message</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="myform"> <div class="form-group"> <textarea class="form-control" id="message-text"></textarea> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <input type="reset" value="submit" class="btn btn-success" id="finalSave" /> </div> </div> </div> </div> } <!-- /page content --> @section Scripts { <script> $('[name = "button"]').click(function () { $('[name = "Status"]').val($('[name = "button"]').val()); }) $(document).ready(function () { $('#finalSave').click(function () { var dataform = $('#myform').serialize(); $.ajax({ type: 'POST', url: '/Feedback/Add_Fulfillment_Reject', data: dataform, success: function () { $('#exampleModal').modal('hide'); } }) }) }) </script> } the controller: #region fulfillment [HttpPost] public ActionResult Add_Fulfillment_Accept(int Request_ID, int? Status) { var user = db.TBL_Request.Find(Request_ID); user.Inserted_by = Status ?? 0; db.SaveChanges(); return RedirectToAction("Index"); } //this is the one with the issue [HttpPost] public ActionResult Add_Fulfillment_Reject(fulfillmentVM vM) { //save the status //save the note db.SaveChanges(); return RedirectToAction("Index"); } #endregion } A: Your Javascript submits only the textarea that is in the <form id="myForm"> to a controller action that is expecting a fulfillmentVM object. Change your Html.Hidden fields to Html.HiddenFor. This will bind those values on post. Use a TextAreaFor instead of a textarea for model binding, and make sure your viewmodel has an appropriate property for it. @Html.HiddenFor(m => m._Requests[i].Request_ID) @Html.HiddenFor(m => m._Requests[i].Status, new { id = "myEdit", value = "" }) @Html.TextAreaFor(m => m.RejectMessage, htmlAttributes: new { @class = "form-control" }) Remove the <form id="myForm"> tags, they're unnecessary. Keep the button as a submit button, and it will post to the Add_Fulfillment_Reject controller, passing all the bound values for your fulfillmentVM. Where to put the form Personally, I would put it starting right before the text box, move the hidden fields down there, too. End it right after the submit button. @using (Html.BeginForm("Add_Fulfillment_Reject", "Feedback", FormMethod.Post)) { @Html.HiddenFor(m => m._Requests[i].Request_ID) @Html.HiddenFor(m => m._Requests[i].Status, new { id = "myEdit", value = "" }) @Html.TextAreaFor(m => m.RejectMessage, htmlAttributes: new { @class = "form-control" }) // rest of modal code <input type="submit" class="btn btn-success" id="finalSave" /> } // end form
{ "pile_set_name": "StackExchange" }
Q: More efficient way to get nearest center My data object is an instance of: class data_instance: def __init__(self, data, tlabel): self.data = data # 1xd numpy array self.true_label = tlabel # integer {1,-1} So far in code, I have a list called data_history full with data_istance and a set of centers (numpy array with shape (k,d)). For a given data_instance new_data, I want: 1/ Get the nearest center to new_data from centers (by euclidean distance) let it be called Nearest_center. 2/ Iterate trough data_history and: 2.1/ select elements where the nearest center is Nearest_center (result of 1/) into list called neighbors. 2.2/ Get labels of object in neighbors. Bellow is my code which work but it steel slow and I am looking for something more efficient. My Code For 1/ def getNearestCenter(data,centers): if centers.shape != (1,2): dist_ = np.sqrt(np.sum(np.power(data-centers,2),axis=1)) # This compute distance between data and all centers center = centers[np.argmin(dist_)] # this return center which have the minimum distance from data else: center=centers[0] return center For 2/ (To optimize) def getLabel(dataPoint, C, history): labels = [] cluster = getNearestCenter(dataPoint.data,C) for x in history: if np.all(getNearestCenter(x.data,C) == cluster): labels.append(x.true_label) return labels A: You should rather use the optimized cdist from scipy.spatial which is more efficient than calculating it with numpy, from scipy.spatial.distance import cdist dist = cdist(data, C, metric='euclidean') dist_idx = np.argmin(dist, axis=1) An even more elegant solution is to use scipy.spatial.cKDTree (as pointed out by @Saullo Castro in comments), which could be faster for a large dataset, from scipy.spatial import cKDTree tr = cKDTree(C) dist, dist_idx = tr.query(data, k=1)
{ "pile_set_name": "StackExchange" }
Q: How to multiply matrices? I've written a java-programm(JOGL) and have my vertices from the object I want to draw on screen. I've read, when I want to rotate my object I must multiply the matrix of my object with the so-called "rotation-matrix". Link -> rotationsmatrix . I don't know what I've done wrong by multiplying the two matrices. So please, can anyone help me? A: I cannot read German, but I used Google translate. Please forgive me if I've misunderstood your goal. Your mistake was in your definition of the rotation matrix. Because you are rotating the object around the positive $z$ axis, the $z$ coordinate should not change after the rotation. The rotation matrix should be a $3\times3$ matrix, not a $4\times4$; the result should be a $3\times1$ column vector that describes a point, not a $4\times4$ matrix. I will call $\vec M$ the original point vector and $\vec M'$ the rotated point vector. Thus: $$\vec M' = \mathbf R \vec M$$ We let $\vec M = \pmatrix{x \\ y \\ z}$. Because we are rotating around the positive $z$-axis, the rotation matrix is: $$R = \pmatrix{\cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1}$$ Thus: $$\begin{align} \vec M' &= \pmatrix{\cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1}\pmatrix{x \\ y \\ z} \\ &= \pmatrix{x\cos\theta -y\sin\theta \\ x\sin\theta + y\cos\theta \\ z} \end{align}$$
{ "pile_set_name": "StackExchange" }
Q: Android forwards compatibility I just published my first application to the market, but i just found out that android.telephony.gsm.smsmanager was depreciated as of Android 1.6. My application depends on sending SMS messages, so it cannot not work in 1.6 or newer. I built the project against 1.5, but I only have a device with 1.5 to test on. Since I built on 1.5, am I fine in terms of newer OSes, or will users get force closes? Thanks in advance! P.S. Is there a way to send/receive SMS messages in the emulator? That would be helpful. A: Usually deprecated methods work just fine in subsequent API versions. (It's just a flag that roughly says that there is an updated and better way of doing that task.) When it comes to sending and receiving SMSes in the emulator, have a look at the documentation: http://developer.android.com/guide/developing/tools/emulator.html#calling Or other forums: http://www.anddev.org/how_to_send_sms-t552.html http://learnandroid.blogspot.com/2008/01/sms-emulation-on-android.html
{ "pile_set_name": "StackExchange" }
Q: Importing an existing Eclipse project into MyEclipse workspace I am trying to import an existing project into my ECLIPSE wORKSPACE . While importing the project into Eclipse using the (Existing Projects into Workspace ) option from eclipse , i have got the following screen shot . Now my question is What does the checkbox mean here (Copy Projects into Workspace ) Please refer to the screen here http://tinypic.com/view.php?pic=n4tcua&s=7 What is the impact if we check or uncheck the checkbox Need your help on this . Thanks . A: I think he is more concerned about the check box, The check box tells you wether to create a copy of all the resources in the project you are importing to your workspace or not, and if you keep it unchecked it will just create a .classpatha and .project file ( basically a project ) with all the resources refering to original location.
{ "pile_set_name": "StackExchange" }
Q: Error on boot: no such partition grub rescue I have a dual boot system (Windows 8.1 and Ubuntu 14.04.02), However recently I have changed my motherboard and since then I am getting an error. I have reinstalled both of my operating systems and followed these but it was still no use: How To Solve: error: no such partition grub rescue in Ubuntu Linux Recovering from 'grub rescue>' crash I have tried installing lilo by using a live-disc which gave me access to Windows, but if I reinstall Ubuntu I get the same error at startup again. I want to get back to the grub2 boot menu so that I can access both Windows and Ubuntu. this is how it looks: http://i.ytimg.com/vi/zwed_1NqAZI/maxresdefault.jpg (sorry couldn't upload an image)and here is the link after performing boot repair: paste.ubuntu.com/10739355/ A: What I would if I were you, based on the information your provided: Boot from a live CD Back-up my data Format the hard drive Reinstall Windows in BIOS mode Reinstall Ubuntu in BIOS mode Restore my data
{ "pile_set_name": "StackExchange" }
Q: command.Parameters cannot convert type object to string I am trying to save the value passed by command.Parameters in a string variable but I am missing something to do that can anyone help to find out where is the issue. If you need more please do let me know I will update my description. string message = command.Parameters["@type"].Value; A: You have to do like this : string message = Convert.ToString(command.Parameters["@type"].Value); You can do command.Parameters["@type"].Value.ToString() too but it'll throw null exception if there is null value.Convert.ToString() will take care of null value and returns empty value if there is null.
{ "pile_set_name": "StackExchange" }
Q: Bad header display on iPhone 3GS I'm using this code for my website header: <!DOCYTYPE> <html> <head> <style> #image_header { border-radius:20px; user-drag:none; user-select:none; -moz-user-select:none; -webkit-user-drag:none; -webkit-user-select:none; -ms-user-select:none; height:100%; position:absolute; top:0; left:50%; transform:translateX(-50%); } #header_image { width:100%; height:150px; overflow:hidden; position:relative; border-radius:30px; } </style> </head> <body> <div id="header_image"><a href="/"><img id="image_header" src="http://static.adzerk.net/Advertisers/78e105390cf2426896c5fc38ae85a4f6.png"></a></div> </body> </html> That code cuts the header image on both sides, left and right, when the browser window is smaller than the image. I tested it on several devices and systems and it's working very well. There's only a bad display on iPhone 3GS running the newest possible version 6.1.6. This is how it looks like: Does anybody know why this does happen? How can I fix it? A: The problem probably lies in using CSS's transform. You can check it over here: http://caniuse.com/#feat=transforms2d Since it's 3Gs iPhone, i suppose you do check you browser's support. Do try adding prefix -webkit-transform: translateX(-50%) else give a change on using position for transformationbackground-position: center;
{ "pile_set_name": "StackExchange" }
Q: SwiftUI animation/transition within scrollview behaving strange I have a ScrollView in SwiftUI with multiple elements, some of them expands on tap. struct ExpandingView: View { @State var showContent = false var body: some View { VStack { HStack { Button(action: {withAnimation { self.showContent.toggle() } }) { Image(systemName: "chevron.right.circle") } Text("TITLE") .padding(.leading, 10) Spacer() } if showContent { Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras volutpat dapibus ante eget laoreet. Aenean lacus elit, auctor ut nisl id, fermentum pretium mi. Quisque lacus nisl, suscipit hendrerit est sed, congue dictum augue. Suspendisse semper viverra accumsan. Maecenas commodo turpis convallis nisl bibendum pharetra.") .transition(AnyTransition.move(edge: .top).combined(with: .opacity)) } } } } struct Test: View { var body: some View { ScrollView { ExpandingView() ExpandingView() ExpandingView() Text("Some static text") } } } If you try to open one of the expanding texts, you will see that the transition is not smooth, it kind of like jumps and then the transition starts. https://media.giphy.com/media/cjhClEVwgsEQpkBGAv/giphy.gif So here is what I've tried: If I remove the scrollview and put this to VStack for example it is working fine, but that is not an option because I have much more elements which will not fit on the screen. I've tried to set an animation for the scrollview because I read that it solves this kind of problem, like this: ScrollView { ExpandingView() ExpandingView() ExpandingView() Text("Some static text") }.animation(.spring()) It works fine in terms of the opening transition, it even looks better with the spring effect, but the spring animation for the whole scrollview plays when the view appears, which I don't want. https://media.giphy.com/media/lTMG9mGD0X0qrksYtB/giphy.gif Again, if I change the ScrollView to a VStack, the animation does not play on appearing which is nice, but I have to use a scrollview. So the best solution for me would be to keep the animation for opening the texts, but somehow remove it when the view appears. A: Here is possible solution. Read also comments inline. Tested with Xcode 11.4 / iSO 13.4 struct ExpandingView: View { @State var showContent = false var body: some View { VStack { HStack { Button(action: { self.showContent.toggle() }) { Image(systemName: "chevron.right.circle") } Text("TITLE") .padding(.leading, 10) Spacer() } if showContent { Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras volutpat dapibus ante eget laoreet. Aenean lacus elit, auctor ut nisl id, fermentum pretium mi. Quisque lacus nisl, suscipit hendrerit est sed, congue dictum augue. Suspendisse semper viverra accumsan. Maecenas commodo turpis convallis nisl bibendum pharetra.") .fixedSize(horizontal: false, vertical: true) .transition(AnyTransition.move(edge: .top).combined(with: .opacity)) } } } } struct DemoExpandingView: View { // initial nil to avoid initial animation @State private var animation: Animation? = nil var body: some View { ScrollView { VStack { ExpandingView() ExpandingView() ExpandingView() Text("Some static text") }.animation(animation) // << needed to animate static section } .onAppear { DispatchQueue.main.async { // assign in-container animation `after` container rendered self.animation = .default } } } }
{ "pile_set_name": "StackExchange" }
Q: Fit into div in CSS Hello everyone my menu bar can't fit into my <div> area at different browser. I have checked with Opera and Chrome it looks fine but with Explorer and Firefox my menu can't fit. And my menu is in this <div> tag: .page { width: 964px; margin-left: auto; margin-right: auto; background-image:url(../images2/images/orta_alan_bg_GOLGE.png); background-repeat:repeat-y; } Here is my menu: ul#menu { padding: 0 0 2px; position: relative; margin: 0; text-align: center; } ul#menu li { display: inline; list-style: none; font-family: 'Museo300Regular'; font-size:17px; font-style:normal; } ul#menu li a { background-image:url(../../images2/images/menu_bg_normal.jpg); background-repeat: repeat; padding: 5px 19px 5px; font-weight: normal; text-decoration: none; line-height: 2.8em; background-color: #e8eef4; color: #FEFEFF; border-radius: 4px 4px 0 0; -webkit-border-radius: 4px 4px 0 0; -moz-border-radius: 4px 4px 0 0; cursor:pointer; } So what is the problem why it can't fit into with Explorer and Firefox? I attach an image you can understand what I mean Here is the Chrome and Opera it can fit A: Text will always take up different space in different browsers (and even in the same browser on different computers). So, if you want your menu to fit exactly, you can't base the width of the buttons directly on the text in them. Either make all buttons the same width, or specify an exact width for each button. Alternatively, resort to using a table, which can divide the space between the cells based on their content.
{ "pile_set_name": "StackExchange" }
Q: Automapper: How do I map Lazy to TTo? I need to map a list of Lazy<TFrom> to a list of TTo. What I've done isn't working - I only get null values. Without the Lazy<> wrapper it works perfectly. What am I doing wrong? // Map this list // It's passed in as an argument and has all the data IList<Lazy<Employee>> employees public static IList<TTo> MapList(IList<Lazy<TFrom>> fromModel) { Mapper.CreateMap<Lazy<TFrom>, TTo>();// Is this needed? return Mapper.Map<IList<Lazy<TFrom>>, IList<TTo>>(fromModel); // This doesn't work // return Mapper.Map<IList<TTo>>(fromModel.Select(x => x.Value)); } // Maps the child classes Mapper.CreateMap<Lazy<Employee>, EmployeeDTO>() .ForMember(x => x.AccidentDTO, i => i.MapFrom(model => model.Value.GetAccident())) .ForMember(x => x.CriticalIllnessDTO, i => i.MapFrom(model => model.Value.GetCriticalIllness())) .ForMember(x => x.ValidationMessages, i => i.MapFrom(model => model.Value.ValidationMessages)); // Returns nulls !!! var dataDTO = MyMapper<Lazy<Employee>, EmployeeDTO>.MapList(employees); A: Here's what I've done to solve my problem. If someone has a better idea, please let me know and I'll mark it as the answer. // Get the Values of the Lazy<Employee> items and use the result for mapping var nonLazyEmployees = employees.Select(i => i.Value).ToList(); var dataDTO = MyMapper<Employee, EmployeeDTO>.MapList(nonLazyEmployees); public static IList<TTo> MapList(IList<Lazy<TFrom>> fromModel) { Mapper.CreateMap<Lazy<TFrom>, TTo>(); return Mapper.Map<IList<Lazy<TFrom>>, IList<TTo>>(fromModel); } // Maps the child classes Mapper.CreateMap<Employee, EmployeeDTO>() .ForMember(x => x.AccidentDTO, i => i.MapFrom(model => model.GetAccident())) .ForMember(x => x.CriticalIllnessDTO, i => i.MapFrom(model => model.GetCriticalIllness())) .ForMember(x => x.ValidationMessages, i => i.MapFrom(model => model.ValidationMessages));
{ "pile_set_name": "StackExchange" }
Q: Netbeans: How do i run a project step by step so I can see where the logical error is? I remember one of my tutors in University, running a project in Netbeans step by step, manually going through each step of the run time. Anyone have any idea how to do this? I can't seem to figure it out. A: First you need to add breakpoints to your code by clicking on the line number like shown on the image below: Once you do that you can start you application in debug mode. You do this by clicking the debug button. And the your program will stop at specified debug points. Here is the image of the debug button: You can get more information here: https://netbeans.org/features/java/debugger.html
{ "pile_set_name": "StackExchange" }
Q: BOOST block_prod matrix multiplication code is #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/operation.hpp> using namespace boost::numeric::ublas; int main () { boost::numeric::ublas::matrix<double> m (1000, 1000); boost::numeric::ublas::matrix<double> n (1000, 1000); boost::numeric::ublas::matrix<double> mn (1000, 1000); for (unsigned i = 0; i < m.size1 (); ++ i) for (unsigned j = 0; j < m.size2 (); ++ j) m (i, j) = 3 * i + j; for (unsigned i = 0; i < n.size1 (); ++ i) for (unsigned j = 0; j < n.size2 (); ++ j) n (i, j) = 2 * i + j; mn = block_prod<matrix<double>, 1024>(m, n); return 0; } but i get these errors: newfile.cpp:88: error: ‘block_prod’ is not a member of ‘boost::numeric::ublas’ newfile.cpp:88: error: expected primary-expression before ‘,’ token newfile.cpp:88: error: no match for ‘operator>’ in ‘1024 > (0, n)’ I searched everywhere but couldn't locate these errors. I appreciate any idea. Thanks A: Add the following to your includes #include <boost/numeric/ublas/operation_blocked.hpp>
{ "pile_set_name": "StackExchange" }
Q: How to return an empty response with grape? I have a format :xml Grape::API and for a delete request I want to return an empty response. Everything I try to enter though, true, false, nil, it tries to convert to xml. How would I go about doing this? Thanks A: Use: delete do # your code... body false end
{ "pile_set_name": "StackExchange" }
Q: How to add a to dynamic table with Jquery? How can I wrap this field array into a <tr> element, so the result will be 4 table data fields in one table row? Json data: { "result": { "rowset": { "row": [ { "field": [ { "content": test1, "name": "name1" }, { "content": "test2", "name": "name2" }, { "content": "test3", "name": "name3" }, { "content": test4, "name": "name4" } ] }, .. etc. Jquery: $.getJSON('data/jsondata.json', function(data) { var rowLength = data.result.rowset.row.length; for (var i = 0; i < rowLength; i++) { //$('tbody').append('<tr>'); //var myTr = $('tbody').append('<tr>'); for (j = 0; j < 4; j++) { $('tbody').append('<td>'+data.result.rowset.row[i].field[j].content+'</td>'); } } }); A: Little adaptation is needed for what you want. Try this: $.getJSON('data/jsondata.json', function(data) { var rowLength = data.result.rowset.row.length; for (var i = 0; i < rowLength; i++) { var row = data.result.rowset.row[i]; var myTR = $('<tr>'); for (j = 0; j < row.field.length; j++) { var myTD = $('<td>'); myTD.text(row.field[j].content); myTR.append(myTD); } $('tbody').append(myTR); } });
{ "pile_set_name": "StackExchange" }
Q: Proof of the Pythagorean Theorem without using the concept of area? Most of the proofs of Pythagorean Theorem that I see all seem to involve the concept of area, which to me does not seem "trivial" to prove. Others show proof for a particular triangle but it does not seem clear to me if it works for all right triangles or just specific variants. Is there a proof that is purely algebraic based on algebraic triangle constraints? Or one that does not rely on area at least and works for any arbitrary right triangle? A: Actually there are many concepts of area, some of them just involving additivity, some of them involving $\sigma$-additivity and completeness. Taking as a reference this recent answer of mine, all of them agree on the following facts: the area/measure of a rectangle in the plane is $\text{base}\times\text{height}$; isometric measurable sets have the same measure; if $A,B$ are measurable and almost-disjoint (meaning that $A\cap B$ is empty or it is just a polygonal path) the measure of $A\cup B$ is the sum of the measures of $A$ and $B$. In particular, all of them agree on the fact that the area of a right triangle (i.e. half a rectangle) is half the product of the lengths of the legs. So there is no issue in using any naive concept of area for proving the Pythagorean theorem, which is usually done by decomposing a square in a smaller square and four isometric right triangles, or by similar approaches by dissection (they just exploit 3.). Anyway, if the unusual appeals to you, you may just prove that the classical definitions of $\sin$ and $\cos$ match with the definition of $\sin$ and $\cos$ as the imaginary/real parts of the complex exponential function (Euler-De Moivre's formula), then prove the Pythagorean theorem in the form $\sin^2\theta+\cos^2\theta=1$ through $e^{z}\cdot e^{w}=e^{w+z}$, see here. On the other hand, as already pointed out in the comments, you already need completeness to define what a length actually is, so it is kind of artificial to want to avoid completeness for dealing with measures in geometry.
{ "pile_set_name": "StackExchange" }
Q: how to change height of uiview in tableview header I have tableview, with a view as a child as the tableview header. I would like the view to grow in height based on interaction with a button on the navigation bar. I have tried to do this with the following without success: - (IBAction)submit:(id)sender { _submitView.frame = CGRectMake(0, 0, _submitView.frame.size.width, 568); [submitView setNeedsDisplay]; [self.tableview reloadData]; } Neither of the reload methods refresh the submitView so that it grows larger when the button is pressed. How can I change the height of the view when a user triggers this function? A: If this is referring to a table view header and NOT a section header then this question suggests that you need to set the header again after changing the frame of it - Something like this should work: CGRect newFrame = headerView.frame; newFrame.size.height = newFrame.size.height + webView.frame.size.height; headerView.frame = newFrame; [self.tableView setTableHeaderView:headerView]; If this is referring to a section header then sage444 has the correct method. Good luck!
{ "pile_set_name": "StackExchange" }
Q: return type consistency in php5 I've seen tons of threads about what to return in case a PHP function fails. But they were all about PHP 4. Now in my most recent (PHP 5) project, I want to enforce some sort of consistency with return types (I don't even know, if it's gonna be worth it down the road). So if the normal return type of a method is an array, what should I return in case the method fails? null empty array() throw an exception instead In C# I would return null, so should I write PHP constantly thinking what I would do in a strongly typed language? Or does something make more sense in this specific scenario? What are the pros and cons for each of the options? A: If there was no error in performing the logic of your method (in which case I would suggest throwing an exception), I would say return an empty array. It would make an situation like this easier to deal with: foreach($obj->method() as $item) { // ... } If YourClass::method() returned null, I would get an "Invalid argument supplied" warning, whereas returning an empty array would never trigger that. Whatever you end up choosing, stick with it. No one likes working with an API whose return values are inconsistent, and have no logical meaning. A: I would throw an exception on an unrecoverable error. For example, let's say you have a method like getById($id). It is ok to return null if nothing is found. Now let's say you have another method, delete($id) that will itself call getById($id). In this case, if nothing is found (i.e: getById returned null) an exception should be thrown. Remember that whenever you report an error with a return value, being a null, empty array or string, or even a integer, you will need to handle this error, probably doing some cleanup somewhere else depending on the returned value. This might lead to some dirty in all the methods/functions involved. Using exceptions will allow you to handle and catch these errors at one place only (at the catch). So you dont have to replicate the code that checks for the error (was the return an empty array? was the return value 1, 2, or 9?, etc). Besides that, using exceptions lets you easily "catalog" the kind of error (like a business logic exception, or an invalid arguments) without writing a lot of if's along the source. So if a function/method returns something (i.e: it terminated normally), the return value is something you can use (an empty array, a null, or empty string, are all valid return values). If a function/method throws an exception, clearly something went wrong. Another important thing is that null can be equals to false, 0, and an empty string if you dont use strict checking (=== vs. ==) so this might lead to other kind of bugs. This is where exceptions can also be an advantage. And of course, whatever you decide, the important thing is to be consistent with your choices along the code.
{ "pile_set_name": "StackExchange" }
Q: Как получить индекс повторяющегося элемента в Python? Сравниваю поочередно левую и правую часть списка на равенство. И если они равны, то возвращаю число между ними, но вместо позиции 3, цифры 10, получаю позицию 1. arr = [20,10,30,10,10,15,35] # [1,100,50,-51,1,1] def find_even_index(arr): n = 0 while sum(arr[:1 + n]) <= sum(arr[2 + n:]): if sum(arr[:1 + n]) == sum(arr[2 + n:]): print(arr.index(arr[1+n])) return arr.index(arr[1+n]) # индекс позиции elif sum(arr[:1 + n]) > sum(arr[2 + n:]): print('Not allowed') return -1 n += 1 find_even_index(arr) A: Вы на каждой итерации заново вычисляете сумму всех элементов, кроме одного. То есть ваш алгоритм имеет квадратичную сложность. А ведь есть решение за O(n): def find_even_index(arr): left_sum = 0 right_sum = sum(arr[1:]) n = 0 stop_n = len(arr)-1 while n < stop_n: if left_sum == right_sum: return n left_sum += arr[n] n += 1 right_sum -= arr[n] print('Not allowed') return -1 arr = [20,10,30,10,10,15,35] print(find_even_index(arr)) Теперь, о том, почему не работает ваше решение. Когда в списке несколько значений 10, и вы ищете значение 10, то компьютер в принципе не может знать, какую из этих нескольких десяток вам нужно получить. Поэтому он выдаёт ПЕРВОЕ подходящее значение. И если разобраться, то вот это выражение: arr.index(arr[1+n]) на самом деле совершенно излишне. В нём вы ищете позицию значения, которое находится в позиции n+1. Но если вы уже знаете, что оно находится в позиции n+1, то зачем вам искать, в какой позиции оно находится? Вы же и так знаете, что n+1.
{ "pile_set_name": "StackExchange" }
Q: Why the brain region with less activity is not more responsible for some action? From my naive understanding, it seems that when people try to find correlations between a human action and a certain pattern of activity in the brain, they measure the brain activity with some device designed for that while a group of people perform that action. It seems that it is usually deduced that the brain region that shows more activity is more responsible for the action under investigation. What is the proof that the relation is not inversed? That is: Why the region with less activity is not actually more responsible for the action under investigation? A: The thing neuroscientists do is look at the differences in brain activity. They thus don't see "a high activity in brain area X". Instead, they see, between condition A and B, a difference in activity in brain area X. These differences can be both positive and negative, and each may receive it's own explanation. There must thus always be some kind of reference. This references can be done in different ways: Brain activity during a task is compared to some resting state activity. Before or after the experiment the subject is asked to sit still, often look at a fixation cross and do nothing. The assumption is that, while doing nothing, the brain is in some sort of neutral state. Every difference in activity you then find, could be attributed to the brain processes necessary to perform the experimental task. A control task is performed. In a study to emotional responses (Moser et al., 2006), for example, they show pictures. Some pictures contain emotion eliciting content, other pictures are perceived as emotional neutral. The reason a control task would be performed is to eliminate unknown variance in the data. If you are interested in an emotional response to pictures, and would compare that to a resting activity, as described above, you do not know for sure whether the difference in brain activity is caused by an emotional response, or by the fact that you presented a picture. By presenting emotion-full pictures and comparing brain activity with activity during presenting neutral pictures, the only difference is the emotional content in the picture. Not the type of task. You could perform one task and make a distinction based on behavioral results you obtained. In the following fMRI study (Drummond et al., 2005), subjects performed a psychomotor vigilance task (a simple reaction time (RT) task). The long RT-trials were seperated from the short RT-trials, and then brain activity is compared. This way, everything is the same in the experiment, but the behavior of the subjects. References Drummond, S., Bischoff-Grethe, A., Dinges, D. F., Ayalon, L., Mednick, S. C., & Meloy, M. J. (2005). The neural basis of the psychomotor vigilance task. Sleep, 28(9), 1059-1068. Moser, J. S., Hajcak, G., Bukay, E., & Simons, R. F. (2006). Intentional modulation of emotional responding to unpleasant pictures: an ERP study. Psychophysiology, 43(3), 292-296.
{ "pile_set_name": "StackExchange" }
Q: Create line heatmap with QGIS I have loaded my bike tours as .gpx files into QGIS. It already looks quite nice but I was wondering if it might be possible to create something similar to the strava heatmap with tools of QGIS. I have tried to generate points along the lines and use kernel density but it just does not look nice as a raster layer. Any suggestions? A: I am not familiar with Strava, but in QGIS you can use a combination of blending modes and draw effects to get a raster-like feel, similar to the image above. You can find both of them in the Style Properties of your layer (blending modes are under Layer Rendering). A: this is how looks like my strava routes, rendered in QGIS. What I do is to merge all gpx tracks (otherwise you should change blending mode one by one) into a single file and then, into the Layer Properties > Symbology tab, choose an appropriate colour, then opening the layer rendering options to select Screen as the blending type for the Features parameter while you keep the normal rendering for the Layer parameter. Hope this helps. Cheers,
{ "pile_set_name": "StackExchange" }
Q: Logstash : Directly send logs to redis broker I have read different articles about centralized logging. Most of them seems to use Redis as Brocker and logstash shipper to write to it. Is it possible to write directly to Redis from a Java web application ? Without logging to a file and then have logstash reading the file and sending the event to Redis. Or is it considered bad practice ? Since logstash is written in Java, maybe there is even a way to use its Redis output ? A: First, logstash plugin is write in Ruby, not Java! Of course, you can send the logs to redis directly! For example, this is my logstash indexer configuration. My redis data_type is list and key is logstash input { redis { port => 5566 data_type => "list" key => "logstash" } } output { stdout { codec => rubydebug } } I start a redis server on the port 5566, and then logstash indexer read the logs directly from redis. When I use redis-cli to put a log to the logstash list, redis 127.0.0.1:5566> lpush logstash "abc" Logstash can read the logs from redis and create a log event. The logstash output is: { "message" => "abc", "@version" => "1", "@timestamp" => "2014-07-09T01:16:33.566Z" } And also, you can refer to here about how to implement the redis-cli. For example, use jredis as your client in JAVA and send the log directly to logstash list in redis. Have fun and try it. If you have any problem, please feel free to ask! :)
{ "pile_set_name": "StackExchange" }
Q: Spring Boot Login Redirect 302 Losing HTTPS Upon login attempt in a SpringBoot app using custom login page, the webapp automatically switches from HTTPS to HTTP. I want to allow both, but it shouldn't switch out of HTTPS automatically if it was already there. See Chrome log here: -- General Request URL:https://example.com/login Request Method:POST Status Code:302 -- Response Headers: location:http://example.com/ I'm using WebSecurityConfigurerAdapter, my configure(HttpSecurity http): http.authorizeRequests().antMatchers("/version*").permitAll().anyRequest().authenticated() .and().formLogin().loginPage("/login").permitAll().and().logout().permitAll(); My /login page is quite simple: <form method="post" enctype="application/x-www-form-urlencoded"> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> <input type="text" name="username"> <input type="password" name="password"> <input id="signInBtn" type="submit" value="Sign In"> </form> Anyone know how I can fix the configuration? A: I was able to solve this issue using the following spring config: security.require-ssl=true It will force HTTPS despite a spring boot app running on port 8080.
{ "pile_set_name": "StackExchange" }
Q: JavaFX can't edit text I have: 2 FXML Files, and 2 Controllers. Each FXML's have the controllers merged. This is the code opening the new FXML (While the real fxml is running it opens another one) try { Parent root = FXMLLoader.load(getClass().getResource( "settings.fxml")); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.centerOnScreen(); stage.show(); } catch (Exception e) { e.printStackTrace(); Logger.logCrash("ApplicationScene", e); } This is the controller of the FXML file which gets opened @FXML public TextField destination; @FXML public TextArea view; @FXML public TextArea point; public void initialize() { destination.appendText("LOL"); view.appendText("LAA"); point.appendText("LOWKAPF"); } As you can see, I'm appending text on all declared fields (FXML-ID'S ARE BOUND!) after the root has been loaded through the initialize method. Sounds good and great, but I get a NullPointerException. To point the things out clearly: - I've already bound the fxml-ids to their corresponding components. - The FXML file gets loaded up correctly (root is being loaded correctly, else the initialize method wouldnt work) This has nothing to do with the static access. Even without static access this does not work. <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.text.*?> <?import javafx.scene.control.*?> <?import java.lang.*?> <?import javafx.scene.layout.*?> <AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="373.0" prefWidth="518.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="removed"> <children> <TextField fx:id="destination" layoutX="14.0" layoutY="19.0" prefHeight="25.0" prefWidth="464.0" promptText="Destination of the files" text="ie.: C:\" /> <Text layoutX="14.0" layoutY="57.0" strokeType="OUTSIDE" strokeWidth="0.0" text="moo" wrappingWidth="464.0" /> <TextArea fx:id="point" layoutX="14.0" layoutY="76.0" prefHeight="42.0" prefWidth="464.0" promptText="HI/> <Text layoutX="14.0" layoutY="131.0" strokeType="OUTSIDE" strokeWidth="0.0" text="meow" wrappingWidth="464.0" /> <TextArea fx:id="view" layoutX="14.0" layoutY="135.0" prefHeight="42.0" prefWidth="464.0" promptText="HI" /> <Text layoutX="14.0" layoutY="191.0" strokeType="OUTSIDE" strokeWidth="0.0" text="m00" wrappingWidth="464.0" /> <Button layoutX="220.0" layoutY="269.0" mnemonicParsing="false" onAction="#initialize" text="Default" /> </children> </AnchorPane> Oh. Ok, so, What I did is was: package com.engine.application.content; import com.engine.Logger; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Settings extends Application { public static void start() { Application.launch(); } @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource( "settings.fxml")); Scene scene = new Scene(root); setStageProperties(primaryStage, scene); } /** * Sets the properties of the application * * @param stage * the stage's properties to set * @param scene * the scene's properties to set */ private void setStageProperties(Stage stage, Scene scene) { stage.setScene(scene); stage.setTitle("Test"); stage.centerOnScreen(); stage.setResizable(true); stage.show(); Logger.log("Launcher", "Set stage properties"); } } Then I'm calling Application.start() when a button is clicked This is the result: Caused by: java.lang.IllegalStateException: Application launch must not be called more than once at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source) at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source) at javafx.application.Application.launch(Unknown Source) at xxx.Settings.start(Settings.java:14) at xxx.openMenu(ApplicationScene.java:43) ... 56 more I'm not calling it somewhere else btw. EDIT: This is the Settings application init. public class Settings extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource( "settings.fxml")); Scene scene = new Scene(root); setStageProperties(primaryStage, scene); System.out.println("YAY"); } /** * Sets the properties of the application * * @param stage * the stage's properties to set * @param scene * the scene's properties to set */ private void setStageProperties(Stage stage, Scene scene) { stage.setScene(scene); stage.setTitle("Test"); stage.centerOnScreen(); stage.setResizable(true); ApplicationScene.settingsMenu = stage; Logger.log("Launcher", "Set stage properties"); } } This is the Main application public class ApplicationLauncher extends Application { /** * The main method * * @param args * the arguments given upon start */ public static void main(String args[]) { launch(args); } @Override public void start(Stage stage) throws Exception { Logger.log("Launcher", "Starting up.."); Parent root = FXMLLoader.load(getClass().getResource( "ah.fxml")); Directory directory = new Directory(); // Logger.logError("LOL", "ERROR! LOLOLOL L /n LOL \n LOL LOL"); Scene scene = new Scene(root); directory.createFolder(); setStageProperties(stage, scene); Settings.main(null); Logger.log("Launcher", "Application started up!"); } /** * Sets the properties of the application * * @param stage * the stage's properties to set * @param scene * the scene's properties to set */ private void setStageProperties(Stage stage, Scene scene) { stage.setScene(scene); stage.setTitle("Test"); stage.centerOnScreen(); stage.setResizable(true); stage.show(); Logger.log("Launcher", "Set stage properties"); } } Result: Caused by: java.lang.IllegalStateException: Application launch must not be called more than once It's no where else called. (Btw. doing Settings.main(null); is the same as Settings.launch(); lol) After re-thinking the concept This did it: new Settings().start(new Scene()); A: After a long time of discussing with @SnakeDoc, We finally managed to fix it. For anyone who had the same problem: new Settings().start(new Scene()); This does it. Since the start method basically does everything (Loads the FXML etc.), only that line of code will be needed. If you're still having difficulties, make sure the FXID is identical with the variable name of the instance to connect with.
{ "pile_set_name": "StackExchange" }
Q: How to profile pyspark jobs I want to understand profiling in pyspark codes. Following this: https://github.com/apache/spark/pull/2351 >>> sc._conf.set("spark.python.profile", "true") >>> rdd = sc.parallelize(range(100)).map(str) >>> rdd.count() 100 >>> sc.show_profiles() ============================================================ Profile of RDD<id=1> ============================================================ 284 function calls (276 primitive calls) in 0.001 seconds Ordered by: internal time, cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 4 0.000 0.000 0.000 0.000 serializers.py:198(load_stream) 4 0.000 0.000 0.000 0.000 {reduce} 12/4 0.000 0.000 0.001 0.000 rdd.py:2092(pipeline_func) 4 0.000 0.000 0.000 0.000 {cPickle.loads} 4 0.000 0.000 0.000 0.000 {cPickle.dumps} 104 0.000 0.000 0.000 0.000 rdd.py:852(<genexpr>) 8 0.000 0.000 0.000 0.000 serializers.py:461(read_int) 12 0.000 0.000 0.000 0.000 rdd.py:303(func) Above works great. But If I do something like below: from pyspark.sql import HiveContext from pyspark import SparkConf from pyspark import SparkContext conf = SparkConf().setAppName("myapp").set("spark.python.profile","true") sc = SparkContext(conf=conf) sqlContext = HiveContext(sc) df=sqlContext.sql("select * from myhivetable") df.count() sc.show_profiles() This does not give me anything. I get the count but show_profiles() give me None Any help appreciated A: There is no Python code to profile when you use Spark SQL. The only Python is to call Scala engine. Everything else is executed on Java Virtual Machine.
{ "pile_set_name": "StackExchange" }
Q: Does pow() work for int data type in C? I was simply writing a program to calculate the power of an integer. But the output was not as expected. It worked for all the integer numbers except for the power of 5. My code is: #include <stdio.h> #include <math.h> int main(void) { int a,b; printf("Enter the number."); scanf("\n%d",&a); b=pow(a,2); printf("\n%d",b); } The output is something like this: "Enter the number. 2 4 "Enter the number. 5 24 "Enter the number. 4 16 "Enter the number. 10 99 Can't we use pow() function for int data type?? A: Floating point precision is doing its job here. The actual working of pow is using log pow(a, 2) ==> exp(log(a) * 2) Look at math.h library which says: <math.h> /* Excess precision when using a 64-bit mantissa for FPU math ops can cause unexpected results with some of the MSVCRT math functions. For example, unless the function return value is stored (truncating to 53-bit mantissa), calls to pow with both x and y as integral values sometimes produce a non-integral result. ... */ Just add 0.5 to the return value of pow and then convert it to int. b = (int)(pow(a,2) + 0.5); So, the answer to your question Does pow() work for int data type in C? Not always. For integer exponentiation you could implement your own function (this will work for 0 and +ve exp only): int int_pow(int base, int exp) { int result = 1; while (exp) { if (exp % 2) result *= base; exp /= 2; base *= base; } return result; } A: there is no int based pow. What you are suffering from is floating point truncation. an int based pow is too constrained (the range of inputs would quickly overflow an int). In many cases int based pow, like in your case where its powers of 2 can be done efficiently other ways. A: printf("%a", pow(10, 2)) and see what you get; I expect you'll see you don't quite get 100. Call lround if you want to round instead of truncating.
{ "pile_set_name": "StackExchange" }
Q: Interprocess communication: passing C-style structs vs C++-objects Warning/Disclaimer: This question contains heresay, but I could not find the answers to the claims stated below, in my little research done in the last half an hour or so. I am just curious if someone here already knows about this. This question has no code. Just technical queries. Background: I have a legacy application, which uses C-style structs passed between processes for interprocess communication. And this works quite well and has been working for many many years, long before even I was on this planet :P. I was supposed to write a new process that would become part of this application. Unwittingly, I wrote it in C++, assuming whaterver IPC, we are using could handle this. Unfortunately, then I found out (from colleagues) that the existing infrastructure can only pass C-style structs. 'Unverified' claims/statements: In addition,one of the colleagues listed the following reasons why C++ was a bad choice in this case. C++ objects have vtables. C-style structs are just variables and values. Therefore C-style structs can be passed around processes, while C++ objects cannot be. With C-style structs we can embed information like size of the struct, so that both sides know what to expect and what to send, but for C++ objects this is not possible since 'the size of the vtable could vary'. 'If we change compilers, then it is even worse. We would have even more permutations to deal with for the case of C++ objects.' Investigating the claims: Needless to say, this colleague has a little bias for C, but he is much more experienced than me and probably knows what he is talking about. I am language-agnostic. But this immediately got me thinking. How can it be that we cannot do interprocess communication with C++? I googled and the first hits were invariably from stackoverflow, like this one: Inter-Process Communication Recommendation And I looked up on the different methods of IPC listed here. https://en.wikipedia.org/wiki/Inter-process_communication#Approaches I mean, I followed up on each of those methods in the list like pipes or shared memory, etc and the only caveat that everyone keeps on pointing out, is, that pointers (duh! of course) cannot be passed like this and some issues with synchronization could creep up - je nachdem. BUT nowhere could I find something that could refute or corroborate his 'claims'. (Of course, I could continue on digging for the rest of the day. :P) Questions: Are his three claims really so or was it just FUD? Considering that, all that I have in those objects that I wanted wanted to pass around are also only, POD variables and some STL containers like std::vector and std::pair and their values (no pointers or anything), and the getters for those variables. There are no virtual functions except the virtual destructor, which exists since I inherited all the messages from one base message class, since at that time, I was thinking that there might be some common base functionality. (I could get rid of this base class quite easily now, since there is nothing really common there till now! Thankfully for some reason I kept the parsing and formatting of messages in a separate class. Luck or foresight? :D ) It also actually makes me wonder, how does the compiler know when a struct is a C-style struct since we are using the g++ compiler for the whole project anyways? Is it the use of the 'virtual' keyword? I am not asking for a solution for my case. I can wrap the results from those objects into structs and pass them on through the IPC or I could get rid of base class and virtual destructor as stated in 'my' point 1 above. Boost or any C++11 stuff or any library that handles this is not desired. Any suggestions in this regard are tangential to the question at hand. (p.s. Now that I posted and re-read what I posted, I want to nip the thought in the bud that might be creeping up in any reader's head who reads this, that ... I am asking this for my knowledge, and not for arguing with that colleague. Skepticism is good, but would be nice for the community if we all assumed others to have good intentions.:) ) A: only caveat that everyone keeps on pointing out, is, that pointers (duh! of course) cannot be passed like this Pointer values (as well as other references to memory and resources) are indeed meaningless across processes. This is obviously a consequence of virtual memory. Another caveat is while C standard specifies exact (platform specific) memory layout for structs, C++ standard doesn't guarantee a particular memory layout for classes in general. One process doesn't necessarily agree with another process on the amount of padding between members for example - even within the same system. C++ only guarantees memory layout for standard layout types - and this guaranteed layout matches with C structs. ... and some STL containers like std::vector ... (no pointers or anything) All standard containers except std::array use pointers internally. They have to because their size is dynamic, and therefore must allocate the data structures dynamically. Also, none of those are standard layout classes. Furthermore, the class definitions of one standard library implementation are not guaranteed to match another implementation and two processes can use different standard libraries - this is not at all uncommon on Linux where some processes might use libstdc++ (from GNU) while others might use libc++ (from Clang). There are no virtual functions except the virtual destructor In other words: There is at least one virtual function (the destructor), and therefore there is a pointer to a vtable. And also no guaranteed memory layout because classes with virtual functions are never standard layout classes. So to answer the questions: Mostly no FUD, although some claims are technically a bit inaccurate: C++ objects may have vtables; not all of them do. C structures can have pointers, so not all C structures can be shared either. Some C++ objects can be shared accross processes. Specifically, standard layout classes can be shared (assuming there are no pointers). Objects with vtables cannot be shared indeed. Standard layout classes have a guaranteed memory layout. Changing the compiler is not a problem as long as you restrict yourself to standard layout classes. Trying to share other classes might appear work if you're unlucky, but you'll probably face problems when you start mixing compilers. The C++ stadard defines the exact conditions where a class is standard layout. All C struct definitions are standard layout classes in C++. The compiler knows those rules. This is not a question. Conclusion: You can use C++ for IPC, but you're limited to standard layout classes in that interface. This excludes you from many C++ features such as virtual functions, access specifiers etc. But not all: You can still have member functions for example. Do note however, that using C++ features may cause the inter process interface to only work with C++. Many languages can interface with C, but hardly any can interface with C++. Furthermore: If your "interprocess" communication goes beyond the boundaries of the system - across network that is - even a C structure or standard layout class is not a good representation. In that case you need serialisation.
{ "pile_set_name": "StackExchange" }
Q: How to add parent object in JSON with python I have this json which has 3 parents and several child elements under each parent. I want to add one more common parent for all 3 current parents. Currently I have: { "Parent1": { "Key1": "Value", "Key2": "Value", "Key3": "Value" }, "Parent2": { "Key1": "Value", "Key2": "Value", "Key3": "Value" }, "Parent3": { "Key1": "Value", "Key2": "Value", "Key3": "Value" } } What I want to have: { "Main parent": { "Parent1": { "Key1": "Value", "Key2": "Value", "Key3": "Value" }, "Parent2": { "Key1": "Value", "Key2": "Value", "Key3": "Value" }, "Parent3": { "Key1": "Value", "Key2": "Value", "Key3": "Value" } } } Below python3 code doesn't do the job: with open ("myfile.json", 'r') as f: myjson = json.load(f) myjson["Main Parent"] = myjson I would appreciate if you spread some light on this situation. A: with open ("myfile.json", 'r') as f: myjson = json.load(f) myjson = {'Main Parent': myjson}
{ "pile_set_name": "StackExchange" }
Q: Why is my command-line hash different from online MD5 hash results? On a Mac OS X v10.5 (Leopard) PowerPC, if I do: echo "hello" | md5 on the command line, the result is: b1946ac92492d2347c6235b4d2611184 But if I enter hello into one of the online MD5 hash sites like http://md5online.net/, I get: 5d41402abc4b2a76b9719d911017c592 Am I doing something wrong? If I want to use MD5 on the go, how can I make sure what I'm getting on the command line will agree with the online md5 tools? A: When you echo from the command line, md5 is calculating the sum of 6 characters - h,e,l,l,o plus newline. The text you enter in a website doesn't have a newline. Try doing echo -n hello | md5 and it'll give you what you expect. The -n tells echo not to output a newline. A: You can also use printf instead of echo, which automatically suppresses the newline character: printf hello | md5 Or even: printf "hello" | md5
{ "pile_set_name": "StackExchange" }
Q: Determine $w + \overline w + (w + w^2 )^2- w^{38}(1-w^2)$ for each $w \in G_7$. I'm starting to see complex numbers in algebra. I've missed a few classes and I have exercises similar to this one: Determine $w + \overline w + (w + w^2 )^2- w^{38}(1-w^2)$ for each $w \in G_7$. It should break down at one moment to two cases, when $w=1$ and $w \not = 1$. I'm not sure how to get there. So far I have that the expression above should be equal to $w+w^2+w^3+w^4+w^5+w^6$ if I didn't mess up along the way. Could you give me any hint of what I should do next? (It's not for grading so a complete answer would be useful as well) Many thanks! A: Your expression should evaluate to $w+w^2+w^3+w^4+w^5+w^6$. For the case $w\neq1$, you can use that $1+w+w^2+w^3+w^4+w^5+w^6=0$$. See for example: Intuitive understanding of why the sum of nth roots of unity is 0? For the case $w=1$, simply evaluate $w+w^2+w^3+w^4+w^5+w^6=1+1^2+\ldots=?$.
{ "pile_set_name": "StackExchange" }
Q: AFrame: How to render a camera to a texture I'm trying to have a second camera to show a "from the sky" view of an AFrame scene. I've learned how to do it using a 2D canvas for rendering, following this example: But I wonder if this could be done without using a external <div>, something like rendering directly to some asset, or maybe directly to the texture... My current code is: <html> <head> <script src="//aframe.io/releases/0.8.2/aframe.min.js"></script> <script> // Original code: // https://wirewhiz.com/how-to-use-a-cameras-output-as-a-texture-in-aframe/ // AFRAME.registerComponent('view',{ 'schema': { canvas: { type: 'string', default: '' }, // desired FPS fps: { type: 'number', default: 90.0 } }, 'init': function() { var targetEl = document.querySelector(this.data.canvas); this.counter = 0; this.renderer = new THREE.WebGLRenderer( { antialias: true } ); this.renderer.setPixelRatio( window.devicePixelRatio ); this.renderer.setSize( targetEl.offsetWidth, targetEl.offsetHeight ); // creates spectator canvas targetEl.appendChild(this.renderer.domElement); this.renderer.domElement.id = "canvas"; this.renderer.domElement.crossorigin="anonymous" this.renderer.domElement.height=300; this.renderer.domElement.width=400; this.el.removeAttribute('look-controls'); this.el.removeAttribute('wasd-controls'); console.log(this.renderer.domElement); console.log(document.querySelector('a-scene')) }, 'tick': function(time, timeDelta) { var loopFPS = 1000.0 / timeDelta; var hmdIsXFasterThanDesiredFPS = loopFPS / this.data.fps; var renderEveryNthFrame = Math.round(hmdIsXFasterThanDesiredFPS); if(this.counter % renderEveryNthFrame === 0){ this.render(timeDelta); } this.counter += 1; }, 'render': function(){ this.renderer.render( this.el.sceneEl.object3D , this.el.object3DMap.camera ); } }); </script> <body> <a-scene physics="debug: true"> <a-plane static-body position="0 0 -4" rotation="-90 0 0" width="30" height="40" color="yellow"></a-plane> <a-box color="red" position="0 2 0" depth="8" width="8"></a-box> <a-entity id="secondaryCamera" position="0 40 0" rotation="-90 0 0"> <a-camera view="canvas:#spectatorDiv;" active="false"> </a-camera> </a-entity> <a-entity position="0 0 10" look-controls> <a-entity camera position="0 1.6 0" wasd-controls> <a-entity geometry="primitive:plane; width:.2; height:.2" material="src:#canvas; opacity: .6" position="0.2 -0.3 -0.7" rotation="0 -10 0"></a-entity> <a-cylinder radius="2" color="green"></a-box> </a-entity> </a-entity> </a-scene> <div style="height:300px; width:400px;" id='spectatorDiv'></div> </body> </html> A: After some tinkering and considering all suggestions, I've come to this code, that gives me what I wanted. In short, I built a component (camrenderer) that uses a canvas within the a-assets element for rendering the output of the camera. This allows any material to reference it (in the code below, see it added to a plane attached to the main camera). For ensuring the material gets updated when the rendering changes, you also need to add another component (canvas-updater) to the object acting as screen. Therefore, the camera renderer can be referenced by any material in any component, with no extra hacks. <html> <head> <script src="//aframe.io/releases/0.8.2/aframe.min.js"></script> <script> AFRAME.registerComponent('camrender',{ 'schema': { // desired FPS fps: { type: 'number', default: 90.0 }, // Id of the canvas element used for rendering the camera cid: { type: 'string', default: 'camRenderer' }, // Height of the renderer element height: { type: 'number', default: 300 }, // Width of the renderer element width: { type: 'number', default: 400 } }, 'update': function(oldData) { var data = this.data if (oldData.cid !== data.cid) { // Find canvas element to be used for rendering var canvasEl = document.getElementById(this.data.cid); // Create renderer this.renderer = new THREE.WebGLRenderer({ antialias: true, canvas: canvasEl }); // Set properties for renderer DOM element this.renderer.setPixelRatio( window.devicePixelRatio ); this.renderer.domElement.crossorigin = "anonymous"; }; if (oldData.width !== data.width || oldData.height !== data.height) { // Set size of canvas renderer this.renderer.setSize(data.width, data.height); this.renderer.domElement.height = data.height; this.renderer.domElement.width = data.width; }; if (oldData.fps !== data.fps) { // Set how often to call tick this.tick = AFRAME.utils.throttleTick(this.tick, 1000 / data.fps , this); }; }, 'tick': function(time, timeDelta) { this.renderer.render( this.el.sceneEl.object3D , this.el.object3DMap.camera ); } }); AFRAME.registerComponent('canvas-updater', { dependencies: ['geometry', 'material'], tick: function () { var el = this.el; var material; material = el.getObject3D('mesh').material; if (!material.map) { return; } material.map.needsUpdate = true; } }); </script> </head> <body> <a-scene> <a-assets> <canvas id="cam2"></canvas> </a-assets> <a-plane position="0 0 -4" rotation="-90 0 0" width="30" height="40" color="yellow"></a-plane> <a-box color="red" position="0 2 0" depth="8" width="16"></a-box> <a-box color="blue" position="0 2 6" depth="2" width="6"></a-box> <a-entity position="0 40 0" rotation="-90 0 0"> <a-camera camrender="cid: cam2" active="false"> </a-camera> </a-entity> <a-entity position="0 0 10" look-controls> <a-entity camera position="0 1.6 0" wasd-controls> <a-entity geometry="primitive:plane; width:.2; height:.2" material="src:#cam2; opacity: .6" canvas-updater position="0.2 -0.3 -0.7" rotation="0 -10 0"></a-entity> <a-cylinder radius="2" color="green"></a-cylinder> </a-entity> </a-entity> </a-scene> </body> </html> Notes: Thanks to Diego Marcos who put me on-track. Thanks to Piotr Adam Milewski who suggested using Utils.ThrottleTick, which simplifies the code a lot. This version includes a fix for a problem found with current master (but also works with 0.8.2) I've created a npm package with this components: A-Frame Playground Components. So you can just use it instead of the script above.
{ "pile_set_name": "StackExchange" }
Q: How can I test for a serialized variable? Without throwing E_NOTICE if string is not serialized I am coding my own var_dump to meet certain requirements which probably only apply to me and have a problem. The code checks for objects, arrays, etc and finally gets to a stage where it reckons it is left with a number, a string or a boolean. Of course, a string can actually be a serialized variable, so I want to heck for that ... if (is_string($variable)) { // check if it is serialzed; if so, unserialize & dump as an array, \ // with a suitable header indicating that it was serialized try { $old_error_level= error_reporting(E_ALL ^ E_NOTICE); $unserialized_varaible = @unserialize($variable); $result .= my_dump($unserialized_varaible, ... <some params>); // recursive call $old_error_level= error_reporting($old_error_level); } catch(Exception $e) // Treat it as a string { $old_error_level= error_reporting($old_error_level); $result .= GetHtmlForSimpleVariable($variable, ... <some params>); } } But, what I get when trying to dump a simple, non-serialized, string is Problem type Notice "unserialize() [<a href='function.unserialize'>function.unserialize</a>]: Error at offset 0 of 14 bytes" at line 362 in file my_dump.php<br><br> Update: the point there is that I want to suppress that E_NOTICE when a string is not a serialized string. I had thought that the @on @unserizlize() would do that, but ... If the string is serialized then everything is hunky dory. If not, then not. A: When you try to unserialize it, it returns false if it is not serialized. It also returns a an E_NOTICE which is where that output is coming from. From the manual: In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued. Check if the return value of unserialize ===false
{ "pile_set_name": "StackExchange" }
Q: Boundary equation of the trajectory of a closed curve Are there analytical/closed form equations for the boundaries of the trajectory traced out by a closed curve (tool) in 2D plane? Refer to the attached image (The tool does not change orientation. It moves along a trajectory) Perhaps one can find a point on g(x,y)=0 farthest along the normal of f(x,y) = 0 for every point on the trajectory of the tool. A: The key search term here is convolution, as essentially your tool $A$ is convolved with the shape $B$ whose boundary is the curve. The first paper below provides more than you need (in that your moving shape is rigid): In this paper we suggest an algebraic algorithm to compute the exact general sweep boundary of a 2D curved object which moves in its own $xy$ plane along a parametric curve trajectory while changing its shape parametrically. In this case the general sweep boundary is composed of algebraic curve segments.         The second paper below is more specific to your question (despite its non-descriptive title). Kim, Myung-Soo, Jae-Woo Ahn, and Soon-Bum Lim. "An algebraic algorithm to compute the exact general sweep boundary of a 2D curved object." Information Processing Letters 47.5 (1993): 221-229. Bajaj, Chanderjit, and M-S. Kim. "Generation of configuration space obstacles: The case of a moving sphere." IEEE Journal on Robotics and Automation 4.1 (1988): 94-99.
{ "pile_set_name": "StackExchange" }
Q: Mock SSL HttpRequest for Unit Testing I'm trying to mock out an SSL HttpRequest but I'm having trouble figuring out how to set the protocol to HTTPS in the request object. I got started from an example from Phil Haack here: http://haacked.com/archive/2005/06/11/simulating_httpcontext.aspx Is there a way to set the request to SSL? public class MockHttpRequest : SimpleWorkerRequest { private string _Host; public MockHttpRequest( string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output, string host) : base(appVirtualDir, appPhysicalDir, page, query, output) { if (string.IsNullOrEmpty(host)) { throw new ArgumentException("Host must be provided."); } _Host = host; } } public static class UnitTestingHelper { public static HttpContext CreateMockHttpContext(string host, string page) { string appVirtualDir = "/"; string appPhysicalDir = @"C:\Documents and Settings\user\My Documents\Workspace\Project\"; string query = string.Empty; TextWriter output = null; MockHttpRequest request = new MockHttpRequest(appVirtualDir, appPhysicalDir, "default.aspx", query, output, host); // How to make the request HTTPS? HttpContext context = new HttpContext(request); return new HttpContext(request); } } A: I think there's a IsSecureConnection property somewhere in HttpContext.Request that needs to be true.
{ "pile_set_name": "StackExchange" }
Q: How to test custom JsonSerializer with JUnit and Mockito i have a custom JsonSerialzier to serialize dates in a special format: public class CustomDateJsonSerializer extends JsonSerializer<Date> { @Override public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException { String outputDateValue; //... do something with the Date and write the result into outputDateValue gen.writeString(outputDateValue); } } It works fine but how can i test my code with JUnit and Mockito? Or rather how can i mock the JsonGenerator and access the result? Thank you for your help. A: You can do something like this: import static org.mockito.Mockito.verify; import static org.mockito.Mockito.times; @RunWith(MockitoJUnitRunner.class) public class CustomDateJsonSerializerTest { @Mock private JsonGenerator gen; @Test public void testOutputDateValue() { CustomDateJsonSerializer serializer = new CustomDateJsonSerializer(); serializer.serialize(new Date(), gen, null /*or whatever it needs to be*/); String expectedOutput = "whatever the correct output should be"; verify(gen, times(1)).writeString(expectedOutput); } }
{ "pile_set_name": "StackExchange" }
Q: VBA macro - Clicking the button part of code does not run So, I have been reading and digging a bit around how to solve this problem and I havent found a working solution. I have tried: -checking i have no "active-Sheets/Workbook" references. -Checking method names are ok. This is I am a newbie in VBA so i stole the function from somewhere and made a little tweak to it. Function (and whole code) is working properly when i hit the play button in the vba console, but it does not when i click the activeX button. Any idea how to proceed? Thanks in advance! Here is the code in the button_click(): Private Sub CommandButton1_Click() Módulo1.Formatting_Number (Sheets("Hoja5").Range("AB8:AB23")) Módulo1.WhereToInsertRow End Sub And here is the code in the module, that gets called from the button: Public Function LastRec(Myrng As Range, g As Integer) For x = Myrng(1).Row To Myrng(Myrng.Count, 1).End(xlUp).Row If Cells(x, Myrng.Column).Value = Cells(x + 1, Myrng.Column).Value Then GoTo continue If Cells(x, Myrng.Column).Value = g Then LastRec = x Exit Function End If LastRec = CStr(g) & "Not FOUND" continue: Next x End Function Public Sub WhereToInsertRow() Dim g As Integer For g = 2 To 7 Sheets("Hoja5").Range("AB" & g + 6) = LastRec(Sheets("Hoja5").Range("O:O"), g) Next g For g = 14 To 23 Sheets("Hoja5").Range("AB" & g).Value = LastRec(Sheets("Hoja5").Range("O:O"), (g + 87)) Next g End Sub Public Sub Formatting_Number(rng As Range) Dim cel As Range For Each cel In rng cel.NumberFormat = "0" Next cel End Sub P.D: In case you are curious, original function returned last occurrence of a value in a column starting from last cell, i tweaked it so now it starts from first cell. A: You could tighten it up thus. Better still to specify other parameters such as ranges and/or sheets. Public Function LastRec(Myrng As Range, g As Integer) Dim x As Long, rFind As Range With Myrng Set rFind = .Find(What:=g, After:=.Cells(.Count), Lookat:=xlWhole, _ SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) If Not rFind Is Nothing Then LastRec = rFind.Row Else LastRec = g & " not FOUND" End If End With End Function Public Sub WhereToInsertRow() Dim g As Integer, r As Range With Sheets("Hoja5") Set r = .Range("O1", .Range("O" & Rows.Count).End(xlUp)) End With For g = 2 To 7 Sheets("Hoja5").Range("AB" & g + 6) = LastRec(r, g) Next g For g = 14 To 23 Sheets("Hoja5").Range("AB" & g).Value = LastRec(r, g + 87) Next g End Sub Public Sub Formatting_Number(rng As Range) rng.NumberFormat = "0" End Sub Sub x() Module1.Formatting_Number Sheets("Hoja5").Range("A8:A23") Module1.WhereToInsertRow End Sub
{ "pile_set_name": "StackExchange" }
Q: Visual Basic 6 Command included on String Table Here is the situation, I have this string table, in a .res file and I have some strings loaded into one of the forms, say Form1. On a form on I want to popup a message box with a message loaded from the string table using LoadResString(1234). Is it possible that when Resource ID 1234 contains "This is testing vbNewline This is a new line!." that string will be loaded using the said function onto the message box (popup box)? I've tested it: It will also print out the "vbNewline" command and NOT parse it. Is there any other way to parse the said string making this kind of message ? This is testing This is new line!. I wanted that kind of message to appear. A: You are trying to put a VB constant in a String expression so it is treating it like text, you can try using the Replace Function ( I realize this is a .Net link but the signature is the same as the VB6 method) to remove your string and substitute the correct value something like this should work: MsgBox (Replace(LoadResString(1234), "vbNewLine", vbNewLine)) or create a function like this: Public Function ParseNewLine(value As String) As String ParseNewLine = Replace(value, "vbNewLine", vbNewLine) End Function and call it like this: MsgBox (ParseNewLine(LoadResString(1234)))
{ "pile_set_name": "StackExchange" }
Q: Python 3.6.1 Linux - Blackjack game Attached below, is the full program for the simple, text-based blackjack game that I have recently finished developing for Python. Upon review, I was wondering if anyone out there would be able to offer any suggestions for any improvements to my code that could improve functionality or perhaps reduce the length of the program. #J.Corbett #Blackjack game prototype - text based #04/09/17 #import lines import time import random import sys #set default integer values PLYRcardValue = 0 DLRcardValue = 0 PLYRcard1 = 0 PLYRcard2 = 0 PLYRcard3 = 0 DLRcard1 = 0 DLRcard2 = 0 DLRcard3 = 0 #set True/False statements play = True PLYR_ace1 = False PLYR_ace2 = False PLYR_ace3 = False DLR_ace1 = False DLR_ace2 = False DLR_ace3 = False print("Blackjack Protoype - Version: 101\n\n") #"open file" function - for reading def readFile(filename): myList = [] file = open(filename,"r") for line in file: currentLine = line.strip().split(",") myList.append(currentLine[0]) return myList #open external file "deck" and assign to array deck = readFile("deck.txt") #"check if a card is an Ace" function def checkAce (card,deck,ace): if card == deck[0] or card == deck[13] or card == deck[26] or card == deck[39]: ace = True else: ace = False return card, ace #calling function example: PLYRcard1, PLYR_ace1 = checkAce(PLYRcard1, deck, PLYR_ace1) #"calculate value of dealt hand" function def HandValueCalc(card,hand,deck): card = deck[random.randint(0,51)] if card == deck[0]: hand += 1 elif card == deck[1]: hand += 2 elif card == deck[2]: hand += 3 elif card == deck[3]: hand += 4 elif card == deck[4]: hand += 5 elif card == deck[5]: hand += 6 elif card == deck[6]: hand += 7 elif card == deck[7]: hand += 8 elif card == deck[8]: hand += 9 elif card == deck[9]: hand += 10 elif card == deck[10]: hand += 10 elif card == deck[11]: hand += 10 elif card == deck[12]: hand += 10 elif card == deck[13]: hand += 1 elif card == deck[14]: hand += 2 elif card == deck[15]: hand += 3 elif card == deck[16]: hand += 4 elif card == deck[17]: hand += 5 elif card == deck[18]: hand += 6 elif card == deck[19]: hand += 7 elif card == deck[20]: hand += 8 elif card == deck[21]: hand += 9 elif card == deck[22]: hand += 10 elif card == deck[23]: hand += 10 elif card == deck[24]: hand += 10 elif card == deck[25]: hand += 10 elif card == deck[26]: hand += 1 elif card == deck[27]: hand += 2 elif card == deck[28]: hand += 3 elif card == deck[29]: hand += 4 elif card == deck[30]: hand += 5 elif card == deck[31]: hand += 6 elif card == deck[32]: hand += 7 elif card == deck[33]: hand += 8 elif card == deck[34]: hand += 9 elif card == deck[35]: hand += 10 elif card == deck[36]: hand += 10 elif card == deck[37]: hand += 10 elif card == deck[38]: hand += 10 elif card == deck[39]: hand += 1 elif card == deck[40]: hand += 2 elif card == deck[41]: hand += 3 elif card == deck[42]: hand += 4 elif card == deck[43]: hand += 5 elif card == deck[44]: hand += 6 elif card == deck[45]: hand += 7 elif card == deck[46]: hand += 8 elif card == deck[47]: hand += 9 elif card == deck[48]: hand += 10 elif card == deck[49]: hand += 10 elif card == deck[50]: hand += 10 else: hand += 10 return card, hand #calling function example: PLYRcard1, PLYRcardValue = HandValueCalc(PLYRcard1,PLYRcardValue,deck) #"check if hand is bust" function def checkBust (handValue): if handValue > 21: bust = True print("Gone bust!") else: bust = False return bust #calling function example: PLYRbust = checkBust(PLYRcardValue) #initiate game if play == True: #setvalues for the players cards, and check if any are aces PLYRcard1, PLYRcardValue = HandValueCalc(PLYRcard1, PLYRcardValue, deck) PLYRcard2, PLYRcardValue = HandValueCalc(PLYRcard2, PLYRcardValue, deck) PLYRcard1, PLYR_ace1 = checkAce(PLYRcard1, deck, PLYR_ace1) PLYRcard2, PLYR_ace2 = checkAce(PLYRcard2, deck, PLYR_ace2) time.sleep(1) print("You have been dealt these two cards:",PLYRcard1,"and",PLYRcard2) time.sleep(1) print("The value of your hand is:",PLYRcardValue) time.sleep(1) #let player choose value for Ace, if an ace is present (potential for a function?) if PLYR_ace1 == True or PLYR_ace2 == True: ace_choice = input("You have been dealt an ace. The ace can be valued one, or eleven. \nWhich value do you want?:") if ace_choice == 1: PLYRcardValue += 1 elif ace_choice == 11: PLYRcardValue += 11 else: print("Unknown Error: Please restart the program.") sys.exit() print("The value of your hand is now:",PLYRcardValue) choice = input("\nWould you like to stick or split?:") if choice == "split": #set value for the players third card, and check if an ace is present PLYRcard3, PLYRcardValue = HandValueCalc(PLYRcard3, PLYRcardValue, deck) PLYRcard3, PLYR_ace3 = checkAce(PLYRcard3, deck, PLYR_ace3) print("You drew:", PLYRcard3) time.sleep(0.5) #choice for value of ace if PLYR_ace3 == True: ace_choice = input("You have been dealt an ace. The ace can be valued one, or eleven. \nWhich value do you want?:") if ace_choice == 1: PLYRcardValue += 1 elif ace_choice == 11: PLYRcardValue += 11 else: print("Unknown Input: Please restart the program.") sys.exit() print("Your hand is now worth:",PLYRcardValue) time.sleep(1) #check if the hand is bust PLYRbust = checkBust(PLYRcardValue) #CPU's turn #set values for dealers hand, check if aces DLRcard1, DLRcardValue = HandValueCalc(DLRcard1, DLRcardValue, deck) DLRcard2, DLRcardValue = HandValueCalc(DLRcard2, DLRcardValue, deck) DLRcard1, DLR_ace1 = checkAce(DLRcard1, deck, DLR_ace1) DLRcard2, DLR_ace2 = checkAce(DLRcard2, deck, DLR_ace2) time.sleep(1) #random choice for ace value if DLR_ace1 == True or DLR_ace2 == True: ace_DLR = random.randint(1,2) if ace_DLR == 1: DLRcardValue+= 1 print("The dealer has decided to value the Ace at: 1") elif ace_DLR == 2: DLRcardValue += 11 print("The dealer has decided to value the Ace at: 11") else: print("Unknown Error: Please restart the program.") sys.exit() print("\nThe Dealer's hand is worth:",DLRcardValue) #random choice for dealer splitting DLRchoice = random.randint(1,3) time.sleep(3) if DLRchoice == 3: print("\nThe dealer has decided to split.") #set value for dealers third card, check if ace DLRcard3, DLRcardValue = HandValueCalc(DLRcard3, DLRcardValue, deck) DLRcard3, DLR_ace3 = checkAce(DLRcard3, deck, DLR_ace3) #ace's value, random choice if DLR_ace3 == True: ace_DLR = random.randint(1,2) if ace_DLR == 1: DLRcardValue+= 1 elif ace_DLR == 2: DLRcardValue += 11 else: print("Unknown Error: Please restart the program.") sys.exit() print("The Dealer's hand is now worth:",DLRcardValue) else: print("\nThe dealer has decided to stick.") time.sleep(1) #check if dealer's hand is bust DLRbust = checkBust(DLRcardValue) time.sleep(2) #Decide winner if PLYRbust == True and DLRbust == True and DLRcardValue < PLYRcardValue: print("\nThe Dealer is closer to 21! \nDealer wins!") elif PLYRbust == True and DLRbust == True and DLRcardValue > PLYRcardValue: print("\nThe Player is closer to 21! \nPlayer wins!") elif PLYRbust == True and DLRbust == False: print("\nThe Dealer is closer to 21! \nDealer wins!") elif PLYRbust == False and DLRbust == True: print("\nThe Player is closer to 21! \nPlayer wins!") elif PLYRcardValue > DLRcardValue and PLYRcardValue < 21: print("\nThe Player is closer to 21! \nPlayer wins!") elif PLYRcardValue < DLRcardValue and DLRcardValue < 21: print("\nThe Dealer is closer to 21! \nDealer wins!") elif PLYRcardValue == DLRcardValue: print("It's a draw!") else: print("\nUnknown error, please Restart the program.") A: I'm only going to review your functions, as your if play == True code is in no way anywhere near how I play blackjack. Python has a style guide - PEP8. It's best if you follow it so that fellow Python programmers can read and manipulate your code easier. It's mostly simple things like rather than calling a function checkAce, you call it check_ace. Make sure you have a space after most commas, so (card,deck,ace) becomes (card, deck, ace). Don't put spaces between a functions name and the arguments. And so rather than using checkAce (card,deck,ace), you use check_ace(card, deck, ace). In check_ace, rather than manually checking if card is equal to something, and then if it's not you check if it's equal to something else. Just check if it's in an object. For example you can use 'a' in ('a', 'b'). In read_file, you should use a with statement, it mostly comes down to correctly closing the file. If you wish to know more you can read another one of my answers. In read_file, you may want to use a list comprehension, rather than manually building a list. This is as list comprehensions are simpler to read. For example [i + 1 for i in range(10)] would return all the numbers from 1 to 10 inclusive. I'd recommend that you make your functions have as close to one responsibility each. And so in check_bust, I'd highly recommend that you remove the print. Allowing for a simple single line function. In hand_value_calc, you have about one hundred lines of if a == b[i]: c += mutate(i). There are a couple of problems with this: The variable card is overwritten by deck[index]. This means that your ifs are mostly useless. You know what index is, however you manually iterate all values of it. Instead just calculate it. Take min(9, random.randint(0, 51) % 13) + 1. Finally this doesn't remove a card from the deck, and so multiple users can get the same card. And so, for all bar the last error I raised, you can reduce your functions to these: def read_file(filename): with open(filename, 'r') as file: return [ line.strip().split(',')[0] for line in file ] def check_ace (card, deck, ace): return card, card in {deck[0], deck[13], deck[26], deck[39]} def hand_value_calc(card, hand, deck): index = random.randint(0, 51) return deck[index], hand + min(9, index % 13) + 1 def check_bust (hand_value): return hand_value > 21 I would go through your code more, however, there are some major problems with your code. Instead I'd highly recommend rethinking how you handle the deck and cards. They should probably both be custom classes, which allows for easier to read code. I'd also highly recommend that you allow the user to just play the game, and for your program to care about scoring. Why is the first question you're asked if you draw an ace be: You have been dealt an ace. The ace can be valued one, or eleven. Which value do you want? I, the user, just want to play, and to assign the ace a specific value at a later date. At the beginning I may want the ace to be an 11, however, I later may want it to be a 1. The way I'd go about doing this, is to give cards names, 'Ace of Spades', and also give them the possibility of multiple values, 1 and 11. This allows the Aces to work correctly. We should also make a 'card holder', with some helper functions such as values. This can then loop through all the cards in the holder, and return all the combinations of values each card can have. This can be constructed by using: from collections import deque class Card: def __init__(self, name, value): self.name = name if isinstance(value, int): self.value = [value] else: self.value = value def _perms(prevs, list): if not list: yield prevs return group = list.popleft() for item in group: yield from _perms(prevs + [item], list) list.appendleft(group) def perms(list): yield from _perms([], deque(list)) class CardHolder(list): def values(self): return perms(card.value for card in self) After this, you can focus on what the AI does, and also allow users to enter input. This should have a common 'action phase', but different 'pick phases'. For example a very simple 'build' and 'pick phase' could be: # make deck deck = CardHolder([ Card('Ace of Spades', [1, 11]), Card('Two of Spades', 2), ... Card('King of Spades', 10), ... ]) # build initial hand hand = CardHolder([ deck[0], deck[12] ]) # simple AI pick phase if (any(sum(value) == 21 for value in hand.values()) or all(sum(value) > 15 for value in hand.values())): command = 'stand' else: command = 'hit' A: There's a lot to change in this code. So much so, that I'll just start with a few items. First, you read in something from "deck.txt" but it's not clear what. I'd suggest that you eliminate this entirely. Just hard-code the values in your program - a deck of cards isn't likely to change very much in the next year or two. Also, you don't validate the deck you read in. You just assume it has the right size and contents. That's super bogus, since users love to mess with configuration files. If you're going to read in the deck, you'll need to add some validation code. Next, the card valuation (HandValueCalc): this is nuts. Look up the .index() method and build a parallel list of values. Or do the math: j = index modulo 13, then j if j < 10 else 10. Finally, I'll suggest that you break up the huge block of code at the bottom of the file into some sensible functions. A main game function, some "turn" functions, etc. See if you can chop off a bunch of lines, update your question, and we'll try again.
{ "pile_set_name": "StackExchange" }
Q: Tableau server Map Cache zooming I have a dashboard with custom geocoding uploaded to the tableau server, The dashboard works fine in the Desktop but take 12secs to execute each query/filter/zoom. When I see the networks i see there is a XHR request each time with takes the greatest time with high TTFB time. Can this be improved by any method ? Can using nginx compression and load balancing increase the speed ? Will additional layer of cloudflare caching will help ? A: I haven't worked with Tableau Server so far, but if the TTFB has a high value, that your server needs that much time to process your data. Load balancing doesn't speed up a server, it just passes each request to a different server, but the TTFB for a single Request won't be faster. I assume that only better server hardware can lower the TTFB. Or maybe a Tableau Cluster.
{ "pile_set_name": "StackExchange" }
Q: How to not draw zero values on a linechart while showing their X axis values on MPAndroidChart? I'm using MPAndroidChart to display my data in a line graph. For each date I have its own value. This works just fine. What I want to do now is to not draw the 0 values, but instead draw the line between 2 adjacent non-zero values (like a trend-line), while keep showing the dates on the x-axis for the zero values. My current graph: The desired graph should look similar to this graph: How can I achieve this behavior? A: I'm posting my friend's solution here (worked like a charm): Create a dataset with 0 values. Draw it but with line of transparent color. Create a dataset without 0. Draw it with the color that you need. Put (1) and (2) on the same LineChart. It will give you an x axis with x values where there are 0 values but will not draw a line for them. The second dataset will show the line of data points without the 0 values.
{ "pile_set_name": "StackExchange" }
Q: How to make org-protocol work? I tried the instructions here - I am using firefox on Lubuntu (openbox). But I get the error "Firefox doesn't know how to open this address, because the protocol (org-protocol) isn't associated with any program". How should I fix this? A: The following steps for setting up org-protocol work with Ubuntu 16.04 and presumably later versions. Org-mode is assumed to have already been set-up (and installed using apt-get install org-mode or via the ELPA repository). Set-up 1) Add .desktop file Create and save a file called org-protocol.desktop to ~/.local/share/applications containing: [Desktop Entry] Name=org-protocol Exec=emacsclient %u Type=Application Terminal=false Categories=System; MimeType=x-scheme-handler/org-protocol; Then run: $ update-desktop-database ~/.local/share/applications/ This step makes Firefox aware that "org-protocol" is a valid scheme-handler or protocol (by updating ~/.local/share/applications/mimeinfo.cache), and causes Firefox to prompt for a program to use when opening these kinds of links. 2) Add config settings to ~/.emacs.d/init.el (or ~/.emacs) file Have the following settings in your emacs configuration file: (server-start) (require 'org-protocol) Also add some template definitions to the configuration file, for example: (setq org-protocol-default-template-key "l") (setq org-capture-templates '(("t" "Todo" entry (file+headline "/path/to/notes.org" "Tasks") "* TODO %?\n %i\n %a") ("l" "Link" entry (file+olp "/path/to/notes.org" "Web Links") "* %a\n %?\n %i") ("j" "Journal" entry (file+datetree "/path/to/journal.org") "* %?\nEntered on %U\n %i\n %a"))) Now run emacs. 3) Create your notes.org file Assuming you use the capture templates defined in step 2, you will need to prepare a notes.org file at the location you specified in step 2. You must create this file -- if it is not created along with the headlines specified in step 2, org-mode will just give a warning when you try to capture web-pages. So, given the capture templates from step 2, notes.org should contain the following: * Tasks * Web Links 4) Add bookmarklet(s) to Firefox Save bookmark to toolbar containing something like the following as the location: javascript:location.href='org-protocol://capture?template=l&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title)+'&body='+encodeURIComponent(window.getSelection()) If you are using an older version of org-mode, you may need to use the following instead: javascript:location.href='org-protocol://capture://l/'+encodeURIComponent(location.href)+'/'+encodeURIComponent(document.title)+'/'+encodeURIComponent(window.getSelection()) Notice the 'l' (lowercase L) in the above URL -- this is what chooses the capture template (automatically) -- it is the key one would normally have to press when capturing with org-mode via C-c c. When you click on this bookmarklet, Firefox will ask what program to use to handle the "org-protocol" protocol. You can simply choose the default program that appears ("org-protocol"). Using it (Optionally) select some text on a webpage you're viewing in Firefox. When you click on the bookmarklet, the link and selected text will be placed in the emacs capture buffer. Go to emacs, modify the capture buffer as desired, and press C-c C-c to save it. A: These instructions are more up-to-date than the ones above. Add protocol handler Create file ~/.local/share/applications/org-protocol.desktop containing: [Desktop Entry] Name=org-protocol Exec=emacsclient %u Type=Application Terminal=false Categories=System; MimeType=x-scheme-handler/org-protocol; Note: Each line's key must be capitalized exactly as displayed, or it will be an invalid .desktop file. Then update ~/.local/share/applications/mimeinfo.cache by running: On GNOME: update-desktop-database ~/.local/share/applications/ On KDE: kbuildsycoca4 Configure Emacs Init file Add to your Emacs init file: (server-start) (require 'org-protocol) Capture template You'll probably want to add a capture template something like this: ("w" "Web site" entry (file+olp "/path/to/inbox.org" "Web") "* %c :website:\n%U %?%:initial") Note: Using %:initial instead of %i seems to handle multi-line content better. This will result in a capture like this: \* [[http://orgmode.org/worg/org-contrib/org-protocol.html][org-protocol.el – Intercept calls from emacsclient to trigger custom actions]] :website: [2015-09-29 Tue 11:09] About org-protocol.el org-protocol.el is based on code and ideas from org-annotation-helper.el and org-browser-url.el. Configure Firefox Expose protocol-handler On some versions of Firefox, it may be necessary to add this setting. You may skip this step and come back to it if you get an error saying that Firefox doesn't know how to handle org-protocol links. Open about:config and create a new boolean value named network.protocol-handler.expose.org-protocol and set it to true. Note: If you do skip this step, and you do encounter the error, Firefox may replace all open tabs in the window with the error message, making it difficult or impossible to recover those tabs. It's best to use a new window with a throwaway tab to test this setup until you know it's working. Make bookmarklet Make a bookmarklet with the location: javascript:location.href='org-protocol://capture://w/'+encodeURIComponent(location.href)+'/'+encodeURIComponent(document.title)+'/'+encodeURIComponent(window.getSelection()) Note: The w in the URL chooses the corresponding capture template. You can leave it out if you want to be prompted for the template. When you click on this bookmarklet for the first time, Firefox will ask what program to use to handle the org-protocol protocol. If you are using Ubuntu 12.04, you must add the /usr/bin/emacsclient program, and choose it. With Ubuntu 12.10 or later, you can simply choose the default program that appears (org-protocol). You can select text in the page when you capture and it will be copied into the template, or you can just capture the page title and URL. Pentadactyl If you're using Pentadactyl, you can map key sequences something like this: map cc -javascript location.href='org-protocol://capture://w/'+encodeURIComponent(content.location.href)+'/'+encodeURIComponent(content.document.title)+'/'+encodeURIComponent(content.document.getSelection()) Note: The JavaScript objects are slightly different for running from Pentadactyl. You might also want to add one for the `store-link` sub-protocol, like: map cl -javascript location.href='org-protocol://store-link://'+encodeURIComponent(content.location.href)+'/'+encodeURIComponent(content.document.title) Capture script You may want to use this script to capture input from a terminal, either as an argument or piped in: #!/bin/bash if [[ $@ ]] then data="$@" else data=$(cat) fi if [[ -z $data ]] then exit 1 fi encoded=$(python -c "import sys, urllib; print urllib.quote(' '.join(sys.argv[1:]), safe='')" "${data[@]}") # "link" and "title" are not used, but seem to be necessary to get # $encoded to be captured emacsclient "org-protocol://capture://link/title/$encoded" Then you can capture input from the shell like this: tail /var/log/syslog | org-capture org-capture "I can capture from a terminal!" Note: I edited all of this updated and expanded information into the answer above, but the edit was rejected because it "deviates from the original intent of the post" and doesn't "preserve the goals of the post's owner". I'm afraid the wonks have come over from Wikipedia, who would rather throw away useful, up-to-date information (the original answer is 3 years old) and take for granted contributors' valuable time (I've just spent several hours this morning setting up org-protocol and finding out the hard way that the other answer is out-of-date). So here is a new, separate answer that obsoletes the other one. I guess I should just post this on a blog somewhere, since Stack doesn't want to be up-to-date and useful anymore.
{ "pile_set_name": "StackExchange" }
Q: ¿Cómo consumo este Web Service? Tratando de aprender cómo funciona y el consumo de un Web Service he dado muchas vueltas y los ejemplos que encuentro no logro adaptarlos y hacerlos funcionar a lo que quiero. Tengo el siguiente Web Service y no se muy bien cómo puedo hacer para consumirlo [WebService(Namespace = "http://www.mysite.com.co/WS/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class ServicioSUCIS : System.Web.Services.WebService { public ServicioSUCIS() { //Elimine la marca de comentario de la línea siguiente si utiliza los componentes diseñados //InitializeComponent(); } [WebMethod] [SoapDocumentMethod (Use = SoapBindingUse.Literal)] public DataTable consultaIndividualSUCIS(int tipoId, int numId) { try { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("SELECT tipoCodigoEntidad, Nombre, estadoAutorizacion, tipoIntermediario, indicadorVinculado, tipoIdEntidadVincula, numIdEntidadVincula, nombreEntidadVincula, fechaVinculacion, fechaDesvinculacion, organismoAutorizado, fechaIniAcreditacion, fechaFinAcreditacion, ramosAutorizados FROM Idoneidad_Funcionarios WHERE tipoId = @tipoId AND numId = @numId")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Parameters.AddWithValue("@tipoid", tipoId); // <-- Este es el parámetro de SQL que estás recibiendo cómo parámetro en tu método cmd.Parameters.AddWithValue("@numId", numId); // <-- Este es el parámetro de SQL que estás recibiendo cómo parámetro en tu método cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { dt.TableName = "Idoneidad_Funcionarios"; sda.Fill(dt); return dt; } } } } } catch (Exception ex) { lblError.Text = ex.Message; throw; } } } Eso me arroja el siguiente resultado: A: La solución de @NeKSV sirve para webservices WCF y de ese tipo. Para los webservices de .net clasicos, debes hacer los siguiente: En el explorador de soluciones de la aplicación donde quieras consumir el webservices, pulsas con el boton derecho en Referencias y te aparecerá esta ventana: Aqui deberás pulsar en Avanzadas... en la parte inferior, y te aparecerá lo siguiente: Como ves, en la parte inferior ya tienes la opción Agregar referencia web.... Pulsando te aparecerá la siguiente ventana: Aqui pegas tu URL y le das a Agregar referencia y ya tienes añadido el webservice. Por último, en tu código no tienes mas que crear una instancia de tu webservice, algo asi: tunombredereferencia.ServicioSUCIS ws = new tunombredereferencia.ServicioSUCIS(); ws.Credentials = System.Net.CredentialCache.DefaultCredentials; ws.PreAuthenticate = true; ws.ConsultaIndividualSUCIS(tipoID, numID);
{ "pile_set_name": "StackExchange" }
Q: How to find the asymptotes of a square root function? While working out some examples I'm trying to solve, I stumbled on a question that asks to find the asymptotes of the following function: $$y = \sqrt{x^2 + 3}$$ For rational functions I was thought to perform long division for horizontal/oblique asymptotes which in this case there are 2 oblique. How to I find these asymptotes without performing the limits method since I have no idea how to do it and we weren't thought that method in class. Thanks A: Probably what the instructor wants you to realize is that when $x$ is very large in magnitude (either positive or negative), your function is approximately $\sqrt{x^2}=|x|$. If you graph your function and $|x|$, you will see the root function approaches the absolute value function in the long term. This is analogous to what happens when rational functions have "oblique" asymptotes, as they are called in high school. (I highly doubt you'll ever hear anyone outside of high school refer to such things.) For example, the function $$f(x)=\frac{x^3}{x^2-1}$$ is approximately $x^3/x^2=x$ when $x$ is large in magnitude, so in the long run this rational function approaches the line $y=x$. The important idea here is to think approximately. Another approach is to view your function as the upper branch of a hyperbola, but this won't make sense if you haven't studied conic sections.
{ "pile_set_name": "StackExchange" }
Q: Split values by hyphen that exist in the same row and integrate with a INNER JOIN? A table in my database holds values as below, TBLFlow FlowId FlowName ProcessId ------------------------------------------------ F00 Flow1 PID01-PID02-PID03 F01 Flow2 PID01-PID03-PID02 The Name of the process are listed in another table as below, TBLProcess ProcessId ProcessName --------------------------- PID01 Process1 PID02 Process2 PID03 Process3 Now, I would like to split the values in the table 'TBLFlow' in order to get their name from the table 'TBLProcess' by perform a join(preferably 'Inner Join') between two tables. Finally, when I execute the query, I would like the result to be as below, FlowId FlowName ProcessId ProcessName ------------------------------------------------------------------------------ F01 Flow1 PID01-PID02-PID03 Process1-Process2-Process3 F01 Flow1 PID01-PID03-PID02 Process1-Process3-Process2 I am working on SQL Server 2008 and would like to do this operation in a single Stored Procedure.Could you help me on the query to written in the Stored Procedure. EDIT: Table 'TBLFlow' can be recontructed as below, TBLFlow FlowId FlowName ProcessId ------------------------------------------------ F00 Flow1 PID01 F00 Flow1 PID02 F00 Flow1 PID03 F01 Flow2 PID01 F01 Flow2 PID03 F01 Flow2 PID02 A: I imagined such a monster DECLARE @TBLFlow table (FlowId varchar(20), FlowName varchar(100), ProcessId varchar(1000)) DECLARE @TBLProcess table (ProcessId varchar(20), ProcessName varchar(100)) insert into @TBLFlow values ('F00','Flow1','PID01-PID02-PID03'), ('F01','Flow2','PID01-PID03-PID02') insert into @TBLProcess values ('PID01','Process1'), ('PID02','Process2'), ('PID03','Process3') ;with c as ( select 1 as rn, FlowId, FlowName, CHARINDEX('-',ProcessId,1) as Pos, case when CHARINDEX('-',ProcessId,1)>0 then SUBSTRING(ProcessId,1,CHARINDEX('-',ProcessId,1)-1) else ProcessId end as value, case when CHARINDEX('-',ProcessId,1)>0 then SUBSTRING(ProcessId,CHARINDEX('-',ProcessId,1)+1,LEN(ProcessId)-CHARINDEX('-',ProcessId,1)) else '' end as ProcessId from @TBLFlow union all select rn + 1 as rn, FlowId, FlowName, CHARINDEX('-',ProcessId,1) as Pos, case when CHARINDEX('-',ProcessId,1)>0 then SUBSTRING(ProcessId,1,CHARINDEX('-',ProcessId,1)-1) else ProcessId end as Value, case when CHARINDEX('-',ProcessId,1)>0 then SUBSTRING(ProcessId,CHARINDEX('-',ProcessId,1)+1,LEN(ProcessId)-CHARINDEX('-',ProcessId,1)) else '' end as ProcessId from c where LEN(ProcessId)>0 ) select f.FlowId, f.FlowName, f.ProcessId, stuff( ( select '-'+p.ProcessName from c inner join @TBLProcess p on p.ProcessId=c.value where c.flowid=f.flowid order by c.rn FOR XML PATH('') ), 1, 1, '' ) as ProcessName from @TBLFlow f
{ "pile_set_name": "StackExchange" }
Q: in nodeJs request, how can we get the html after an ajax loading? doing var page_url = "http://skiferie.danskbilferie.dk/sidste_chance_uge7_norge_sverige.html"; http.get(page_url, (http_res) => { var data = ""; http_res.on("data", function (chunk) { data += chunk; }); http_res.on("end", function () { resolve({data}); }); }); get's the correct HTML from that page, but how can I wait for the table of deals to be filled? as that page only fills the data I need after it loads, calling an ajax method to fill the data in... is there a wait for me to wait for such action to be completed? A: To wait until ajax will be loaded, you need to add timeout for your request. Your goal is to somehow tell script to wait for some period of time and than get rendered html. You can implement such behavior as @GabrielBleu said, with puppeteer and here is nice tutorial with example: tutorial Or with webdriver or you can try with this resource
{ "pile_set_name": "StackExchange" }
Q: APC not recommended for production? I have started having problems with my VPS in the way that it would faill to serve the pages on all the websites. It just showed a blank page, or offered to download the php file ( luckily the code was not in the download file :) ). The server was still running, but this seemed to be a problem with PHP, since i could login into WHM. If i did a apache restart, the sites would work again. After some talks with the server support they told me this is a problem with the APC extension witch they considered to be old and not recommended for production servers. So they removed it for now, to see if the same kind of fails would continue to appear. I haven't read anywhere that APC could have some problems or that its not always recommended to use, quite the contrary ... everywhere people are saying to always use it. The APC extension was installed ssh and is the latest version. Edit: They also dont recomend MemCache and say that a more reliable extension would be eAccelerator A: Um APC is current tech and almost a must for any performant PHP site. Not only that but it will ship as standard in PHP 6 (rather than being an optional module like it is now). I don't know what your issue is/was but it's not APC being outdated or old tech. A: I run several servers myself and the only time I have ever had trouble with APC was when trying to run it concurrently with Zend Optimizer. They don't work together so if I must use Optimizer (like if some commercial, third-party code requires it) I run eAccelerator instead of APC. Effectively 6 of one, half-dozen of another when it comes to performance but I really doubt APC is the problem here.
{ "pile_set_name": "StackExchange" }
Q: XSLT3 Issue with Lookup Value | Streaming I have a merged report data(data comes from two sources)as an input file and I needed to lookup a value based on a key. Currently my code is returning incorrectly looking up values. Since the size of the input data is expected to be large, I would like to use streaming for better performance. Here is my input xml Element Number'is the key to lookup. Xpath is 'Batch/Workers/Number` Lookup Phone element based on Number' . Xpath isMergedOutput/Data/Row/Phone` Sample Input <?xml version="1.0" encoding="UTF-8"?> <MergedOutput> <Data> <Row> <Employee_Batch_Id>12567</Employee_Batch_Id> <Phone>FirstEmp8013457896</Phone> <Assignment_Id>5046150263</Assignment_Id> </Row> <Row> <Employee_Batch_Id>12568</Employee_Batch_Id> <Phone>SecondEmp7853457896</Phone> <Assignment_Id>5046150263</Assignment_Id> </Row> </Data> <Batch> <Workers> <Number>12567</Number> <Contact>Work7864532890</Contact> </Workers> <Workers> <Number>12568</Number> <Contact>Work6782340167</Contact> </Workers> </Batch> </MergedOutput> Current XSLT3 code <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:map="http://www.w3.org/2005/xpath-functions/map" exclude-result-prefixes="xs r1 r2 map" version="3.0"> <xsl:output method="xml" indent="yes"/> <xsl:mode streamable="yes" on-no-match="shallow-skip" use-accumulators="#all"/> <xsl:accumulator name="FirstReportLookupValuePhone" as="xs:string" initial-value="''" streamable="yes"> <xsl:accumulator-rule match="Phone/text()" select="."/> </xsl:accumulator> <xsl:accumulator name="EmployeeIDLookup" as="map(xs:string,xs:string)" initial-value="map{}" streamable="yes"> <xsl:accumulator-rule match="Employee_Batch_Id/text()" select="map:put($value, string(.), accumulator-before('FirstReportLookupValuePhone'))"/> </xsl:accumulator> <xsl:template match="Batch"> <Workers> <xsl:apply-templates select="Workers"/> </Workers> </xsl:template> <xsl:template match="Workers"> <xsl:variable name="vWorkers" select="copy-of()"/> <xsl:variable name="vMappedWorker" select="accumulator-after('EmployeeIDLookup')( normalize-space($vWorkers/Number))"/> <Worker> <WorkerID><xsl:value-of select="$vWorkers/Number"/></WorkerID> <Work_Contact_Number><xsl:value-of select="$vWorkers/Contact"/></Work_Contact_Number> <Home_Contact_Number><xsl:value-of select="$vMappedWorker"/></Home_Contact_Number> </Worker> </xsl:template> </xsl:stylesheet> Current output <?xml version="1.0" encoding="UTF-8"?> <Workers> <Worker> <WorkerID>12567</WorkerID> <Work_Contact_Number>Work7864532890</Work_Contact_Number> <Home_Contact_Number/> <!-- Value is empty, Expected value is FirstEmp8013457896 --> </Worker> <Worker> <WorkerID>12568</WorkerID> <Work_Contact_Number>Work6782340167</Work_Contact_Number> <Home_Contact_Number>FirstEmp8013457896</Home_Contact_Number> <!-- Incorrect Value, Expected value is SecondEmp7853457896 --> </Worker> </Workers> Expected Output <?xml version="1.0" encoding="UTF-8"?> <Workers> <Worker> <WorkerID>12567</WorkerID> <Work_Contact_Number>Work7864532890</Work_Contact_Number> <Home_Contact_Number>FirstEmp8013457896</Home_Contact_Number> </Worker> <Worker> <WorkerID>12568</WorkerID> <Work_Contact_Number>Work6782340167</Work_Contact_Number> <Home_Contact_Number>SecondEmp7853457896</Home_Contact_Number> </Worker> </Workers> Please could someone help me figure out how could i get the desired output? A: The problem is that the accumulator matching Employee_Batch_ID tries to use the accumulator value for Phone; but because the Employee_Batch_ID appears before the Phone element, the Phone accumulator value isn't available yet. I think you have to reverse the logic: when you encounter an Employee_Batch_ID/text(), save the ID value as a string in accumulator A; when you encounter a Phone/text(), add an ID=phone entry to a map held in Accumulator B.
{ "pile_set_name": "StackExchange" }
Q: Can a LDAP 3 client access a LDAP 2 server? I'm writing a PHP client that would allow access to any LDAP server. For various reasons I'd like to be able to access both LDAP 2 and 3 servers. If I don't make use of any LDAP 3 specific functionality, would it be a reasonable thing to use an LDAP 3 client to access both LDAP 2 and 3 servers? This would allow me to use the same client implementation for any LDAP server. Is there any better way to go about this? A: Probably not very well. You can use a V2 client with a V3 server. Be aware that on a search request, however, the V3 server may send back data in the full range of UTF-8 format, while a V2 client may be only able to handle data in the IA5 character set. There are many differences in V2 vs V3. And as EJP mentioned, it is difficult to even find a LDAP server implementation that does not support v3. Fianlly v2 has been depricated since 2003 https://tools.ietf.org/html/rfc3494. -jim
{ "pile_set_name": "StackExchange" }
Q: JAVA - Xuggler - Play video while combining an MP3 audio file and a MP4 movie Using JAVA and Xuggler - the following code combines an MP3 audio file and a MP4 movie file and outputs a combined mp4 file. I want outputVideo file should be play automatically while combining audio and video file. String inputVideoFilePath = "in.mp4"; String inputAudioFilePath = "in.mp3"; String outputVideoFilePath = "out.mp4"; IMediaWriter mWriter = ToolFactory.makeWriter(outputVideoFilePath); IContainer containerVideo = IContainer.make(); IContainer containerAudio = IContainer.make(); // check files are readable if (containerVideo.open(inputVideoFilePath, IContainer.Type.READ, null) < 0) throw new IllegalArgumentException("Cant find " + inputVideoFilePath); if (containerAudio.open(inputAudioFilePath, IContainer.Type.READ, null) < 0) throw new IllegalArgumentException("Cant find " + inputAudioFilePath); // read video file and create stream IStreamCoder coderVideo = containerVideo.getStream(0).getStreamCoder(); if (coderVideo.open(null, null) < 0) throw new RuntimeException("Cant open video coder"); IPacket packetvideo = IPacket.make(); int width = coderVideo.getWidth(); int height = coderVideo.getHeight(); // read audio file and create stream IStreamCoder coderAudio = containerAudio.getStream(0).getStreamCoder(); if (coderAudio.open(null, null) < 0) throw new RuntimeException("Cant open audio coder"); IPacket packetaudio = IPacket.make(); mWriter.addAudioStream(1, 0, coderAudio.getChannels(), coderAudio.getSampleRate()); mWriter.addVideoStream(0, 0, width, height); while (containerVideo.readNextPacket(packetvideo) >= 0) { containerAudio.readNextPacket(packetaudio); // video packet IVideoPicture picture = IVideoPicture.make(coderVideo.getPixelType(), width, height); coderVideo.decodeVideo(picture, packetvideo, 0); if (picture.isComplete()) mWriter.encodeVideo(0, picture); // audio packet IAudioSamples samples = IAudioSamples.make(512, coderAudio.getChannels(), IAudioSamples.Format.FMT_S32); coderAudio.decodeAudio(samples, packetaudio, 0); if (samples.isComplete()) mWriter.encodeAudio(1, samples); } coderAudio.close(); coderVideo.close(); containerAudio.close(); containerVideo.close(); mWriter.close(); If anybody knows play video file automatically when combining audio and video file using java xuggler.. please please help me..It would be really appreciable.. A: Here is the complete code. I also did some changes: if audio is longer, then write the rest separately, and added progress of audio and video in title bar. You may need to check if there is really video or audio stream in your files to prevent errors. import com.xuggle.mediatool.IMediaWriter; import com.xuggle.mediatool.ToolFactory; import com.xuggle.xuggler.Global; import com.xuggle.xuggler.IAudioSamples; import com.xuggle.xuggler.IContainer; import com.xuggle.xuggler.IPacket; import com.xuggle.xuggler.IStreamCoder; import com.xuggle.xuggler.IVideoPicture; import com.xuggle.xuggler.video.ConverterFactory; import com.xuggle.xuggler.video.IConverter; import java.awt.Graphics; import java.awt.Image; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.SwingUtilities; /** * * @author Pasban */ public class MergeVideoAudio extends JDialog { Image image; private double video_duration = 0.00001, video_read = 0, audio_duration = 0.00001, audio_read = 0; public static void main(String[] args) { final MergeVideoAudio merge = new MergeVideoAudio(); Thread thread = new Thread() { @Override public void run() { merge.perform("y:/a.mp4", "y:/b.mp3", "y:/c.mp4"); merge.setVisible(false); System.exit(0); } }; thread.run(); } public void perform(String path_video, String path_audio, String path_output) { IMediaWriter mWriter = ToolFactory.makeWriter(path_output); IContainer containerVideo = IContainer.make(); IContainer containerAudio = IContainer.make(); // check files are readable if (containerVideo.open(path_video, IContainer.Type.READ, null) < 0) { throw new IllegalArgumentException("Cant find " + path_video); } if (containerAudio.open(path_audio, IContainer.Type.READ, null) < 0) { throw new IllegalArgumentException("Cant find " + path_audio); } // read video file and create stream IStreamCoder coderVideo = containerVideo.getStream(0).getStreamCoder(); if (coderVideo.open(null, null) < 0) { throw new RuntimeException("Cant open video coder"); } int width = coderVideo.getWidth(); int height = coderVideo.getHeight(); this.setSize(width, height); this.setLocationRelativeTo(null); this.setVisible(true); // read audio file and create stream IStreamCoder coderAudio = containerAudio.getStream(0).getStreamCoder(); if (coderAudio.open(null, null) < 0) { throw new RuntimeException("Cant open audio coder"); } IPacket packet = IPacket.make(); mWriter.addAudioStream(1, 0, coderAudio.getChannels(), coderAudio.getSampleRate()); mWriter.addVideoStream(0, 0, width, height); video_duration = 0.000001 + (containerVideo.getDuration() == Global.NO_PTS ? 0 : (containerVideo.getDuration() / 1000.0)); audio_duration = 0.000001 + (containerAudio.getDuration() == Global.NO_PTS ? 0 : (containerAudio.getDuration() / 1000.0)); while (containerVideo.readNextPacket(packet) >= 0) { video_read = (packet.getTimeStamp() * packet.getTimeBase().getDouble() * 1000); // video packet IVideoPicture picture = IVideoPicture.make(coderVideo.getPixelType(), width, height); coderVideo.decodeVideo(picture, packet, 0); if (picture.isComplete()) { mWriter.encodeVideo(0, picture); IConverter converter = ConverterFactory.createConverter(ConverterFactory.XUGGLER_BGR_24, picture); this.setImage(converter.toImage(picture)); this.setProgress(video_duration, video_read, audio_duration, audio_read); } // audio packet containerAudio.readNextPacket(packet); audio_read = (packet.getTimeStamp() * packet.getTimeBase().getDouble() * 1000); IAudioSamples samples = IAudioSamples.make(512, coderAudio.getChannels(), IAudioSamples.Format.FMT_S32); coderAudio.decodeAudio(samples, packet, 0); if (samples.isComplete()) { mWriter.encodeAudio(1, samples); this.setProgress(video_duration, video_read, audio_duration, audio_read); } } //write the remaining audio, if your audio is longer than your video while (containerAudio.readNextPacket(packet) >= 0) { audio_read = (packet.getTimeStamp() * packet.getTimeBase().getDouble() * 1000); IAudioSamples samples = IAudioSamples.make(512, coderAudio.getChannels(), IAudioSamples.Format.FMT_S32); coderAudio.decodeAudio(samples, packet, 0); if (samples.isComplete()) { mWriter.encodeAudio(1, samples); this.setProgress(video_duration, video_read, audio_duration, audio_read); } } coderAudio.close(); coderVideo.close(); containerAudio.close(); containerVideo.close(); mWriter.close(); } public MergeVideoAudio() { this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public void setImage(final Image image) { SwingUtilities.invokeLater(new Runnable() { public void run() { MergeVideoAudio.this.image = image; repaint(); } }); } @Override public synchronized void paint(Graphics g) { if (image != null) { g.drawImage(image, 0, 0, null); } } public static String convertDurationHMSm(double time) { long elapsed = (long) (time * 1000); long duration = elapsed / 1000; long ms = elapsed % 1000; return String.format("%02d:%02d:%02d.%02d", duration / 3600, (duration % 3600) / 60, (duration % 60), ms / 10); } private void setProgress(double video_duration, double video_read, double audio_duration, double audio_read) { this.setTitle("Video: " + (int) (100 * video_read / video_duration) + "%, Audio " + (int) (100 * audio_read / audio_duration) + "%"); } } If you need to show frames based on video frame rate, then add the following code after every time you read your video packet, or else leave it for fast merging. try { Thread.sleep((long) (1000 / coderVideo.getFrameRate().getDouble())); } catch (InterruptedException ex) { ex.printStackTrace(); }
{ "pile_set_name": "StackExchange" }
Q: How to avoid duplicate activities when resuming from home screen i'm new to Android and java. What i have is an activity that has a handler (h_main) and a runable (r_test). * The runable is called in the activities onStart(). * The runable calls a function that gets me feedback via Log.d(TAG,"tick.."). * At the end of the function the runable get called again with delay of 1000ms. That way i got my fuction called every second what works fine. But when i return to Androids home screen and return to my app, i get two 'ticks' per second. It apears that my activity is running twice now. How can i avoid this? @Override protected void onStart() { super.onStart(); Log.d(TAG,"onStart()"); h_main.postDelayed(r_test, 1000); } public void timer_runable() { Log.d(TAG,"tick.."); h_main.postDelayed(r_test, 1000); } A: The solution is to cancle your pending runnable in onPause(): @Override protected void onPause() { super.onPause(); h_main.removeCallbacks(r_test); }
{ "pile_set_name": "StackExchange" }
Q: Redirect non-www to www with Node.js and Express I am serving a static directory like so: var app = express.createServer(); app.configure(function(){ app.use(express.static(__dirname + '/public')); }); So I am not using routes at all. I would like to redirect example.com to www.example.com, is this possible using Express? A: The following code preserve path while redirecting Ex: http://foo.com/foo to http://www.foo.com/foo var app = express.createServer(); self.app.all(/.*/, function(req, res, next) { var host = req.header("host"); if (host.match(/^www\..*/i)) { next(); } else { res.redirect(301, "http://www." + host + req.url); } }); app.use('/',express.static('public')); A: Yes. This should do it. var express = require("express"); var app = express.createServer(); var port = 9090; app.all(/.*/, function(req, res, next) { var host = req.header("host"); if (host.match(/^www\..*/i)) { next(); } else { res.redirect(301, "http://www." + host); } }); app.use(express.static(__dirname + "/public")); app.listen(port); A: Alternatively, you can use a ready-made module for Express that does exactly what you want, e.g. node-force-domain. See https://github.com/goloroden/node-force-domain for details.
{ "pile_set_name": "StackExchange" }
Q: Is Revelation a good substitute for a self-destruct device? Over the course of the game, you get access to a virus called Revelation that can be used to destroy target systems (or rather to disable them for a while). Should you ever be traced and have the authorities break into your server room (as indicated by the motion sensor), will running Revelation on your machine prevent you from losing money and reputation? A: It will, however it also spreads to other systems (apart from the first version), so if you're going for the good ending I'd advise against it. From an Uplink forum post: Q: I activated Revelation on my computer, how do I get it back??? A: Smart move. Well, you can't get it back - you have just ruined it. However, all your information is there - the account, the rating. So you just have to buy a new computer, and buy again all your hardware and software. Could be worse, however...
{ "pile_set_name": "StackExchange" }
Q: Read binary mode in python2.7 returns a 'str' type. Why is it so? My objective is to read a text (or) file byte by byte in Python. I came across few stack overflow questions: Reading binary file and looping over each byte and using the following method: with open("./test", "rb") as in_file: msg_char = in_file.read(1) print(type(msg_char)) And am geting the output as <type 'str'> I checked this on one other question Read string from binary file which says that read returns a string; in the sense "string of bytes". I am confused. Following is the question: Is "string of bytes" different from conventional strings (as used in C/C++ etc..). A: In Python 2 the differentiation between text and bytes isn't as well-developed as it is in Python 3, which has separate types - str for text, in which the individual items are Unicode characters, bytes for binary data, where the individual items are 8-bit bytes. Since Python 2 didn't have the bytes type it used strings for both types of data. Although the Unicode type was introduced into Python 2, no attempt was made to change the way files handled data, and decoding was left entirely to the programmer. Similarly in C, "string" originally meant string of bytes, then wide character types were introduced later as the developers realized text was rather different from bytes data. As a programmer you should always try to maintain separation between string data and the bytes that are used to represent it in a particular encoding. The simplest rule is "decode on input, encode on output' -- that way you know your text is using appropriate encodings.
{ "pile_set_name": "StackExchange" }
Q: When a request to a proxy times out, what happens if/when the destination server eventually gets around to responding? I'm trying to diagnose a web service that sits behind some load balancers and proxies. Under load, one of the servers along the way starts to return HTTP 504 errors, which indicates a gateway timeout. With that background out of the way, here is my question: When a proxy makes a request to the destination server, and the destination server receives the request but doesn't respond in time (thus exceeding the timeout), resulting in a 504, what happens when the destination server does eventually respond? Does it know somehow that the requestor is no longer interested in a response? Does it happily send a response with no idea that the gateway already sent HTTP error response back to the client? Any insight would be much appreciated. A: It's implementation-dependent, but any proxy that conforms to RFC 2616 section 8.1.2.1 should include Connection: close on the 504 and close the connection back to the client so it can no longer be associated with anything coming back from the defunct server connection, which should also be closed. Under load there is the potential for race conditions in this scenario so you could be looking at a bug in your proxy. If the client then wants to make further requests it'll create a new connection to the proxy which will result in a new connection to the backend.
{ "pile_set_name": "StackExchange" }
Q: Why does std::bind() tries to copy my object? I'm using VS2010. In the constructor of my non-compyable Scene class I have : auto& character_mgr = CharacterManager::Instance(); character_mgr.initialize(); character_mgr.add_observer( std::bind( &Scene::on_character_event, *this, std::placeholders::_1, std::placeholders::_2 ) ); Here add_observer is defined as : void add_observer( Observer observer ){ ... } with Observer defined as : typedef std::function< void ( CharacterEvent, const Character& ) > Observer; The problem is that the compiler tells me there is an attempt to copy my Scene, that I provided in the bind using *this, thinking it would keep a reference on it, not trying to copy it when I copy the functor generated by the binding. Why does it try to copy my object? Is it normal? How should I do to avoid the copy while providing the member function of my object? A: It's the default behaviour. To pass by reference, try using std::ref . A: To avoid copying, pass this instead of *this, or as the other answer, std::ref(*this). character_mgr.add_observer( std::bind( &Scene::on_character_event, this, std::placeholders::_1, std::placeholders::_2 ) ); Take a look at Using bind with pointers to members.
{ "pile_set_name": "StackExchange" }
Q: Symbol of computer science I'm programming a Website and wanted to include the symbol of computer science, but i couldn't find the symbol somewhere ... does someone know where i can find it? Do we have a symbol? for example psychology has a symobl: http://en.wikipedia.org/wiki/Psychology A: If you want to go with Greek letters then probably ϴ would be a good choice. Or perhaps just a Roman "Big O": O ?
{ "pile_set_name": "StackExchange" }
Q: PHP: How to Logout From API using JWT So I created an API using Token based authentication for Login, now I want to create the logout but I do not know how to go about it. The login process just uses the following steps: User passes Username and Password to server Server checks DB to ensure user is Valid Token is generated containing uid and other details Token is then passed to User who sends back to server whenever he makes a request Now I want user to logout, how do I go about it, I do not have power over the user Token anymore. A: I also come here in search of a solution, but after reading much I came to few conclusions or say possible situations. Edit Note:- Never store any potential information in token, as reading the data in token doesn't require the secret key. Secret Key is only for verifying signature of Base64 token. To check this out go to http://jwt.io and paste your token. I added this point because somewhere I saw a developer adding username and password of user in token. Please don't do things like this. 1.) Account logout event is initiated by client, if he wants to logout before expiry time of token. Solution:- Remove the token from every place in client side. It can be stored in DOM, or JavaScript Variable, or HTML key-pair storage, or session storage or cookies storage. Everywhere we can store a value in a browser, we have also rights to delete the values. Once the token is deleted from every corner of this world user is logged out. Caveat 1 in above solution What if user is logging out in emergency, like someone might have stollen the token. How to destroy the token? Answer is same as what will do if our secret key for JWT is stollen. We will quickly change the secret key and regenerate the tokens for logged in users. But in case of users what should we change?User ID( I will say no.). We should add a account locking mechanism similar to mechanism in Debit/Credit cards, where card is locked for 24 hours. But in our case we should have end period of account locking little more than the expiry time of token. 2.) Tokens are just like missiles, once fired we can not ask them to shut down. I am talking about ideal case, if you are storing the reference of fired token in database, than there is no point of using JWT. We can generate a token using any hash generation method. 3.) Set expiry time short. Renew without letting user notice this, a little before the previous token expire. Time can be around 20 seconds. Still you have to consider caveat 1, as any person having a genuine token can ask for fresh token. 4.) We can also add an field IP address in token and check if current IP address of users matches with the one used at the time of login or not. It prevents from remote hackers. 5.) Add a clearly visible Logout button in your user interface for preventing naive users, and guide users to logout from your application every time they are done with your application. 6.) Add a client type in your token meta. For mobile applications check HMAC or IMEI codes, instead of IP address as mobile applications require keep running session as no one wants his or her users to logout from their mobile applications. But compromiser can compromise IMEI and HMAC address although. But randomly using between HMAC, IMEI or any other available string can add a little more security. 7.) I will add more if get to know more such. Invalidating JSON Web Tokens this thread is also having many good inputs. As mentioned in comment under question.
{ "pile_set_name": "StackExchange" }
Q: Как вычислить разницу дней и часов между двумя введенными датами? Есть 4 поля EditText, где пользователь выбирает дату, время начала и дату, время окончания и поле TextView, куда нужно вывести данные о разнице дней между введенными датами: etDateStart = (EditText) findViewById(R.id.etDateStart); etTimeStart = (EditText) findViewById(R.id.etTimeStart); etDateEnd = (EditText) findViewById(R.id.etDateEnd); etTimeEnd = (EditText) findViewById(R.id.etTimeEnd); tvInfo = (TextView)findViewById(R.id.tvInfo); Как я могу посчитать эту разницу (нужны только дни и часы) и вывести инфу в TextView? A: Как пример: 1) Создаёте два экземпляра календаря. 2) Берёте в мс время. 3) Вычитаете. GregorianCalendar dateStart = new GregorianCalendar(...); GregorianCalendar dateEnd = new GregorianCalendar(...); // здесь у нас разница в миллисекундах int dif = dateEnd.getTimeInMillis() - dateStart.getTimeInMillis(); const final int HOUR = 3600 * 1000; const final int DAY = HOUR * 24; // здесь дни int days = dif / DAY; // здесь часы int hours = (dif - days * DAY) / HOUR; Что-то вроде того, на коленке набросал.
{ "pile_set_name": "StackExchange" }
Q: Webform variants as blocks Drupal 8.9, Webforms 5.x I have a load of forms that are all basically the same, except for the confirmation URL (a download link, essentially) and some minor tweaks to the handlers. In an effort to reduce duplication, I've been looking into the possibility of using variants for this. I can create all the variants easily enough, but I'm at a loss as to how to include these on the correct pages. The form itself is included in the layout of the content type as a block and I can specify a specific variant there via default submission data (as per image) but that's a single variant for the whole content type rather than a specific variant for a single page. What's the best way to do this? Is it actually possible with variants at all? Or perhaps there's some other solution I've missed A: So the eventual answer wasn't variants at all, but webform nodes. Inserting a webform block into the content type's layout enabled me to use the [webform-submission:source-entity:foo] tokens, which were exactly what I wanted. Important to note that you have to enable the "Webforms Node" extension for this (I've not seen this mentioned anywhere, so was confused about where the "References" tab was)
{ "pile_set_name": "StackExchange" }
Q: WPF - binding to a property in ViewModel and to other control In my WPF application (using MVVM) I have a CheckBox and a TextBlock. When the CheckBox is checked the value from the TextBlock will be saved. There is a binding from both controls to my ViewModel. Below simplified XAML: <StackPanel> <Label>Add to list</Label> <CheckBox IsChecked="{Binding Path=AddItem}"></CheckBox> <Label>Gross amount:</Label> <TextBlock Text="{Binding Path=Amount}"></TextBlock> </StackPanel> Now I would like to have the CheckBox checked when a user starts typing in the TextBlock. I know binding can do that but I already bind to a property in my ViewModel. How can I bind to a property in ViewModel and to other control? A: You should use the multibinding. Something like this: <CheckBox Content="CheckBox" HorizontalAlignment="Left" Margin="191,82,0,0" VerticalAlignment="Top"> <CheckBox.IsChecked> <MultiBinding Converter="{StaticResource checkConverter}"> <Binding Path="IsChecked"/> <Binding Path="UserStartedTyping"/> </MultiBinding> </CheckBox.IsChecked> </CheckBox> checkConverter is a MultiValueConverter that you need in order to decide what to do with the values you are binding with (such as &&, || etc.). public class CheckConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { return (bool)((bool)values[0] || (bool)values[1]); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { object[] splitValues = { value, false }; return splitValues; } } UserStartedTyping is a property in the ViewModel that would be set to true when KeyDown event is fired. Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: What reasons could there be for cement not setting? I'm writing a scene set on a construction site where the builders notice that the cement they pour is not setting: it just remains in its liquid state or it is taking a very long time to set. This is set in a world where there are mystical/magical/horrific anomalies of various kinds. So magical things can happen but I'm interested in what they might look like to a scientist or engineer who does not believe in magic. What scientific explanation could there be for this? I'm looking for some change in the world that would have the effect that cement would be prevented from setting. For example, if a particular chemical substance had its properties changed somehow or if the surrounding climatic conditions were altered somehow. A: Non-hydraulic cement will not set if it can't exchange water vapour and CO2 with the environment (or if water is replaced). Several oily and gelly substances exist that will form a thin film above or on the surface of a liquid and slow down evaporation and CO2 diffusion. "Slow down" is not the same thing as "prevent", though. To prevent it completely, you would need a film with the thickness and properties of clingy film, which would be really noticeable. Hydraulic cement will not be hindered by this, since it is self-reacting. For it, you would need some substance capable of blocking calcium silicates from reacting with water. Perhaps some soaps could do that. Or some lubricants could make the sludge appear not to be setting; it would rather collapse in a sort of useless gritty gruel. I know of none that would be water-souble though, or survive in the alkaline environment. Also microencapsulation of cement particles with hydrophobic compounds would work, but here we'd be talking about high-tech sabotage; also, the powdered cement properties (color, weight, fluidity, texture) would likely change drastically. Same goes for "corning" and "glazing" the cement, if possible: it would slow penetration of water and the setting reaction. ask the expert I had forgotten this question, but by chance I've people pouring concrete just round the corner, and I asked them. It turns out that there are lots of substances that will do what you seek; they are called setting retardants, and they act by slowing down the calcium silicate hydration reaction. After a few Google enquiries I'd go for sodium glucoheptonate - on the usage directions it says that using an excessive quantity can "kill" the set of concrete. This is "commonly" done if for any reason it is impossible to empty the concrete drum on a mixer; killing the set wastes the concrete, but allows salvaging the mixer drum. On a similar product (sodium gluconate), some producers claim that it can prolong "workable time" (which I assume means before setting) to a few days. The quantity needed is below one percent. A: Not sure about climactic changes, but you might want to look into plain table sugar. Adding sugar to wet concrete can delay or completely suspend hardening at high enough concentrations. Whether that sugar was provided by gumdrop rain or literal pixie sticks would be up to you.
{ "pile_set_name": "StackExchange" }
Q: How can I select for an input and a textarea? I have the following code: $('input.update-grid', $form) .each(function () { var id = this.id.replace('modal', ''); $('#input' + id).val(this.value) }) I would like this to also select for textareas that have a class of upgrade-grid. Is there a way that I can do this without making another selector and code? Also if I want to set the text in a textarea is that just set in the same way as an input with .val()? A: $('input.update-grid, textarea.update-grid', $form) Or if no other element tags have that class: $('.update-grid', $form)
{ "pile_set_name": "StackExchange" }
Q: QCombobox with model with 50,000 rows has large delay on the first-time dropdown When assigning prepared model having more than 50,000 rows (which performs immediately) to a combobox and trying to press dropdown button, experience a few seconds delay before combobox dropdown list appear. Observe this situation ONLY when FIRST time presses dropdown button in combobox. Any way to improve performance here? A: The key point is combobox by default uses QStandardItemModel to store the items and a QListView subclass displays the popuplist. Investigating QListView properties had solved the problem, details here: https://stackoverflow.com/a/33404207/630169
{ "pile_set_name": "StackExchange" }
Q: adding a new SDK written in C into android Is it possible for us to port a SDK written in C into android and used it to develop an apps? because I have a SDk written in C and wish to use it to develop an apps using it, how should I do? A: Java talks to the native layer (C code) via the Java Native Interface (JNI). You can use you C SDK if you write JNI wrappers for you API. This way you will be able to import you native library into Java and call your native (meaning C) functions from it. That's what the wrappers are for. This will only work provided that your SDK itself does not use any libraries that Android doesn't support. If it's straightforward C and the GNU toolchain will compile it, it should work well. In order to compile native C code for Android (or ARM to be more precise), you need the Android Native Development Kit (NDK). This should get you started. There are plenty of great examples of how to use JNI and the NDK on the web, including Stack Overflow.
{ "pile_set_name": "StackExchange" }
Q: Find the point on the curve farthest from the line $x-y=0$. the curve $x^3-y^3=1$ is asymptote to the line $x-y=0$. Find the point on the curve farthest from the line $x-y=0$.can someone please explain it to me what the question is demanding? I cant think it geometrically as I am not able to plot it Also is there any software to plot such graphs.? A: NOTE: you do need to know that the distance of a point $(x,y)$ from the line $y=x$ is $|x-y|$ (multiplied by the constant $1/\sqrt 2$). There are many ways to figure that out, from many viewpoints. ORIGINAL: If we write $$ u = x-y, $$ $$ v = x+y, $$ we can use the identity $$ x^2 + xy + y^2 = \frac{1}{4} \left( (x-y)^2 + 3 (x+y)^2 \right) $$ to find $$ x^3 - y^3 = \frac{1}{4} \; u \; \left( u^2 + 3 v^2 \right), $$ so the curve becomes $$ u \; \left( u^2 + 3 v^2 \right) = 4 $$ May be worth emphasizing that, since we must have $u > 0,$ we always have $$ u^3 = 4 - 3 u v^2 \leq 4. $$ Therefore $u$ achieves its maximum when $v=0,$ at which point $$ u^3 = 4. $$ This relates to a point where $y=-x,$ so $u=2x$ there and the value of $x$ satisfies $$ 8 x^3 = 4. $$ PLOT: A: Rotate by $-\pi/4$. This corresponds to $x\mapsto x-y$ and $y\mapsto x+y$ (up to a scalar factor). Then your line becomes $x-y-(x+y)=0\iff y=0$ and the equation of the curve becomes $$(x-y)^3-(x+y)^3=1\iff -2y^3-6yx^2=1\iff x^2=-\frac{1+2y^3}{6y}$$ as $y$ can't be $0$. You want to find the farthest point from the line $y=0$, so you need to minimize $y$ so that the fraction on the right is positive. So the solution is $(0,-1/\sqrt[3]2)$, which is $$(1/\sqrt[3]2,-1/\sqrt[3]2)$$ in the original coordinates. A: Since I don't have a good-enough ( or high -enough ) reputation, I will write my thoughts here: You have two sets of points in the plane, $S_1=(x,x)$ and EDIT $S_2=(x,(x^3-1)^{1/3}) $ Now use the Euclidean distance and minimize the distance.
{ "pile_set_name": "StackExchange" }
Q: How to iterate over multiple Word instances (with AccessibleObjectFromWindow) I need to iterate over all Word instances, no matter if opened by users, by automation, zumbis, etc. I will describe all the steps until now: I saw and implemented the solutions that I got here; Do For Each objWordDocument In objWordApplication.Documents OpenDocs(iContadorDocs - 1) = objWordDocument.Name OpenDocs(iContadorDocs) = objWordDocument.path iContadorDocs = iContadorDocs + 2 ReDim Preserve OpenDocs(iContadorDocs) Next objWordDocument iWordInstances = iWordInstances + 1 objWordApplication.Quit False Set objWordApplication = Nothing Set objWordApplication = GetObject(, "Word.Application") Loop While Not objWordApplication Is Nothing it works, but: for iterate over all word instances we have to GetObject and close it, looping until no more opened instances are, and after, reopen all that I care this take a lot of time & R/W cycles & Disk Access and of course has to be accomplished outside Word, because it may close the code running instance first, or in the middle of the loop... So, after some googling, I saw some examples of access the process direct, here and here for VB. I managed to get the PID for all Winword.exe instances, mainly adapting a little the code at VBForums: Showing only the modified piece of code: Do If LCase(VBA.Left$(uProcess.szExeFile, InStr(1, uProcess.szExeFile, Chr(0)) - 1)) = LCase(ProcessName) Then ProcessId = uProcess.th32ProcessID Debug.Print "Process name: " & ProcessName & "; Process ID: " & ProcessId End If Loop While ProcessNext(hSnapShot, uProcess) For the above code run, we need the PROCESSENTRY32 structure that include both process name (szExeFile) and Process Id fields (th32ProcessID); this code is @ VBnet/Randy Birch. So, now I have the word instances PIDs; what next? After doing that, I tried to see how could I pass these PID instances to the GetObject function. At this time I bumped into this Python thread, that opened my eyes to the AccessibleObjectFromWindow that creates an object from a windows handle. I dug in a lot of places, the most useful being these here, here and here and could get this piece of code: Private Declare Function FindWindowEx Lib "User32" Alias "FindWindowExA" _ (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _ ByVal lpsz2 As String) As Long Private Declare Function IIDFromString Lib "ole32" _ (ByVal lpsz As Long, ByRef lpiid As GUID) As Long Private Declare Function AccessibleObjectFromWindow Lib "oleacc" _ (ByVal hWnd As Long, ByVal dwId As Long, ByRef riid As GUID, _ ByRef ppvObject As Object) As Long Private Type GUID Data1 As Long Data2 As Integer Data3 As Integer Data4(7) As Byte End Type Private Const S_OK As Long = &H0 Private Const IID_IDispatch As String = "{00020400-0000-0000-C000-000000000046}" Private Const OBJID_NATIVEOM As Long = &HFFFFFFF0 Sub testWord() Dim i As Long Dim hWinWord As Long Dim wordApp As Object Dim doc As Object 'Below line is finding all my Word instances hWinWord = FindWindowEx(0&, 0&, "OpusApp", vbNullString) While hWinWord > 0 i = i + 1 '########Successful output Debug.Print "Instance_" & i; hWinWord '########Instance_1 2034768 '########Instance_2 3086118 '########Instance_3 595594 '########Instance_4 465560 '########Below is the problem If GetWordapp(hWinWord, wordApp) Then For Each doc In wordApp.documents Debug.Print , doc.Name Next End If hWinWord = FindWindowEx(0, hWinWord, "OpusApp", vbNullString) Wend End Sub Function GetWordapp(hWinWord As Long, wordApp As Object) As Boolean Dim hWinDesk As Long, hWin7 As Long Dim obj As Object Dim iid As GUID Call IIDFromString(StrPtr(IID_IDispatch), iid) hWinDesk = FindWindowEx(hWinWord, 0&, "_WwF", vbNullString) '########Return 0 for majority of classes; only for _WwF it returns other than 0 hWin7 = FindWindowEx(hWinDesk, 0&, "_WwB", vbNullString) '########Return 0 for majority of classes; only for _WwB it returns other than 0 If AccessibleObjectFromWindow(hWin7, OBJID_NATIVEOM, iid, obj) = S_OK Then '########Return -2147467259 and does not get object... Set wordApp = obj.Application GetWordapp = True End If End Function The errors are commented (########) above into the code; but resuming, I identify all instances, but cannot retrieve the object. For Excel, the lines: hWinDesk = FindWindowEx(hWinXL, 0&, "XLDESK", vbNullString) hWin7 = FindWindowEx(hWinDesk, 0&, "EXCEL7", vbNullString) works, because instead of zero I got hWinDesk = 1511272 and 332558, and after I got the Excel object. The EXCEL7 corresponding Word Windows class is _WwG (but it gives 0 above), the XLMAIN corresponding Word class name is OpusApp. What is the XLDESK corresponding for Word? So, I need help to discover it; or do you know how to capture the COM object in VBA knowing it's PID? MS itself suggested that I look into the Office 200 docs; I'll do that, but if someone has did this before... In fact now I'm interested in both approaches, but of course this last one is 99% implemented, so, my preferred. TIA P.S. Of course, when implemented, all objects will be closed/nothing, error-handling, etc... EDIT 1: Here is Spy++ output, as per @Comintern advise: Interesting is that I can locate in Excel output only two of the strings: XLMAIN and XLDESK, but cannot find at all the EXCEL7, and Excel object is successfully captured. For Word, I tested all the strings (_WwC,_WwO,), but only ?FindWindowEx(hWinWord, 0&, "_WwF", vbNullString) 1185896 ?FindWindowEx(hWinDesk, 0&, "_WwB", vbNullString) 5707422 got a handle, in that order; but to no avail, because ?AccessibleObjectFromWindow(hWin7, OBJID_NATIVEOM, iid, obj) -2147467259 Any ideas? directions? A: After getting more intimate with Spy++ as @Comintern suggested, I traced this: This is the actual Window order; all windows below the OpusApp are its children But to understand why it is functioning now, we have to right click every _Ww[A_Z] below: For _WwF: For its children _WwB: And finally to the goal!!!!! _WwG: With this approach, it is obvious that we must add another layer to the code: Function GetWordapp(hWinWord As Long, wordApp As Object) As Boolean Dim hWinDesk As Long, hWin7 As Long, hFinalWindow As Long Dim obj As Object Dim iid As GUID Call IIDFromString(StrPtr(IID_IDispatch), iid) hWinDesk = FindWindowEx(hWinWord, 0&, "_WwF", vbNullString) hWin7 = FindWindowEx(hWinDesk, 0&, "_WwB", vbNullString) hFinalWindow = FindWindowEx(hWin7, 0&, "_WwG", vbNullString) If AccessibleObjectFromWindow(hFinalWindow, OBJID_NATIVEOM, iid, obj) = S_OK Then Set wordApp = obj.Application GetWordapp = True End If End Function What I don't understand, but don't mind now, is why duplicate results for 2 different instances: Debug.print results: Instance_1 1972934 x - fatores reumaticos.docx FormGerenciadorCentralPacientes.docm Instance_2 11010524 x - fatores reumaticos.docx FormGerenciadorCentralPacientes.docm Instance_3 4857668 But to solve that, I'll adapt the marvel solution by @PGS62; resuming: Private Function GetWordInstances() As Collection Dim AlreadyThere As Boolean Dim wd As Application Set GetWordInstances = New Collection ...code... For Each wd In GetWordInstances If wd Is WordApp.Application Then AlreadyThere = True Exit For End If Next If Not AlreadyThere Then GetWordInstances.Add WordApp.Application End If ...code... End Function And, voilá, iteration for all Word instances for the masses without have to close and reopen!!! Thanks, community, for all ideas in other threads, and @Comintern for the crucial advise.
{ "pile_set_name": "StackExchange" }
Q: Modifying /etc/hosts to easily access a domain name (or ip address) for amazon EC2 instance I previously added into my local(Mac OS x 10.6) /etc/hosts file my server's public ip something like this: 123.123.123.123 myServer to allow me to ssh to myServer without having to remember the ip address of the server and worked fine (using shh public key) , like this: ssh myServer1 However on Amazon EC2 instance I tried to do the same using the long public dns address provided and in /etc/hosts I added this: ec2-23-23-23-23.compute-1.amazonaws.com myServer2 but when I try to ssh myServer2 says that the 'hostname cannot be resolved' any ideas why this is not working? How can I make this work ? The complete command I want to use is: ssh -i key.pem [email protected] and I am trying to create a shortcut which might be something like this: ssh -l username myServer2 or ssh -i key.pem -l username myServer2 any ideas? UPDATE: I used alias instead which is easier: Added this inside .bash_profile (MAC OS x) alias myServer='ssh -i /path/to/key.pem [email protected]' (need to close and open terminal again or use source ~/.bash_profile ) Then ssh with just using myServer on command line $ myServer A: Instead of editing your hosts file, read about the SSH client configuration. You can create host aliases in ~/.ssh/config. For example: Host myServer2 HostName ec2-23-23-23-23.compute-1.amazonaws.com UserName username If you're only using SSH this will work fine. If you need to access other services, either set up DNS, or use port forwarding in SSH (with -L).
{ "pile_set_name": "StackExchange" }
Q: Correct way of "Absolute Import" in Python 2.7 Python 2.7.10 In virtualenv Enable from __future__ import absolute_import in each module The directory tree looks like: Project/ prjt/ __init__.py pkg1/ __init__.py module1.py tests/ __init__.py test_module1.py pkg2/ __init__.py module2.py tests/ __init__.py test_module2.py pkg3/ __init__.py module3.py tests/ __init__.py test_module3.py data/ log/ I tried to use the function compute() of pkg2/module2.py in pkg1/module1.py by writing like: # In module1.py import sys sys.path.append('/path/to/Project/prjt') from prjt.pkg2.module2 import compute But when I ran python module1.py, the interpreter raised an ImportError that No module named prjt.pkg2.module2. What is the correct way of "absolute import"? Do I have to add the path to Project to sys.path? How could I run test_module1.py in the interactive interpreter? By python prjt/pkg1/tests/test_module1.py or python -m prjt/pkg1/tests/test_module1.py? A: How python find module python will find module from sys.path, and the first entry sys.path[0] is '' means, python will find module from the current working directory import sys print sys.path and python find third-party module from site-packages so to absolute import, you can append your package to the sys.path import sys sys.path.append('the_folder_of_your_package') import module_you_created module_you_created.fun() export PYTHONPATH the PYTHONPATH will be imported into sys.path before execution export PYTHONPATH=the_folder_of_your_package import sys [p for p in sys.path if 'the_folder_of_your_package' in p] How could I run test_module1.py in the interactive interpreter? By python Project/pkg1/tests/test_module1.py or python -m Project/pkg1/tests/test_module1.py? you can use if __name__ == '__main__': idiomatic way, and use python Project/pkg1/tests/test_module1.py if __name__ = '__main__': main() A: If you add sys.path.append('path/to/Project') into prjt/__init__.py, you need to import submodules so: from pkg2.module2 import compute (without prjt specification) because prjt package import is in progress and the higher level folder is not in the sys.path. This is exactly what @Cissoid suggested. BTW, from __future__ import absolute_import is not necessary for Py >= 3.0. Answering your second question... I have very similar structure for unittests subfolder, so in the pkg/unittests/testall.py I wrote the following: testfolder = os.path.abspath(os.path.dirname(__file__)) project_root = os.path.abspath(os.path.join(testfolder, r"..\..")) sys.path.append(project_root) import pkg I run it without -m option because it's unnecessary complication. A: Import the outer Project path. sys.path.append('/path/to/Project') Or import "compute" start from pkg2 from pkg2.module2 import compute
{ "pile_set_name": "StackExchange" }
Q: How to get the list of files in a directory and display them in the table Actually I'll get the directory name dynamically from one url.I want to display the list of files in a directory in the html table.How can I do this ? A: The only way you maybe get directory name - ask server. It must have available functionality to scan directory, or get name. And expose it via REST, (while ajax) And from browser, request this endpoint
{ "pile_set_name": "StackExchange" }