text
stringlengths
15
59.8k
meta
dict
Q: add_filter hook not working in plugin's php file I am developing a plugin and it works fine when I call my code from my plugin's main php file but I want to run only once My external file is called in the plugin. I mean I want to place my function inside includes folder and in a file living there. like plugin folder/includes/file.php ... here is my code add_filter('wp_nav_menu_items',',my_custom_function'); function my_custom_function ($nav){ return $nav."<li class='menu-header-search'><a href='#'>Icon</a></li>"; } Kindly let me know how can I make it work, it works in side plugin's main php file but does not work from other php files inside plugin includes folder. A: It should work if you include your file from the plugins main file, just make sure it is included correctly. include plugin_dir_path( __FILE__ ) . 'includes/file.php; This would include a file in an includes folder in your custom plugin folder, and would include an file named: "file.php". If you want to know if its been loaded correctly, just add an die() statement in the included file: die('my include file has been loaded correctly'); Just remove the die() statement after you have an confirmation that its working :) Lastly you need to copy your callback function code and paste it in your included file. If your hook still does not work, then it might be something wrong with your callback function. The documentation for the filter hook you are using: https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/
{ "language": "en", "url": "https://stackoverflow.com/questions/40284346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Automating setterm I've GNU/linux Debian 10 (sid) net install with no x11 on a HP Pavilion dv6. I can keep the monitor on alway with: setterm -blank 0 Then have the monitor shut off after 10 minutes of inactivity with the: setterm -blank 10. What I would like to do is have the screen go off at 23:00 every night and come back on every morning at 06:00. I have tried several things in cron and via systemctld. What I have tried in both is: setterm -blank 10 setterm -term bash -blank 10 setterm -term fish -blank 10 setterm -term /dev/tty1 -blank 10 setterm -term linux -blank 10 $TERM=linux setterm -blank 10 $TERM=bash setterm -blank 10 $TERM=fish setterm -blank 10 $TERM=/dev/tty1 setterm -blank 10 I have also made a bash script with all of those variations. To no avail. Is it even possible to run setterm in cron or as a systemctld event? As a secondary note I'm utilizing fish as my shell, also I have to detach from GNU/screen to actually get setterm to work. A: For some options, setterm works by sending a sequence of characters to stdout. Normally, when you are on the console these are therefore read by the console driver and interpreted. Other options do ioctls on stdin similarly. If you use these commands from cron or a systemd unit, you would need to redirect the output or input to/from the console. For example, from cron, as root, try setterm -term linux -blank 0 >/dev/console Or for something using ioctl, set the stdin setterm -term linux -powersave on </dev/console If you use the bash shell in cron you can say <>/dev/console to open for in and out.
{ "language": "en", "url": "https://stackoverflow.com/questions/66537659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: touchesBegan in custom UITableViewCell, touchesEnded in UIView I am trying to mimic a drag n drop of an image from a UITableView to a UIView. Both the UITableView and UIView are on the same view, side by side. My approach: is to fire the touchesBegan event inside the UITableView (i.e. when a cell is touched/selected) and fire the touchesEnded event when the touch ends in the UIView. The problem: So I created a custom UITableViewCell that contains a UIImageView and a couple of UILabels. And I set the User Interaction Enabled for this UIImageView. Then to receive the touchesBegan event, I did override the touchesBegan method inside the custom UITableViewCell class; and now I am able to receive the touchesBegan event from the cell. The problem is I am not getting the touchesEnded event when the touch ends on the UIView. Note that I already implemented the touchesEnded method inside the view controller class (not in the custom class); and if I start and stop a touch within this UIView, I see the touchesEnded being fired. Is there anything I am missing here? Using Xcode 4.6 (4H127), testing on iPad 2 with iOS 6.1.3 A: This will not work that way. You will need to utilize the touch methods on the parent view that contains both of your subviews. Could look abstractly like this: -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if ([self touchOnCell:touches]) { //check to see if your touch is in the table isDragging = YES; //view cell } } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { //do your dragging code here } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { if (isDragging && [self touchOnDropView:touches]) { //do your drop code here } } now if this doesnt work like that alone you might want to implement the hitTest on the tableView and if the touch is in the dragging object's region, then return the parent view. hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/16109922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I lazyLoad large model outputs that have been saved using saveRDS? I have a few hundred large model outputs (8 Gb), each saved as a list containing many elements (and sub elements). To do further work on all these outputs it is not possible to load all 100 8 Gb files at once into the environment and I came across lazyLoad as a possible solution here, here, and here. But have not succeeded in making the code work for me yet! I suspect the problem might be coming from the data being saved using saveRDS() instead of save() (if I try load() a file saved with saveRDS() it gives an error) but I'm not certain. I have two questions: 1) Is lazyLoad the correct way to deal with large outputs for indexing and loading individual levels of the data structure when called rather than storing everything in memory? 2) What am I doing wrong? I have made several attempts along the lines of this: e = local({readRDS("path/to/file.RData"); environment()}) tools:::makeLazyLoadDB(e, "path/to/file") lazyLoad("path/to/file") But the final line (lazyLoad("path/to/file") gives NULL as a result. Since this is a general problem I haven't created a fake data structure as a reproducible example but can do so if required. I thank you! A: 1) readRDS requires assignment unlike load, so this works: e = local({df <- readRDS("path/to/file.RData"); environment()}) tools:::makeLazyLoadDB(e, "path/to/file") lazyLoad("path/to/file") I should be saving my files according to convention using .rds as an extension when saving data using saveRDS. 2) Probably not the right approach in this case as indexing any element of the "promise" loads the whole file not just the indexed element.
{ "language": "en", "url": "https://stackoverflow.com/questions/60907672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert pixel to percentage for big monitors I developed a web page with 1000px width. But it is look very small in big monitor(We have 2560x1600 monitor). My questions are * *How to convert a (or any) website to big screen using percentage instead of pixels ? *Any conversion method for pixel to percentage? I tried width: 100%,.... But it is not for all(padding, margins, line-height,...) any suggestions? Thank you... A: Have you tried Media Queries? Check out: http://www.w3.org/TR/css3-mediaqueries/ You can detect the screen size (or intervals of sizes) and apply different CSS to it, regarding element size in your page.
{ "language": "en", "url": "https://stackoverflow.com/questions/12858058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby: Convert memory address string format to bytes for shellcode I have found a program that leaks the address of it's buffer. I can capture that by sending a socket.get_once but it's in a string format. So when I go to pass it to pack it doesn't want a string value. How can I convert a memory address in string format to an address that I can put in shellcode? Example Address captured: 0x7fffffffdfc0 Using string.pack('Q') it throws an error that it's not an integer. So I tried using a loop to break up the sections into pairs like so: string.scan(/../).reverse_each { |x| buf += [x.to_i].pack('S')} I know this is probably a simple solution but for some reason I can't wrap my head around it. A: It was easy... buf += [string.to_i(16)].pack('Q')
{ "language": "en", "url": "https://stackoverflow.com/questions/49135022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to reuse the UIScrollView scrolling physics for a custom scrolling view? I have a custom view with some complex scrolling behaviour. I’d like the scrolling to have the same physics as UIScrollView, both the inertia and the edge bouncing. Is it possible to somehow reuse the physics code from UIScrollView to save effort and offer a consistent user experience? A: It’s sort of a hack, but it can be done. The solution is nicely explained in the WWDC 2012 Session #223: Enhancing User Experience with Scroll Views. The main trick is to place a regular UIScrollView over your content, watch for the offset changes reported by the scrollViewDidScroll: delegate call and adjust your custom view’s content accordingly. The only catch is accepting other touch input (as the scroll view covers your real content view and swallows the input), but even this is reasonably easy to solve, as shown in the WWDC video.
{ "language": "en", "url": "https://stackoverflow.com/questions/15482527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - How to avoid Parse errors on older servers when using new functions When I use an anonymous function ( but see also note below ) like : $f = function() use ($out) { echo $out; }; It produces an parse error on servers where PHP is older than 5.3.0. My software needs to be compatible with unknown servers , but in the same time , I want also to use new functions, so I thought I will add some kind of a version check, if (o99_php_good() != true){ $f = function() use ($out) { echo $out; }; } where the o99_php_good() is simply function o99_php_good(){ // $ver= ( strnatcmp( phpversion(),'5.3.0' ) >= 0 )? true:false; $ver= ( version_compare(PHP_VERSION, '5.3.0') >= 0 )? true:false; return $ver; } But still the error is produced . Is there a way to somehow "isolate" that part of the code ? I thought of doing a conditional include() based on a version check , which would probably work, but it will be absurd to make a separate file every time I need to use a function... Any creative ( or trivial ) solution for that ? Note : the example here is just a Lambda function, but the problem can occur in every other function which is a new feature and/or might not be supported on some servers .. Edit I after comment . Adding a "minimum requirements" list is always good, but it does not resolve the problem. If one does not want to loose users (not all customers are happy or can upgrade their servers every time I will update a new function ) it will just force me to "fork" my software into 2 (or possibly more ) unmanageable versions.. A: I had exactly the same problem and solved it using eval function : if (version_compare(PHP_VERSION, '5.3.0') >= 0) { eval(' function osort(&$array, $prop) { usort($array, function($a, $b) use ($prop) { return $a->$prop > $b->$prop ? 1 : -1; }); } '); } else { // something else... } A: Anonymous functions came with PHP 5.3.0. My first thing to do would be to replace with one of the following: $my_print_r = "my_print_r"; $my_print_r(); or $my_print_r = create_function('$a','print_r($a);'); UPDATE: i would go with the first method... It would give me enough control for creating my own function versions and in much easier procedure than create_function, regardless of PHP version. I never had any problems with that approach. In fact i once built a whole multidimensional array of functions, that was easily manageable and able to add/remove functions, think of that.. That system was also used by other users, they were able to add their functions too in a way. A: The only thing I can think of is to make a build script which people will have to run to make it compatible with lower versions. So in case of anonymous methods, the script will loop through all the PHP files, looking for anonymous methods: $f = function($a) use($out) { echo $a . $out; }; and replace them with create_function for < 5.3: $f = create_function('$a', ' global $out; echo $a . $out; '); A: use include if (o99_php_good() != true){ include 'new_func.php'; } new_func.php: $f = function() use ($out) { echo $out; };
{ "language": "en", "url": "https://stackoverflow.com/questions/16413627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: nested_attributes fields not showing up In my current rails app, I have a User model which has_one :user_detail. Currently, I cannot get the form to display the fields for the nested attribute unless I already have it seeded with the seeds.rb file. Here is my User model class User < ActiveRecord::Base has_one :user_detail, :dependent => :destroy accepts_nested_attributes_for :user_detail attr_accessible :email, :password, :password_confirmation, :access_level, :first_name, :last_name, :user_detail_attributes has_secure_password end and my UserDetail model class UserDetail < ActiveRecord::Base belongs_to :user end and my form <%= form_for [:admin, @user] do |f| %> <p><%= f.text_field(:name, :placeholder => 'Name')%></p> <p><%= f.label(:email) %></p> <p><%= f.email_field(:email, :placeholder => 'Your Email')%></p> <p><%= f.password_field(:password, :placeholder => 'Choose a password') %></p> <p><%= f.password_field(:password_confirmation, :placeholder => 'Confirm Password') %></p> <%= f.fields_for :user_detail do |u| %> <p><%= u.text_field(:country, :placeholder => 'Country') %></p> <p><%= u.text_field(:state, :placeholder => 'State') %></p> <p><%= u.text_field(:city, :placeholder => 'City') %></p> <p><%= u.text_field(:phone, :placeholder => 'Phone') %> </p> <% end %> <p><%= submit_tag("Add Owner") %></p> The fields won't show up, until I seed them with this seeds.rb UserDetail.delete_all owner1detail = UserDetail.create(:zip => "84770", :country => "US", :state => "Ut", :city => "St. George", :user_id => owner1.id ) and I run rake db:seed. Once I do this and I edit an existing user, the fields show up, all filled in. However, when creating a user they don't show up. Any ideas why? A: I moved the build to my controller like so and it worked def new @user = User.new @user.build_user_detail end A: Try to prebuild it. <%= form_for [:admin, @user] do |f| %> <p><%= f.text_field(:name, :placeholder => 'Name')%></p> <p><%= f.label(:email) %></p> <p><%= f.email_field(:email, :placeholder => 'Your Email')%></p> <p><%= f.password_field(:password, :placeholder => 'Choose a password') %></p> <p><%= f.password_field(:password_confirmation, :placeholder => 'Confirm Password') %></p> <% @user.user_detail.build if @user.user_detail.nil? %> <%= f.fields_for :user_detail do |u| %> <p><%= u.text_field(:country, :placeholder => 'Country') %></p> <p><%= u.text_field(:state, :placeholder => 'State') %></p> <p><%= u.text_field(:city, :placeholder => 'City') %></p> <p><%= u.text_field(:phone, :placeholder => 'Phone') %> </p> <% end %> <p><%= submit_tag("Add Owner") %></p>
{ "language": "en", "url": "https://stackoverflow.com/questions/10265628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to know how many objects will be created with the following code? I am bit confused in case of objects when it comes to Strings, So wanted to know how many objects will be created with following code, with some explanation about String objects creation with respect to String pool and heap. public static void main(String[] args) { String str1 = "String1"; String str2 = new String("String1"); String str3 = "String3"; String str4 = str2 + str3; } A: 4 objects will be created. Two notes: * *new String("something") always creates a new object. The string literal "something" creates only one object for all occurrences. The best practice is to never use new String("something") - the instantiation is redundant. *the concatenation of two strings is transformed to StringBuilder.append(first).append(second).toString(), so another object is created here. A: each of the str1, str2, str3, str4 are String objects . str1 : "String1" is a string literal and Java creates a String object whenever it encounters a string literal. str2 : as you are using the new keyword and constructor of the class String a String object is created str3 : similar to str1 str4 : concatenated string literal, similar to str1 edit : http://download.oracle.com/javase/tutorial/java/data/strings.html
{ "language": "en", "url": "https://stackoverflow.com/questions/3850921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Passing a location.search parameter to a Jasmine (Karma) test I have a javascript file that uses location.search for some logic. I want to test it using Karma. When I simply set the location (window.location.search = 'param=value' in the test), Karma complains I'm doing a full page reload. How do I pass a search parameter to my test? A: Without seeing some code it's a little tricky to know what you exactly want, however it sounds like you want some sort of fixture/mock capability added to your tests. If you check out this other answer to a very similar problem you will see that it tells you to keep the test as a "unit". Similar post with Answer What this means is that we're not really concerned with testing the Window object, we'll assume Chrome or Firefox manufacturers will do this just fine for us. In your test you will be able to check and respond to your mock object and investigate that according to your logic. When running in live code - as shown - the final step of actually handing over the location is dealt with by the browser. In other words you are just checking your location setting logic and no other functionality. I hope this can work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/32952522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Styled Components & Typescript type error I've set up styled-components successfully in react-native, but I'm now using react-native-web and can't get styled-components to work on the web in this very simple example: import * as React from 'react'; import styled from 'styled-components'; export default class View extends React.PureComponent { public render() { return ( <Container> <h1>Hey</h1> </Container> ); } } const Container = styled.div; I'm getting this error: Type error: JSX element type 'StyledComponentClass<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, a...' is not a constructor function for JSX elements. Property 'render' is missing in type 'StyledComponentClass<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, a...'. TS2605 > 11 | <Container> This is my tsconfig.json: "target": "es6", "jsx": "preserve", "module": "esnext", "sourceMap": true, "outDir": "dist", "types": [ "react", "react-native", "jest" ], "skipLibCheck": true, "lib": [ "es2015.promise", "esnext", "dom" ], "alwaysStrict": false, "downlevelIteration": true, "strict": false, "strictNullChecks": false, "allowJs": true, "esModuleInterop": false, "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true And my package.json: ... "devDependencies": { ... "@types/react": "^16.7.20", "@types/react-dom": "^16.7.20", "@types/react-native": "^0.52.25", "typescript": "^2.9.2" }, "dependencies": { ... "react": "16.3.1", "react-dom": "^16.7.0", "styled-components": "^3.4.5", } I've tried to rm -rf node_modules; rm package-lock.json; npm install to no avail. Probably missing something simple here, but anyone have any ideas? Not sure what other information I can provide. A: You'll want to use the React Native component instead of standard HTML tags. Instead of styled.div, you'll use styled.View. Also you have to use react native's Text component in replace of standard HTML tags that would hold textual data such as <H1>. So, this is what your code should translate to import * as React from 'react' import { Text } from 'react-native' import styled from 'styled-components/native' export default class View extends React.PureComponent { render() { return( <Container> <Text>Hey</Text> </Container> ) } } const Container = styled.View
{ "language": "en", "url": "https://stackoverflow.com/questions/54370455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Serializing object for sending inside Intent on Android I want to pass objects between Activities and Services on Android. The straight forward way to do this is to make your objects implement Serializable or Parcelable. * *Serializable it's relatively bad performance. *Parcelable on the other hand requires me to implement and maintain the serialization myself i.e. always to remember to update it in the future. I was thinking about using Jackson Json serializer for this task. It's faster than Java built in serialization and does not require me write and maintain serializtion code. What you think? A: I believe both the methods have its own importance. * *Parcelable is a good choice. But using parcelable you will have to write code for serialization yourself. This method is not encouraged when you are having large number of data members in your class, whose object you want to send. *On the other hand serialization is for sure bulky operation but I think easy to implement. You will have to make your class implements serializable. But still there is one more option, which you can use. You can make your object static and access it from other Activity. if object is not a lot bulky, then this is also good choice. A: If performance is important, then you really should go with Parcelable. JSON will be relatively slow because it is less efficient than Parcelable which was specifically implemented in Android for improving performance when packaging data for Inter-Process Communication.
{ "language": "en", "url": "https://stackoverflow.com/questions/6341209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Program Data in a POSIX environment? I'm a little confused on how/where program data should be stored in a Posix envronment, Debian Linux specifically. I understand that user specific data should be kept in $home, and looking at this question it looks like data common to all users should be in /var/lib/myProgram/ but how does myProgram get granted the access to read and write data there? I'm a little lost and I'm still a newcomer to linux, I'd appreciate any insights!
{ "language": "en", "url": "https://stackoverflow.com/questions/27684571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Graphing Segments in R I want to plot segmented data in R. That is, say I have data of the form | Product | Date | Origination | Rate | Num | Balance | |-----------------------|--------|-------------|------|-----|-----------| | DEMAND DEPOSITS | 200505 | 198209 | 0 | 1 | 2586.25 | | DEMAND DEPOSITS | 200505 | 198304 | 0 | 1 | 3557.73 | | DEMAND DEPOSITS | 200505 | 198308 | 0 | 1 | 14923.72 | | DEMAND DEPOSITS | 200505 | 198401 | 0 | 1 | 4431.67 | | DEMAND DEPOSITS | 200505 | 198410 | 0 | 1 | 44555.23 | | MONEY MARKET ACCOUNTS | 200505 | 198209 | 0.25 | 2 | 65710.01 | | MONEY MARKET ACCOUNTS | 200505 | 198211 | 0.25 | 2 | 41218.41 | | MONEY MARKET ACCOUNTS | 200505 | 198304 | 0.25 | 1 | 61421.2 | | MONEY MARKET ACCOUNTS | 200505 | 198402 | 0.25 | 1 | 13620.17 | | MONEY MARKET ACCOUNTS | 200505 | 198408 | 0.75 | 1 | 281897.74 | | MONEY MARKET ACCOUNTS | 200505 | 198410 | 0.25 | 1 | 5131.33 | | NOW ACCOUNTS | 200505 | 198209 | 0 | 1 | 142744.35 | | NOW ACCOUNTS | 200505 | 198303 | 0 | 1 | 12191.6 | | SAVING ACCOUNTS | 200505 | 198301 | 0.25 | 1 | 96936.24 | | SAVING ACCOUNTS | 200505 | 198302 | 0.25 | 2 | 21764 | | SAVING ACCOUNTS | 200505 | 198304 | 0.25 | 1 | 14646.55 | | SAVING ACCOUNTS | 200505 | 198305 | 0.25 | 1 | 20909.7 | | SAVING ACCOUNTS | 200505 | 198306 | 0.25 | 1 | 66434.56 | | SAVING ACCOUNTS | 200505 | 198309 | 0.25 | 1 | 20005.56 | | SAVING ACCOUNTS | 200505 | 198404 | 0.25 | 2 | 16766.56 | | SAVING ACCOUNTS | 200505 | 198407 | 0.25 | 1 | 47721.97 | I want to plot on the Y-axis a line per 'Product' type by 'Balance'. On the X-axis, I want to put the 'Origination'. I would ideally also like to set colors to distinguish between the lines. The data is not currently in data.frame form so let me know if I need to change back to that. I haven't been able to find an informative solution online for this, even though I'm sure there is. Thanks, A: As @zx8754 menitioned, you should provide reproducible data. Without having tested the code (because there's no reproducible data), I would suggest the following, assuming that the data is in the data.frame 'data': all_products <- unique(data$Product) colors_use <- rainbow(length(all_products)) plot(y = data[data$Product == all_products[1],"Balance"], x = data[data$Product == all_products[1],"Origination"], type = "l", col = colors_use[1], ylim = c(min(data$Balance, na.rm = T),max(data$Balance, na.rm = T)), xlim = c(min(data$Origination, na.rm = T),max(data$Origination, na.rm = T))) for(i_product in 2:length(all_products)){ lines(y = data[data$Product == all_products[i_product],"Balance"], x = data[data$Product == all_products[i_product],"Origination"], col = colors_use[i_product]) } A: I have not enough reputation to comment, so I write it as an answer. To make @tobiasegli_te's answer shorter, the first plot can be plot(Balance~Origination,data=data,type='n') and then make the subsequent lines done for i_product in 1:length(all_products). That way you need not worry about ylim. Here is an example using the Grunfeld data. z <- read.csv('http://statmath.wu-wien.ac.at/~zeileis/grunfeld/Grunfeld.csv') plot(invest~year,data=z,type='n') for (i in unique(as.numeric(z$firm))) lines(invest~year,data=z, subset=as.numeric(z$firm)==i, col=i) Also note that your Origination is not equally spaced. You need to change it to a Date or similar. A: I guess you want something like the following: df <- as.data.frame(df[c('Product', 'Balance', 'Origination')]) head(df) Product Balance Origination 1 DEMAND DEPOSITS 2586.25 198209 2 DEMAND DEPOSITS 3557.73 198304 3 DEMAND DEPOSITS 14923.72 198308 4 DEMAND DEPOSITS 4431.67 198401 5 DEMAND DEPOSITS 44555.23 198410 6 MONEY MARKET ACCOUNTS 65710.01 198209 library(ggplot2) library(scales) ggplot(df, aes(Origination, Balance, group=Product, col=Product)) + geom_line(lwd=1.2) + scale_y_continuous(labels = comma) A: I am not sure what you my want, is that what you re looking for? Assuming you put your data in data.txt, removing the pipes and replacing the spaces in the names by '_' d = read.table("data.txt", header=T) prod.col = c("red", "blue", "green", "black" ) prod = unique(d$Product) par(mai = c(0.8, 1.8, 0.8, 0.8)) plot(1, yaxt = 'n', type = "n", axes = TRUE, xlab = "Origination", ylab = "", xlim = c(min(d$Origination), max(d$Origination)), ylim=c(0, nrow(d)+5) ) axis(2, at=seq(1:nrow(d)), labels=d$Product, las = 2, cex.axis=0.5) mtext(side=2, line=7, "Products") for( i in 1:nrow(d) ){ myProd = d$Product[i] myCol = prod.col[which(prod == myProd)] myOrig = d$Origination[i] segments( x0 = 0, x1 = myOrig, y0 = i, y1 = i, col = myCol, lwd = 5 ) } legend( "topright", col=prod.col, legend=prod, cex=0.3, lty=c(1,1), bg="white" )
{ "language": "en", "url": "https://stackoverflow.com/questions/39856303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to Edit template any object In visual studio 2015 Unable to Edit template any object In visual studio 2015. I try with blend But I can't do that. please help me? If you don't know, please make a edit template for Button and post it here. Thanks. A: I couldn't solve question completely But I found something useful for default template of controls in Windows 8.1. Windows 8.1 default XAML templates and styles
{ "language": "en", "url": "https://stackoverflow.com/questions/32485568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to send email along with form details in php using wamp Hai Friends iam trying for an online form submission .whenever i try to submit form it redirects me to MS OUTLOOK but my my form values are not included in that why? Is it possible or does it require ftp credentials or something. Give me suggestions.. A: It redirects you to outlook mostly because you click on mailto: link. You can connect to smtp server to send e-mail via php. Here you will find how to do it You don't need FTP which is file transfer protocol you need connection to SMTP which is Simple Mail Transfer Protocol. Also check PHP manual If you doesn't want to use PHP and you want send it via your client for example outlook you need do something like this: <form enctype="text/plain" method="get" action="mailto:webdesign@aboutguide.com"> Your First Name: <input type="text" name="first_name"><br> Your Last Name: <input type="text" name="last_name"><br> Comments: <textarea rows="5" cols="30" name="comments"></textarea> <input type="submit" value="Send"> </form> Code from this page. However, I don't recommend this solution. Connecting to SMTP via PHP is better.
{ "language": "en", "url": "https://stackoverflow.com/questions/20901040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring Integration NotSerializableException on jdbc inbound-channel-adapter update query I have a jdbc inbound-channel-adapter which is defined as shown below. I'm using a MySQL dataSource. I want to update the status of rows that have been polled. I'm trying to follow this document: spring integration ref. mannual . My understanding is that the :id should map to the set of all id's returned by the SELECT query. <int-jdbc:inbound-channel-adapter channel="targetChannel" data-source="dataSource" query="SELECT * FROM mytable WHERE status=''" row-mapper="myRowMapper" max-rows-per-poll="500" update="UPDATE mytable SET status='IN_PROGRESS' WHERE id in (:id)"> <int:poller fixed-delay="60000" /> </int-jdbc:inbound-channel-adapter> The SELECT query executes fine and I have ensured that all the resulting rows are mapped by the RowMapper as expected, however while it tries to update using the given UPDATE query, I get the following exception: 2016-09-23 14:57:29.361 ERROR 15580 --- [task-scheduler-1] o.s.integration.handler.LoggingHandler : org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [UPDATE mytable SET status='IN_PROGRESS' WHERE id in (?)]; Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:108) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:870) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:894) at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:287) at org.springframework.integration.jdbc.JdbcPollingChannelAdapter.executeUpdateQuery(JdbcPollingChannelAdapter.java:181) at org.springframework.integration.jdbc.JdbcPollingChannelAdapter.poll(JdbcPollingChannelAdapter.java:173) at org.springframework.integration.jdbc.JdbcPollingChannelAdapter.receive(JdbcPollingChannelAdapter.java:149) at org.springframework.integration.endpoint.SourcePollingChannelAdapter.receiveMessage(SourcePollingChannelAdapter.java:209) at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:245) at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:58) at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:190) at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:186) at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:353) at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55) at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:51) at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:344) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.sql.SQLException: Invalid argument value: java.io.NotSerializableException at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860) at com.mysql.jdbc.PreparedStatement.setSerializableObject(PreparedStatement.java:3829) at com.mysql.jdbc.PreparedStatement.setObject(PreparedStatement.java:3559) at com.mysql.jdbc.JDBC42PreparedStatement.setObject(JDBC42PreparedStatement.java:68) at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:440) at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:235) at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:150) at org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.setValues(PreparedStatementCreatorFactory.java:292) at org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.createPreparedStatement(PreparedStatementCreatorFactory.java:244) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:627) ... 25 more Caused by: java.io.NotSerializableException: java.lang.Object at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at com.mysql.jdbc.PreparedStatement.setSerializableObject(PreparedStatement.java:3818) ... 33 more What am I doing wrong here? A: Found my mistake, thanks to Artem Bilan. I assumed that :id would map to "id" among the column names in the SELECT's result set and not to getId() on the POJOs. My RowMapper was mapping the "id" into "requestId" in the POJO. That was the mistake.
{ "language": "en", "url": "https://stackoverflow.com/questions/39668748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run application E2E test after argocd deployment? I would like to know how can we run application E2E(UI or API) test after successful deployment of any micro services using ArgoCD. Current Setup: I have CI pipeline setup with github-actions. Upon completion on CI build for any microservices, it updates the docker image version in helm values which resides in one of the github repo. This repo is than polled by ArgoCD for any change, and deploys in Kubernestes cluster if there is change exists. Intent: I want to run the application E2E( UI & API ) test once argocd synced any micro-services deployment object defined in the Helm charts. But I am unsure what should be the trigger point in github actions for that. How E2E test github actions workflow will know argocd has deployed the microservices without any issue and service is ready to be consumed by the automated test. A: Here is the full solution to the problem statement. apiVersion: batch/v1 kind: Job metadata: name: api-test-trigger annotations: argocd.argoproj.io/hook: PostSync argocd.argoproj.io/hook-delete-policy: HookSucceeded spec: template: metadata: labels: name: api-test spec: containers: - name: api-test args: - /bin/sh - -ec - "curl -X POST -H \"Accept: application/vnd.github.v3+json\" -H \"Authorization: token ${GITHUB_TOKEN}\" ${GITHUB_URL} -d '{\"ref\":\"main\"}'" env: - name: GITHUB_URL value: "https://api.github.com/repos/<your org>/<your repo>/actions/workflows/<workflow id>/dispatches" - name: GITHUB_TOKEN value: <your PAT> image: curlimages/curl You can create the PAT from github settings and provide the PAT as a secret. A: ArgoCD provides a feature called resource hooks. Hooks are ways to run scripts before, during, and after a sync operation. A use case for hooks from the official documentation: Using a PostSync hook to run integration and health checks after a deployment. Hooks can be any type of Kubernetes resource kind, but tend to be Pod, Job, or Argo Workflows. Per the GitHub actions documentation, you can send a POST request to the Github API in PostSync hooks template to run the workflow run.
{ "language": "en", "url": "https://stackoverflow.com/questions/69917361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Accessing array attributes from other classes with setter/getter I'm new to Java and was wondering how to access attributes from other classes with setter/getter if they are arrays. Currently, I have one date class that sets a date with parameters for month/day/year. I need to make another class that uses the date class to set a date of hire to store as an attribute, alongside others. My code currently looks like this: public class DateClass { private int month; private int day; private int year; // MONTH public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } // DAY public int getDay() { return day; } public void setDay(int day) { this.day = day; } // YEAR public int getYear() { return year; } public void setYear(int year) { this.year = year; } // FULL DATE public void setDate(int month, int day, int year) { setMonth(month); setDay(day); setYear(year); } public int[] getDate() { return new int[] { month, day, year }; } } This is the second class: public class EmployeeClass { private int[] dateOfHire; public void setDateOfHire(int[] dateOfHire) { dateOfHire.setDate(dateOfHire); } public String[] getDateOfHire() { return dateOfHire.getDate(dateOfHire); } } The error says: Cannot invoke setDate(int[]) on the array type int[] How can I fix this? Thanks! A: You need to do a couple of changes. First your EmployeeClass should have a DateClass attribute instead of int[] and the setDateOfHire() method must call the setDate() method that is available in the DateClass that has 3 parameters: public class EmployeeClass { private DateClass dateOfHire; public void setDateOfHire(int[] dateOfHire) { this.dateOfHire.setDate(dateOfHire[0], dateOfHire[1], dateOfHire[2]); } public int[] getDateOfHire() { return dateOfHire.getDate(); } } This would work, but I would suggest you review your class design. Having int arrays defining dates is a really bad practice. A: You're declaring an array of integer primitives private int[] dateOfHire; To declare an array of DateClass simply use private DateClass[] dateOfHire The primitive or class defined before the [] is what determines the type of array that is initialized You can use this as a reference A: You will need to create a DateClass object to use its methods. Consider changing your EmployeeClass like so: public class EmployeeClass { private int[] dateOfHire; // not sure of the purpose of this array private DateClass dateClassObject; // your variable name is up to you public EmployeeClass () { // Constructor for this class dateClassObject = new DateClass(); // created a new DateClass in the constructor } public void setDateOfHire(int[] dateOfHire) { // this dateOfHire array is the array that is passed in when // method is called. Do not confuse it the array declared as a property. int day = dateOfHire[0] // assuming the day is in index 0 of the array int month = dateOfHire[1] // assuming the month is in index 1 of the array int year = dateOfHire[2] // assuming the year is in index 2 of the array dateClassObject.setDate(month, day, year); // changed to dateClassObject. Also changed setDate to pass correct parameters } public int[] getDateOfHire() { // changed String[] to int[] because returned value of getDate() is a int array. return dateClassObject.getDate(); // changed to dateClassObject. Removed the parameter. } } A: In setDateOfHire just set the value instead of calling a method on it: public void setDateOfHire(int[] dateOfHire) { this.dateOfHire = dateOfHire; } Compare it with the way you implements the setters in the DateClass.
{ "language": "en", "url": "https://stackoverflow.com/questions/69654140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert Row if cell contains "&" Probably something simple I've missed, but I need to run down a column, and copy-insert any rows that have a "&" in the cell. I've managed to get it to here, but it's now just getting stuck on the very first cell with a "&", and won't move past it. Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Working") Dim rng As Range On Error Resume Next ws.Range("A2").Select Do Until ActiveCell.Offset(1, 0) = Empty If InStr(ActiveCell, "&") <> 0 Then GoTo InsertRow Else ActiveCell.Offset(1, 0).Select Loop InsertRow: Set rng = ActiveCell.Rows rng.Rows.Select Selection.Copy Selection.Insert Shift:=xlDown ActiveCell.Offset(2, 0).Select Resume Next There could be blanks in the column, but I can edit that later, so long as the macro can actually run past the first cell, we'll be fine. There are no error messages, as it just sticks to the first cell that contains a "&". That's the before and after, the second image shows the rows being copied out. A: * *no Select, Activate, ActiveCell, etc *no OnError *no Resume *iterate from bottom to top Option Explicit Sub dupAmps() Dim WS As Worksheet, C As Range Dim LR As Long Dim I As Long Set WS = Worksheets("sheet1") With WS LR = .Cells(.Rows.Count, 1).End(xlUp).Row End With For I = LR To 2 Step -1 Set C = WS.Cells(I, 1) If InStr(C, "&") > 0 Then C.EntireRow.Insert shift:=xlDown C.EntireRow.Copy C.Offset(-1, 0) End If Next I End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/56559495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get react URL in php for creating API? I want to get a URL which is coming from a React rout. URL is like: http://localhost:3001/users/[member_username] In which member_username will be dynamic as per the user name. So for example if a url hit like http://localhost:3001/users/gray then a variable will get gray or url hit like http://localhost:3001/users/john then a variable will get john Now i need to get that url into WordPress php file to create an API. I have tried this solution but did not getting the exact solution that is fit to my problem. Here is my API code that in which i need to get URL. function get_user_id(){ $server_name = $_SERVER['SERVER_NAME']; $user_name = basename("http://".$server_name."/users/admin"); // For now i have set the username as static, so it should be a dynamic as user hit the url. $users = get_user_by('login', $user_name); if( !empty($users) ){ foreach ($users as $key => $user) { $user_name = new stdClass(); $user_name->id = $user->ID; $user_name->user_login = $user->user_login; $user_name->user_nicename = $user->user_nicename; $user_name->user_email = $user->user_email; return $user_name; } } } /* * * Add action endpoint building * */ add_action( 'rest_api_init', function () { register_rest_route( 'rest-endpoints/v1', '/userid', array( 'methods' => 'GET', 'callback' => 'get_user_id' )); }); A: Could you let me know why that solution not fit for your problem? seems is ok to get the username. however, maybe you can try this <?php $url = parse_url('http://localhost:3001/users/yourname',PHP_URL_PATH); $url = str_replace("/users/","",$url); echo $url; ?> A: You can use: $url_path = parse_url('http://localhost:3001/users/a13/abc',PHP_URL_PATH); $url = preg_replace("/\/(?:[^\/]*\/)*/","",$url_path); echo $url; output: abc demo: https://regex101.com/r/19x7ut/1/ or this regex: \/(?:[^\/\s]*\/)* demo: https://regex101.com/r/19x7ut/3/ both should work fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/55626025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are the correct min and max values for Gluon maps zooming? I am trying out Gluon maps. As I understand it, Gluon maps uses OpenStreetMap which has a zoom range of 0 to 20 (but this value is not mentioned in the MapView javadoc). I create this code: public class MapTest2 extends Application { MapView mapView = new MapView(); MapPoint mapPoint = new MapPoint(51.509865d,-0.118092d); // London, England @Override public void start(Stage stage) throws Exception { StackPane sp = new StackPane(); sp.getChildren().add(mapView); mapView.setCenter(mapPoint); mapView.setZoom(42.8); // ? and -1.1 works but -1.3 fails Scene scene = new Scene(sp, 500, 300); stage.setScene(scene); stage.show(); } public static void main(String[] args) { MapTest2.launch(MapTest2.class, args); } } where I can set the positive zoom value far higher than 20. Some considerable zooming out on the mouse wheel returns me to a reasonable view. A zoom value of -1.1 works but -1.3 fails with: Exception in thread "main" java.lang.RuntimeException: Exception in Application start method : Caused by: java.lang.ArrayIndexOutOfBoundsException: Index -2 out of bounds for length 20 at com.gluonhq.impl.maps.BaseMap.loadTiles(BaseMap.java:347) at com.gluonhq.impl.maps.BaseMap.layoutChildren(BaseMap.java:490) : What are the real minimum and maximum zoom ranges, and should I use only integer values for zoom as there seems to be some rounding going on?
{ "language": "en", "url": "https://stackoverflow.com/questions/72043320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java- Using if statement inside a loop I wrote a small code : System.out.println("Please enter a number"); int number = scan.nextInt(); if(number == 1) { System.out.println("Number is 1"); } else if(number == 2) { System.out.println("Number is 2"); } else { System.out.println("Invalid selection"); } When the user enters a number different than 1 and 2, user gets "Invalid selection" message and then code terminates. I don't want it to terminate, I want it to run again until user writes 1 or 2. I tried do-while loop but it become an infinite loop. What are your suggestions? A: You can use while loop here Scanner scanner = new Scanner(System.in); boolean status = true; while (status) { // this runs if status is true System.out.println("Please enter a number"); int number = scanner.nextInt(); if (number == 1) { System.out.println("Number is 1"); status=false; // when your condition match stop the loop } else if (number == 2) { System.out.println("Number is 2"); status=false;// when your condition match stop the loop } else{ System.out.println("Invalid selection"); } } A: Try this... int number; do{ System.out.println("Please enter a number"); number = scan.nextInt(); if(number == 1) { System.out.println("Number is 1") ; } else if(number == 2) { System.out.println("Number is 2") ; } else { System.out.println("Invalid selection") ; } }while(number!=1 && number!=2); A: I recommend you check if there is an int with Scanner.hasNextInt() before you call Scanner.nextInt(). And, that makes a nice loop test condition if you use it in a while loop. Scanner scan = new Scanner(System.in); System.out.println("Please enter a number"); while (scan.hasNextInt()) { int number = scan.nextInt(); if (number == 1) { System.out.println("Number is 1"); break; } else if (number == 2) { System.out.println("Number is 2"); break; } else { System.out.println("Invalid selection"); } } // ... A: @Dosher, reposting @Raj_89's answer with correction in while loop condition. Please notice While loop condition int number = 0; do{ System.out.println("Please enter a number"); Scanner scan = new Scanner(System.in); number = scan.nextInt(); if(number == 1) { System.out.println("Number is 1") ; } else if(number == 2) { System.out.println("Number is 2") ; } else { System.out.println("Invalid selection") ; } }while(number==1 || number==2);
{ "language": "en", "url": "https://stackoverflow.com/questions/26751705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to query for default vendor from RPM: Error while executing process. while running streamsets I just followed the following tutorials for latest streamset 2.6.6 with flume as datacollector, https://github.com/streamsets/datacollector/blob/master/BUILD.md At the time of making the build i have faced the following error: [ERROR] Failed to execute goal org.codehaus.mojo:rpm-maven-plugin:2.1.2:attached-rpm (generate-sdc-streamsets-datacollector-aws-lib-rpm) on project streamsets-datacollector-aws-lib: Unable to query for default vendor from RPM: Error while executing process. Cannot run program "rpm": error=2, No such file or directory -> [Help 1]
{ "language": "en", "url": "https://stackoverflow.com/questions/44127780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: dropdown box with entry I have a list of some entries I want to sort the entries by entering some keyword. from tkinter import * from ttkwidgets.autocomplete import AutocompleteCombobox root = Tk() root.geometry("100x100") Phone_no = ["apple", "ball", "cat", "dog", "elephant"] new_list = [] def selected_list(event): match = [i for i in Phone_no if entry.get() in i] print(match) new_list.clear() # this for add data to the listbox for c in match: new_list.append(c) entry.config(completevalues=new_list) def printer(event): print(entry.get()) entry = AutocompleteCombobox(root, width=15, font=('Times', 10), completevalues=Phone_no) entry.place(x=10, y=10) print_button = Button(root, text="Print") print_button.bind("<Button-1>", printer) print_button.place(x=10, y=20) # Execute Tkinter root.mainloop() after the keyrelease the list was not updating and selectlist method is not calling , how to fix , advance thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/70722602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R How to read in a function I'm currently implementing a tool in R and I got stucked with a problem. I looked already in the forums and didn't found anything. I have many .csv files, which are somehow correlated with each other. The problem is I don't know yet how (this depends on the input of the user of the tool). Now I would like to read in a csv-file, that contains an arbitrary function f, e.g. f: a=b+max(c,d), and then the inputs, e.g. a="Final Sheet", b="Sheet1", c="Sheet2", d="Sheet3". (Maybe I didn't explained it very well, then I will upload a picture). Now my question is, can I somehow read that csv file in, such that I can later use the function f in the programm? (Of course the given function has to be common in R). I hope you understand my problem and I would appreciate any help or idea!! A: I would not combine data files with R source. Much easier to keep them separate. You put your functions in separate script files and then source() them as needed, and load your data with read.csv() etc. "Keep It Simple" :-) I am sure there's a contorted way of reading in the source code of a function from a text file and then eval() it somehow -- but I am not sure it would be worth the effort.
{ "language": "en", "url": "https://stackoverflow.com/questions/30435476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Save all values in Uppercase Laravel 5+ What would be the best way to save all values in the database as uppercase. So before saving convert all strings to uppercase. I see options to use Events or a trait would probably be best but not quite sure how to achieve this. I do not want to create accessors & mutators for each of my fields. Got this from : https://laracasts.com/discuss/channels/eloquent/listen-to-any-saveupdatecreate-event-for-any-model trait Trackable { public static function bootTrackable() { static::creating(function ($model) { // blah blah }); static::updating(function ($model) { // bleh bleh }); static::deleting(function ($model) { // bluh bluh }); } } Im not sure how I would be able to get the actual request values to convert them to uppercase? A: As @Louwki said, you can use a Trait to do that, in my case I did something like this: trait SaveToUpper { /** * Default params that will be saved on lowercase * @var array No Uppercase keys */ protected $no_uppercase = [ 'password', 'username', 'email', 'remember_token', 'slug', ]; public function setAttribute($key, $value) { parent::setAttribute($key, $value); if (is_string($value)) { if($this->no_upper !== null){ if (!in_array($key, $this->no_uppercase)) { if(!in_array($key, $this->no_upper)){ $this->attributes[$key] = trim(strtoupper($value)); } } }else{ if (!in_array($key, $this->no_uppercase)) { $this->attributes[$key] = trim(strtoupper($value)); } } } } } And in your model, you can specify other keys using the 'no_upper' variable. Like this: // YouModel.php protected $no_upper = ['your','keys','here']; A: Was a lot easier than I through. Solution that is working for me using traits, posting it if anyone also run into something like this. <?php namespace App\Traits; trait SaveToUpper { public function setAttribute($key, $value) { parent::setAttribute($key, $value); if (is_string($value)) $this->attributes[$key] = trim(strtoupper($value)); } } } UPDATE: For Getting values as upper case you can add this to the trait or just add it as a function in the model: public function __get($key) { if (is_string($this->getAttribute($key))) { return strtoupper( $this->getAttribute($key) ); } else { return $this->getAttribute($key); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/40132516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Webview causes infinite scrollable white space I have a layout which contained Webview inside NestedScrollview, <?xml version="1.0" encoding="utf-8"?> <com.app.swipetofinish.SwipeDownLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/postContainer" android:descendantFocusability="blocksDescendants" xmlns:app="http://schemas.android.com/apk/res-auto"> <android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/postDetails" android:background="?attr/backgroundColor"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:scaleType="fitXY" android:id="@+id/postFeaturedImage"/> <com.app.customizeviews.Lato_Bold_TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="?attr/primaryTextColor" android:letterSpacing="0.02" android:lineSpacingExtra="6sp" android:layout_marginStart="16dp" android:layout_marginTop="20dp" android:layout_marginEnd="16dp" android:id="@+id/postTitle" android:layout_below="@+id/postFeaturedImage"/> <com.app.customizeviews.Lato_Regular_TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/postDate" android:textColor="?attr/secondaryTextColor" android:textSize="14sp" android:layout_below="@+id/postTitle" android:layout_marginTop="8dp" android:layout_marginStart="16dp" /> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/postDate" android:layout_marginTop="12dp"/> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="50dp" android:id="@+id/progressBar" android:layout_centerHorizontal="true"/> </RelativeLayout> </android.support.v4.widget.NestedScrollView> <android.support.constraint.ConstraintLayout android:layout_width="match_parent" android:layout_height="?actionBarSize" app:layout_anchorGravity="bottom" app:layout_anchor="@id/postDetails" android:elevation="25dp" android:background="@drawable/bottom_post_card"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_ext_link_enabled" android:id="@+id/sourceLink" android:layout_marginStart="20dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_share_dark_article" android:id="@+id/postShare" app:layout_constraintStart_toEndOf="@id/sourceLink" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@id/postLike"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_like_article_unselected" android:id="@+id/postLike" app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toStartOf="@id/postBookmark" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toEndOf="@id/postShare"/> <TextSwitcher android:id="@+id/likesCount" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toStartOf="@+id/postBookmark" android:clipToPadding="false" android:inAnimation="@anim/slide_up" android:outAnimation="@anim/fade_out" android:layout_marginEnd="5dp" app:layout_constraintStart_toEndOf="@id/postLike" app:layout_constraintBottom_toBottomOf="@id/postLike" app:layout_constraintTop_toTopOf="@id/postLike" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_bookmark_article_unselected" android:layout_centerVertical="true" android:layout_marginEnd="20dp" android:layout_alignParentEnd="true" android:id="@+id/postBookmark" app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> </android.support.constraint.ConstraintLayout> </android.support.design.widget.CoordinatorLayout> and this working perfectly, but from last day it start causing infinite blank space after the web content ends, like this All the white blank space is caused by Webview after the main contents of Webview.This happens only when I open this layout in a fragment with ViewPager but not if layout open in layout with a single page activity. And also this working perfectly until yesterday from 2-3 months but from yesterday I'm getting this issue. Code for loading contents in Webview : mWebView.getSettings().setLoadWithOverviewMode(true); mWebView.getSettings().setUseWideViewPort(true); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setLoadsImagesAutomatically(true); mWebView.setVerticalScrollBarEnabled(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mWebView.setNestedScrollingEnabled(false); } else { mParentView.setNestedScrollingEnabled(false); } mWebView.loadDataWithBaseURL( "file:///android_asset/", content, "text/html", "utf-8", null); A: try to use wrap_content to RelativeLayout height attribute inside NestedScrollView like below code <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/postDetails" android:background="?attr/backgroundColor"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> //change here <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:scaleType="fitXY" android:id="@+id/postFeaturedImage"/> <com.app.customizeviews.Lato_Bold_TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="?attr/primaryTextColor" android:letterSpacing="0.02" android:lineSpacingExtra="6sp" android:layout_marginStart="16dp" android:layout_marginTop="20dp" android:layout_marginEnd="16dp" android:id="@+id/postTitle" android:layout_below="@+id/postFeaturedImage"/> <com.app.customizeviews.Lato_Regular_TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/postDate" android:textColor="?attr/secondaryTextColor" android:textSize="14sp" android:layout_below="@+id/postTitle" android:layout_marginTop="8dp" android:layout_marginStart="16dp" /> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/postDate" android:layout_marginTop="12dp"/> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="50dp" android:id="@+id/progressBar" android:layout_centerHorizontal="true"/> </RelativeLayout> </android.support.v4.widget.NestedScrollView>
{ "language": "en", "url": "https://stackoverflow.com/questions/48542412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is IsNaN(x) different from x == NaN where x = NaN Why are these two different? var x = NaN; //e.g. Number("e"); alert(isNaN(x)); //true (good) alert(x == NaN); //false (bad) A: The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN. Source This is the rule defined in IEEE 754 so full compliance with the specification requires this behavior. A: Nothing is equal to NaN. Any comparison will always be false. In both the strict and abstract comparison algorithms, if the types are the same, and either operand is NaN, the result will be false. If Type(x) is Number, then * *If x is NaN, return false. *If y is NaN, return false. In the abstract algorithm, if the types are different, and a NaN is one of the operands, then the other operand will ultimately be coerced to a number, and will bring us back to the scenario above. A: The following operations return NaN The divisions 0/0, ∞/∞, ∞/−∞, −∞/∞, and −∞/−∞ The multiplications 0×∞ and 0×−∞ The power 1^∞ The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions. Real operations with complex results: The square root of a negative number The logarithm of a negative number The tangent of an odd multiple of 90 degrees (or π/2 radians) The inverse sine or cosine of a number which is less than −1 or greater than +1. The following operations return values for numeric operations. Hence typeof Nan is a number. NaN is an undefined number in mathematical terms. ∞ + (-∞) is not equal to ∞ + (-∞). But we get that NaN is typeof number because it results from a numeric operation. From wiki:
{ "language": "en", "url": "https://stackoverflow.com/questions/14986361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IBM Cast Iron studio unable to convert '&' to '&' Hello I am constructing a URI from two different strings coming from a source. String1 = 12345&67890 String2 = 78326832 URI = /api?invoice=String1&supplier=String2 After using concat function available in studio, this is the final URI. /api?invoice=12345&67890&supplier=78326832 (Get request fails because 67890 is taken as query) Expected output is /api?invoice=12345&amp;67890&supplier=78326832 how do I achieve this, Can i use xslt to convert symbols to its HTML entity characters A: Your expected output /api?invoice=12345&amp;67890&supplier=78326832 is rather bizarre: there's no context where it makes sense to escape some ampersands (at the XML/HTML level) and leave others unescaped. I think that what you really want is to use URI escaping (not XML escaping) for the first ampersand, that is you want /api?invoice=12345%2667890&supplier=78326832. If you're building the URI using XSLT 2.0 you can achieve this by passing the strings through encode-for-uri() before you concatenate them into the URI. But you've given so little information about the context of your processing that it's hard to be sure exactly what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/49701279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to address a text field created within a symbol from main timeline in Flash using actionscript? How to address a text field created within a symbol from main timeline in Flash using actionscript? For example, if I have a text field named textfield inside a symbol named symbol1, which is input inside a movie clip called movieclip1, which is, of course, on the main timeline, what could I use to make the textfield half size of the movieclip? A: You need to assign a linkage name to the textField in the library first. Let's say you give it a linkage name of title. Now you can do title.width = title.parent.parent.width/2;
{ "language": "en", "url": "https://stackoverflow.com/questions/43072906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excel: DEC2HEX() wrong conversion !? How to fix or any other solution? The idea is to add hours to date time and convert to HEX. I have the following table: In column B i put the hours to add In column C i use formula: =INDIRECT(ADDRESS(ROW()-1,COLUMN()))+B3/24 , to calculate the new time In column D i use formula: =(C3-DATE(1970,1,1))*86400 , to calculate the timestamp In column E i use formula: ="0x"&DEC2HEX(D3) , to convert timestamp to HEX The problem: When converts D3 (timestamp) with DEC2HEX it's incorrect, but the other ones are OK (on the snipet) ! 0x59DC6FEF = 10/10/2017 06:59:59 0x59DC6FF0 = 10/10/2017 07:00:00 What is the solution ? I need to have correct conversions, that 1 second counts too A: This looks like some sort of rounding issue, the result in D3 is deemed to be very slightly below the actual value shown - try using ROUND function in column D, e.g. =ROUND((C3-DATE(1970,1,1))*86400,0)
{ "language": "en", "url": "https://stackoverflow.com/questions/47509235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opening a jQuery UI Dialog with dynamic links I have links generated dynamically based on content in a db. The links end up looking like <ul> <li><a href="/Updates/LoadArticle?NewsId=3" id="article">Article 3</a></li> <li><a href="/Updates/LoadArticle?NewsId=2" id="article">Article 2</a></li> <li><a href="/Updates/LoadArticle?NewsId=1" id="article">Article 1</a></li> </ul> The script I pieced together is $(document).ready(function () { $("#article").click(function (e) { InitializeDialog($("#news"), $(this).attr("href")); e.preventDefault(); $("#news").dialog("open"); }); //Method to Initialize the DialogBox function InitializeDialog($element, page) { $element.dialog({ autoOpen: true, width: 400, resizable: false, draggable: true, title: "Update", modal: true, show: 'fold', closeText: 'x', dialogClass: 'alert', closeOnEscape: true, position: "center", open: function (event, ui) { $element.load(page); }, close: function () { $(this).dialog('close'); } }); } }); This works for the first article in the list - the dialog opens, but the orther articles open in a separate page. I am assuming this is because the ids are not unique. My question is more so how to create a generic jQuery function for any id (say, article1, article2, etc.). I've had about 20 minutes of training on jQuery, so I am shooting in the dark on where to look. Thanks. A: This works for the first article in the list - the dialog opens, but the orther articles open in a separate page. I am assuming this is because the ids are not unique. You're right, having 2 or more elements with the same ID is invalid HTML and will cause you all sorts of problems. Remove the id attribute and use a class attribute instead: <ul> <li><a href="/Updates/LoadArticle?NewsId=3" class="article">Article 3</a></li> <li><a href="/Updates/LoadArticle?NewsId=2" class="article">Article 2</a></li> <li><a href="/Updates/LoadArticle?NewsId=1" class="article">Article 1</a></li> </ul> Then instead of: $("#article").click() Use: $(".article").click()
{ "language": "en", "url": "https://stackoverflow.com/questions/11972551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Telegraf.js bot create a user link without mentioning a user I am trying to send message via bot that contains a link to user profile, but problem is, that this mesage makes an annoying notification for user, with an '@' icon in chat group, is there a way to avoid that? const msg = data?.sort((a, b) => b.rating - a.rating) .reduce((acc, item, index) => { if (index > 14) return acc; acc += ` <a href="tg://user?id=${item.user_id}"><b>${item.user_name}</b></a> - ${item.rating}\n`; return acc; }, ''); ctx.replyWithHTML(`Top 15 gamers: ${msg}`, { disable_notification: true }).catch((err) => console.error(err)); that icon
{ "language": "en", "url": "https://stackoverflow.com/questions/73050860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scan Fb QRCode to login app I'm creating new application that scan Facebook QR Code to login. The result will same as u click "Login with Facebook" in website. But my app is use Facebook QR Code to do that. My app will scan the QR Code from your phone then it will login to my app by Facebook account. Now i'm done the scan code but don't know how to use that code to login as Facebook account. Please help me. Thank you. A: You need integrate facebook SDK. facebook developer
{ "language": "en", "url": "https://stackoverflow.com/questions/46271000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: String-Output: Class@# Lets say I have three classes: Class A: public class A { private String s; public A() { s = "blah"; } public void print() { System.out.println(s); } } Class B: public class B{ private A a[]; public B(){ a = new A[100]; for (int i=0; i<100;i++) { a[i] = new A(); } } public void print() { for (int i=0; i<100; i++) { a.print(); //SHOULD BE a[i].print(); } } } Class Main: public class Main { public static void main(String args[]) { B b = new B(); b.print(); } } Why do I get an outputpattern like B@#, where # is a number. I think it has something to do with indirect adressing but im not quite sure. Why doesn't it print out 100 s? A: You are printing the array rather than the object in the array. As a result, it is printing the address of the object (the number) and the object it is a member of. I suspect you wanted to call each of the prints, you should, in B.print(). You are also missing an increment for i, meaning it will loop indefinitely. for(int i = 0; i < 100; ++i) { a[i].print(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/16263919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scrapy Access Denied crawling the head of a website I wanna crawler a website, but I got the next error: '<head>\n<title>Access Denied</title>\n</head>' I just trying in the console: scrapy shell https://www.zara.com/es/en/ response.css("head").get() What I am doing wrong? Is related to the User-Agent? Does the website have an anti-crawling method? How can crawl this website? A: Set USER_AGENT = 'zara (+http://www.yourdomain.com)' in settings.py. Solves the issue. You could put your own user agent if you like also.
{ "language": "en", "url": "https://stackoverflow.com/questions/62892196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery mobile asp new page in iframe Well I have most of the problem figured out. But there is still a slight problem. The <iframe src="" doesn't seem to be behaving, it won't pick up the url in my data-popupurl="product.asp?itemid=[catalogid]. Anyone know why? <script> $( document ).on( "pageinit", "#page1", function() { $(".popupInfoLink").on("click", function(){ var url = $(this).data("popupurl"); $( "#popupInfo iframe" ).attr("src", url); }); }); </script> <a class="popupInfoLink" href="#popupInfo" data-rel="popup" data-position-to="window" data-popupurl="product.asp?itemid=[catalogid]"><img src= "/thumbnail.asp?file=[THUMBNAIL]&maxx=200&maxy=0" width="320" height="300" alt="pot" border="0" /></a> <div data-role="popup" id="popupInfo" data-overlay-theme="a" data-theme="d" data-tolerance="15,15" class="ui-content"> <iframe src="" width="800px" height="800px"></iframe> </div> You can see my problem here: https://www.kitchenova.com/mobile Just run a search for lets say "cookie" then click on a product. A blank pop-up comes up where the product.asp?itemid=[catalogid] should be loading. A: You can use the jQM popup widget with an iFrame. Here is a DEMO The link around the img now links to the popup id. I added a custom data attribute called data-popupurl that has the url for the iFrame and I added a class for a click handler as you will probably have multiple thumbnails on a page (NOTE: the data attribute could just hold the catalog id, or you could use another way to get the url): <a class="popupInfoLink" href="#popupInfo" data-rel="popup" data-position-to="window" data-popupurl="http://www.houzz.com/photos/6147609/T-Fal-I-Hoffmann-Stock-Pot-8-Qt--contemporary-cookware-and-bakeware-"><img src= "http://st.houzz.com/simgs/a1419d6702561831_3-4003/contemporary-cookware-and-bakeware.jpg" width="320" height="300" alt="pot" border="0" /></a> <div data-role="popup" id="popupInfo" data-overlay-theme="a" data-theme="d" data-tolerance="15,15" class="ui-content"> <iframe src="" width="400px" height="400px"></iframe> </div> The script simply responds to a click on the link by reading the url for the popup and then setting the iFrame src to that url. In your case the url would be product.asp?itemid=[catalogid] $( document ).on( "pageinit", "#page1", function() { $(".popupInfoLink").on("click", function(){ var url = $(this).data("popupurl"); $( "#popupInfo iframe" ).attr("src", url); }); }); A: Have a look at the target attribute of the anchor (a) tag. Here is the W3 Schools documentation. <a href="product.asp?itemid=[catalogid]" target="_blank"><img src= "/thumbnail.asp?file=[THUMBNAIL]&maxx=200&maxy=0" width="320" height="300" alt="[name]" border="0"></a> By the way, I strongly urge you not to do this. People don't like that, because they don't have a way of knowing that's the behavior before they do it. If people really want to open it in a new window or tab, then they can right click and do that. Keep one question per post is the Stack Overflow policy. But the best way to learn is by jumping in and doing tutorials. Don't ask questions until you've gotten seriously stuck. Part of learning to program is learning to figure things out on your own. A: So you don't want to pop open a new window, you want a dialog frame to appear overlayed on top of your other content? Have a look at the PopupControlExtender from the Ajax Control Toolkit. I don't know how well it will work in a jQuery Mobile environment, but it's worth a look. Sample code. <asp:Button runat="server" ID="Btn1" Text="Click Here For More Info" /> <ajaxToolkit:PopupControlExtender ID="PopEx" runat="server" TargetControlID="Btn1" PopupControlID="Panel1" Position="Bottom" /> <asp:Panel runat="server" id="Panel1"> Here is some more info! </asp:Panel> Or since you're using jQuery Mobile, why don't you stick with what they already provide for this? Have a look at jQuery Mobile panels or jQuery Mobile popups.
{ "language": "en", "url": "https://stackoverflow.com/questions/20710128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Global Variables in Y86 Assembly I'm trying to write a program that creates a sum of all inclusive integers between x and y, with the sum, y, and x being global variables. I'm running into problems when I try to assign the x and y to local registers (my simulator assigns the values of 0x60 and 0x64 to the local registers as opposed to 1 and 4) as well as taking the summed value and transferring that to the global variable of sum. Usually I try to find helpful guides online, but Y86 is such a sparingly used language that there is next to nothing. My code: .pos 0 init: irmovl Stack, %esp //Set up stack pointer irmovl Stack, %ebp //Set up base pointer call main //call main program halt //Terminate program main: pushl %ebp //setup rrmovl %esp, %ebp pushl %ebx //declaring x local register irmovl x, %ebx pushl %esi //declaring y local register irmovl y, %esi pushl %eax //declaring sum irmovl sum, %eax pushl %edi //constant of 1 irmovl $1, %edi L2: subl %ebx, %esi // %esi = y-x jl L3 // ends function if x > y irmovl y, %esi // %esi = y addl %ebx, %eax // sum += x addl %edi, %ebx // x++ jmp L2 // go to beginning of loop rmmovl %eax, (%eax) //value assigned to sum global variable L3: rrmovl %ebp, %esp //finish popl %ebx popl %esi popl %edi popl %eax popl %ebp ret .align 4 x: .long 1 y: .long 4 sum: .long 0 .pos 0x200 Stack: .long 0 A: I figured out why the registers were getting the wrong values (I was sending them the memory locations with irmovl instead of the values with mrmovl) and in a similar vein, how to assign the value to the global variable sum (rmmovl %eax, sum). It was a matter of addressing the content as opposed to location
{ "language": "en", "url": "https://stackoverflow.com/questions/27000732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to import image(SVG or PNG) in React using Create React App For example I have this <i> for Icon element <i style={{ backgroundImage: `url(${'./images/names/Mike.svg'}` }}/> I know I can import an image by importing them individually according to this post but it's not feasible in my case since I need to import a lot of them. Is there a workaround to make this possible in Create React App? Edit: I'm currently doing this backgroundImage: `url(${require(`./images/names/${name}.svg`)})` but still not working, unless I hard code the name backgroundImage: `url(${require(`assets/images/names/Mike.svg`)})` which is not viable in my case. A: Here are three ways to import an image (SVG and PNG) into a React project. You can use either file type with all three options. * *Import image and use it in a src attribute. *Import image and use it in a style attribute. *Dynamically insert into a require function. See examples below: import React from 'react'; import backgroundImg from '../assets/images/background.png'; import logoImg from '../assets/images/logo.svg'; const Test = props => { const imageLink = 'another.png' // const imageLink = props.image // You can loop this component in it's parent for multiple images. return ( <div> <img src={logoImg} style={{ width: '200px', height: '45px' }} /> <div style={{ width: '100%', height: '100%', backgroundImage: `url(${backgroundImg})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundSize: 'cover', position: 'fixed'}} /> <img width={900} height={500} alt="test img" src={require(`../assets/images/${imageLink}`)}/> </div> ) } export default Test
{ "language": "en", "url": "https://stackoverflow.com/questions/63630318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Local server port connectivity with R shinyApp I want to deploy shinyApp in local server. Is there any such code by which I can deploy shinyApps in local server. When I run shinyApp locally on desktop, it runs by IP: http://XXX.0.0.1:XXXX/ Every time I run the shinyApp it runs with different port number. I want to configure IP address at local server for shinyApp. I don't know how to do it. Is there any syntax/function like "rsconnect" to deploy shinyApp in local server? We know how to connect to MySQL. Similarly any such code by which we can connect to local server IP? code for connecting to MySQL: library(RMySQL) mydb = dbConnect(MySQL(), user='######', password='#######', dbname='#####', host='###.##.###.###', port=####) Any help would be greatly appreciated. A: Set the default values you want to initialize in (~/.Rprofile) under user directory options(shiny.port = 9999) options(shiny.host= xx.xx.xx.xx)
{ "language": "en", "url": "https://stackoverflow.com/questions/53984580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get files of user defined sizes C# I have been trying to find a way to display files that are within 1MB of user defined file size. so far I have tried this but it comes up as invalid DirectoryInfo folderInfo = new DirectoryInfo("C:\\Windows"); FileInfo[] files = folderInfo.GetFiles(); Console.WriteLine("Enter a file size in Bytes i.e 500 bytes"); int userSize = int.Parse(Console.ReadLine()); FileInfo[] files = files.GetLegnth(userSize); I am a beginner at this and I dont understand How I am supposed to get files within 1MB of user specified sizwe. Thank you in advance A: You could use the IEnumerable extension Where applied to your files array First you need to define the upper and lower limit of your allowed file sizes, then ask the Where extension to examine your files collection to extract the files that are between your limits int upperLimit = (1024 * 1024) + userSize; int lowerLimit = Math.Max(0, usersize - (1024 * 1024)); var result = files.Where(x => x.Length >= lowerLimit && x.Length <= upperLimit); foreach(FileInfo fi in result) Console.WriteLIne(fi.Name + " size = " + fi.Length); A: FileInfo[] files = files.GetLegnth(userSize); this is called wishful programming. Just hoping that the system will have a function that does exactly what you need. What you need to do in go through the files collection and look at each length in turn. SOmething like var matched = files.Where(f=>f.Size > userSize); if you like LINQ or foreach(var file in files) { if (file.Size>userSize) { } } if you dont note - I doubt this code works as typed, I have not read up on the data in a File object, there must be a Size of some sort A: You can try this code, please confirm, if this what you need using System; using System.IO; using System.Linq; namespace ConsoleApplication1 { internal class Program { private static void Main(string[] args) { DirectoryInfo folderInfo = new DirectoryInfo("C:\\Windows"); FileInfo[] files = folderInfo.GetFiles(); Console.WriteLine("Enter a file size in Bytes i.e 500 bytes"); int userSize = int.Parse(Console.ReadLine()); FileInfo[] totalFiles = files.Where(x => x.Length == userSize).ToArray(); } } } A: I won't provide a code in this answer, because it's really basic and you should be the one who finds the final solution. If you need to get files of size within some set bounds (+- 1MB for instance), you first need to get all the files and loop through them to find their sizes. In the loop you'd be checking if it's within these bounds or not. If it is, you can assign the file/size/whatever, into an array of found stuff. If not, simply go to the next file. I'd really AVOID linq solutions, because you need to learn and understand the principles first and then use shortcuts. Otherwise you'd be dependent on SO help for a looooong time. I'll just show you how you get the bounds, rest is up to you: Console.Write("Type the desired size in bytes: "); string userInput = Console.ReadLine(); int userSize = int.Parse(userInput); // you might consider using TryParse here int upperBound = userSize + 1048576; int lowerBound = userSize - 1048576; // get the files of a directory you want to search // loop through and compare their size // if their size is > or = to the lower bound // AND < or = to the upper bound, // you've found match and add it to results Just a note: 1048576 bytes = 1 megabyte Second note: you should probably check if the lower bound is higher or equal to zero, if the user typed in a valid number and so on...
{ "language": "en", "url": "https://stackoverflow.com/questions/27933339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How do I copy a string to the clipboard? I'm trying to make a basic Windows application that builds a string out of user input and then adds it to the clipboard. How do I copy a string to the clipboard using Python? A: I didn't have a solution, just a workaround. Windows Vista onwards has an inbuilt command called clip that takes the output of a command from command line and puts it into the clipboard. For example, ipconfig | clip. So I made a function with the os module which takes a string and adds it to the clipboard using the inbuilt Windows solution. import os def addToClipBoard(text): command = 'echo ' + text.strip() + '| clip' os.system(command) # Example addToClipBoard('penny lane') # Penny Lane is now in your ears, eyes, and clipboard. As previously noted in the comments however, one downside to this approach is that the echo command automatically adds a newline to the end of your text. To avoid this you can use a modified version of the command: def addToClipBoard(text): command = 'echo | set /p nul=' + text.strip() + '| clip' os.system(command) If you are using Windows XP it will work just following the steps in Copy and paste from Windows XP Pro's command prompt straight to the Clipboard. A: Looks like you need to add win32clipboard to your site-packages. It's part of the pywin32 package A: You can use pyperclip - cross-platform clipboard module. Or Xerox - similar module, except requires the win32 Python module to work on Windows. A: Not all of the answers worked for my various python configurations so this solution only uses the subprocess module. However, copy_keyword has to be pbcopy for Mac or clip for Windows: import subprocess subprocess.run('copy_keyword', universal_newlines=True, input='New Clipboard Value ') Here's some more extensive code that automatically checks what the current operating system is: import platform import subprocess copy_string = 'New Clipboard Value ' # Check which operating system is running to get the correct copying keyword. if platform.system() == 'Darwin': copy_keyword = 'pbcopy' elif platform.system() == 'Windows': copy_keyword = 'clip' subprocess.run(copy_keyword, universal_newlines=True, input=copy_string) A: The simplest way is with pyperclip. Works in python 2 and 3. To install this library, use: pip install pyperclip Example usage: import pyperclip pyperclip.copy("your string") If you want to get the contents of the clipboard: clipboard_content = pyperclip.paste() A: You can also use ctypes to tap into the Windows API and avoid the massive pywin32 package. This is what I use (excuse the poor style, but the idea is there): import ctypes # Get required functions, strcpy.. strcpy = ctypes.cdll.msvcrt.strcpy ocb = ctypes.windll.user32.OpenClipboard # Basic clipboard functions ecb = ctypes.windll.user32.EmptyClipboard gcd = ctypes.windll.user32.GetClipboardData scd = ctypes.windll.user32.SetClipboardData ccb = ctypes.windll.user32.CloseClipboard ga = ctypes.windll.kernel32.GlobalAlloc # Global memory allocation gl = ctypes.windll.kernel32.GlobalLock # Global memory Locking gul = ctypes.windll.kernel32.GlobalUnlock GMEM_DDESHARE = 0x2000 def Get(): ocb(None) # Open Clip, Default task pcontents = gcd(1) # 1 means CF_TEXT.. too lazy to get the token thingy... data = ctypes.c_char_p(pcontents).value #gul(pcontents) ? ccb() return data def Paste(data): ocb(None) # Open Clip, Default task ecb() hCd = ga(GMEM_DDESHARE, len(bytes(data,"ascii")) + 1) pchData = gl(hCd) strcpy(ctypes.c_char_p(pchData), bytes(data, "ascii")) gul(hCd) scd(1, hCd) ccb() A: You can use the excellent pandas, which has a built in clipboard support, but you need to pass through a DataFrame. import pandas as pd df=pd.DataFrame(['Text to copy']) df.to_clipboard(index=False,header=False) A: I think there is a much simpler solution to this. name = input('What is your name? ') print('Hello %s' % (name) ) Then run your program in the command line python greeter.py | clip This will pipe the output of your file to the clipboard A: Here's the most easy and reliable way I found if you're okay depending on Pandas. However I don't think this is officially part of the Pandas API so it may break with future updates. It works as of 0.25.3 from pandas.io import clipboard clipboard.copy("test") A: Actually, pywin32 and ctypes seem to be an overkill for this simple task. tkinter is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff. If all you need is to put some text to system clipboard, this will do it: from tkinter import Tk # in Python 2, use "Tkinter" instead r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append('i can has clipboardz?') r.update() # now it stays on the clipboard after the window is closed r.destroy() And that's all, no need to mess around with platform-specific third-party libraries. If you are using Python 2, replace tkinter with Tkinter. A: Widgets also have method named .clipboard_get() that returns the contents of the clipboard (unless some kind of error happens based on the type of data in the clipboard). The clipboard_get() method is mentioned in this bug report: http://bugs.python.org/issue14777 Strangely, this method was not mentioned in the common (but unofficial) online TkInter documentation sources that I usually refer to. A: Solution with stdlib, without security issues The following solution works in Linux without any additional library and without the risk of executing unwanted code in your shell. import subprocess def to_clipboard(text: str) -> None: sp = subprocess.Popen(["xclip"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) sp.communicate(text.encode("utf8")) Note that there multiple clipboard in Linux, the you use with the Middle Mouse (Primary) and yet another that you use pressing STRG+C,STRG+V. You can define which clipboard is used by adding a selection parameter i.e. ["xclip", "-selection", "clipboard"]. See the man xclip for details. If you using Windows, just replace xclip with clip. This solution works without Tkinter, which not available some Python installations (i.e. the custom build I am currently using). A: For some reason I've never been able to get the Tk solution to work for me. kapace's solution is much more workable, but the formatting is contrary to my style and it doesn't work with Unicode. Here's a modified version. import ctypes from ctypes.wintypes import BOOL, HWND, HANDLE, HGLOBAL, UINT, LPVOID from ctypes import c_size_t as SIZE_T OpenClipboard = ctypes.windll.user32.OpenClipboard OpenClipboard.argtypes = HWND, OpenClipboard.restype = BOOL EmptyClipboard = ctypes.windll.user32.EmptyClipboard EmptyClipboard.restype = BOOL GetClipboardData = ctypes.windll.user32.GetClipboardData GetClipboardData.argtypes = UINT, GetClipboardData.restype = HANDLE SetClipboardData = ctypes.windll.user32.SetClipboardData SetClipboardData.argtypes = UINT, HANDLE SetClipboardData.restype = HANDLE CloseClipboard = ctypes.windll.user32.CloseClipboard CloseClipboard.restype = BOOL CF_UNICODETEXT = 13 GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc GlobalAlloc.argtypes = UINT, SIZE_T GlobalAlloc.restype = HGLOBAL GlobalLock = ctypes.windll.kernel32.GlobalLock GlobalLock.argtypes = HGLOBAL, GlobalLock.restype = LPVOID GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock GlobalUnlock.argtypes = HGLOBAL, GlobalSize = ctypes.windll.kernel32.GlobalSize GlobalSize.argtypes = HGLOBAL, GlobalSize.restype = SIZE_T GMEM_MOVEABLE = 0x0002 GMEM_ZEROINIT = 0x0040 unicode_type = type(u'') def get(): text = None OpenClipboard(None) handle = GetClipboardData(CF_UNICODETEXT) pcontents = GlobalLock(handle) size = GlobalSize(handle) if pcontents and size: raw_data = ctypes.create_string_buffer(size) ctypes.memmove(raw_data, pcontents, size) text = raw_data.raw.decode('utf-16le').rstrip(u'\0') GlobalUnlock(handle) CloseClipboard() return text def put(s): if not isinstance(s, unicode_type): s = s.decode('mbcs') data = s.encode('utf-16le') OpenClipboard(None) EmptyClipboard() handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2) pcontents = GlobalLock(handle) ctypes.memmove(pcontents, data, len(data)) GlobalUnlock(handle) SetClipboardData(CF_UNICODETEXT, handle) CloseClipboard() paste = get copy = put The above has changed since this answer was first created, to better cope with extended Unicode characters and Python 3. It has been tested in both Python 2.7 and 3.5, and works even with emoji such as \U0001f601 (). Update 2021-10-26: This was working great for me in Windows 7 and Python 3.8. Then I got a new computer with Windows 10 and Python 3.10, and it failed for me the same way as indicated in the comments. This post gave me the answer. The functions from ctypes don't have argument and return types properly specified, and the defaults don't work consistently with 64-bit values. I've modified the above code to include that missing information. A: I've tried various solutions, but this is the simplest one that passes my test: #coding=utf-8 import win32clipboard # http://sourceforge.net/projects/pywin32/ def copy(text): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT) win32clipboard.CloseClipboard() def paste(): win32clipboard.OpenClipboard() data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) win32clipboard.CloseClipboard() return data if __name__ == "__main__": text = "Testing\nthe “clip—board”: " try: text = text.decode('utf8') # Python 2 needs decode to make a Unicode string. except AttributeError: pass print("%r" % text.encode('utf8')) copy(text) data = paste() print("%r" % data.encode('utf8')) print("OK" if text == data else "FAIL") try: print(data) except UnicodeEncodeError as er: print(er) print(data.encode('utf8')) Tested OK in Python 3.4 on Windows 8.1 and Python 2.7 on Windows 7. Also when reading Unicode data with Unix linefeeds copied from Windows. Copied data stays on the clipboard after Python exits: "Testing the “clip—board”: " If you want no external dependencies, use this code (now part of cross-platform pyperclip - C:\Python34\Scripts\pip install --upgrade pyperclip): def copy(text): GMEM_DDESHARE = 0x2000 CF_UNICODETEXT = 13 d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None) try: # Python 2 if not isinstance(text, unicode): text = text.decode('mbcs') except NameError: if not isinstance(text, str): text = text.decode('mbcs') d.user32.OpenClipboard(0) d.user32.EmptyClipboard() hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2) pchData = d.kernel32.GlobalLock(hCd) ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text) d.kernel32.GlobalUnlock(hCd) d.user32.SetClipboardData(CF_UNICODETEXT, hCd) d.user32.CloseClipboard() def paste(): CF_UNICODETEXT = 13 d = ctypes.windll d.user32.OpenClipboard(0) handle = d.user32.GetClipboardData(CF_UNICODETEXT) text = ctypes.c_wchar_p(handle).value d.user32.CloseClipboard() return text A: If you don't like the name you can use the derivative module clipboard. Note: It's just a selective wrapper of pyperclip After installing, import it: import clipboard Then you can copy like this: clipboard.copy("This is copied") You can also paste the copied text: clipboard.paste() A: Use pyperclip module Install using pip pip install pyperclip. * *https://pypi.org/project/pyperclip/ Copy text "Hello World!" to clip board import pyperclip pyperclip.copy('Hello World!') You can use Ctrl+V anywhere to paste this somewhere. Paste the copied text using python pyperclip.paste() # This returns the copied text of type <class 'str'> A: This is an improved answer of atomizer. Note that * *there are 2 calls of update() and *inserted 200 ms delay between them. They protect freezing applications due to an unstable state of the clipboard: from Tkinter import Tk import time r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append('some string') r.update() time.sleep(.2) r.update() r.destroy() A: In addition to Mark Ransom's answer using ctypes: This does not work for (all?) x64 systems since the handles seem to be truncated to int-size. Explicitly defining args and return values helps to overcomes this problem. import ctypes import ctypes.wintypes as w CF_UNICODETEXT = 13 u32 = ctypes.WinDLL('user32') k32 = ctypes.WinDLL('kernel32') OpenClipboard = u32.OpenClipboard OpenClipboard.argtypes = w.HWND, OpenClipboard.restype = w.BOOL GetClipboardData = u32.GetClipboardData GetClipboardData.argtypes = w.UINT, GetClipboardData.restype = w.HANDLE EmptyClipboard = u32.EmptyClipboard EmptyClipboard.restype = w.BOOL SetClipboardData = u32.SetClipboardData SetClipboardData.argtypes = w.UINT, w.HANDLE, SetClipboardData.restype = w.HANDLE CloseClipboard = u32.CloseClipboard CloseClipboard.argtypes = None CloseClipboard.restype = w.BOOL GHND = 0x0042 GlobalAlloc = k32.GlobalAlloc GlobalAlloc.argtypes = w.UINT, w.ctypes.c_size_t, GlobalAlloc.restype = w.HGLOBAL GlobalLock = k32.GlobalLock GlobalLock.argtypes = w.HGLOBAL, GlobalLock.restype = w.LPVOID GlobalUnlock = k32.GlobalUnlock GlobalUnlock.argtypes = w.HGLOBAL, GlobalUnlock.restype = w.BOOL GlobalSize = k32.GlobalSize GlobalSize.argtypes = w.HGLOBAL, GlobalSize.restype = w.ctypes.c_size_t unicode_type = type(u'') def get(): text = None OpenClipboard(None) handle = GetClipboardData(CF_UNICODETEXT) pcontents = GlobalLock(handle) size = GlobalSize(handle) if pcontents and size: raw_data = ctypes.create_string_buffer(size) ctypes.memmove(raw_data, pcontents, size) text = raw_data.raw.decode('utf-16le').rstrip(u'\0') GlobalUnlock(handle) CloseClipboard() return text def put(s): if not isinstance(s, unicode_type): s = s.decode('mbcs') data = s.encode('utf-16le') OpenClipboard(None) EmptyClipboard() handle = GlobalAlloc(GHND, len(data) + 2) pcontents = GlobalLock(handle) ctypes.memmove(pcontents, data, len(data)) GlobalUnlock(handle) SetClipboardData(CF_UNICODETEXT, handle) CloseClipboard() #Test run paste = get copy = put copy("Hello World!") print(paste()) A: also you can use > clipboard import clipboard def copy(txt): clipboard.copy(txt) copy("your txt") A: If (and only if) the application already uses Qt, you can use this (with the advantage of no additional third party dependency) from PyQt5.QtWidgets import QApplication clipboard = QApplication.clipboard() # get text (if there's text inside instead of e.g. file) clipboard.text() # set text clipboard.setText(s) This requires a Qt application object to be already constructed, so it should not be used unless the application already uses Qt. Besides, as usual, in X systems (and maybe other systems too), the content only persist until the application exists unless you use something like parcellite or xclipboard. Documentation: * *QGuiApplication Class | Qt GUI 5.15.6 *QClipboard Class | Qt GUI 5.15.6 See also: python - PyQT - copy file to clipboard - Stack Overflow A: import wx def ctc(text): if not wx.TheClipboard.IsOpened(): wx.TheClipboard.Open() data = wx.TextDataObject() data.SetText(text) wx.TheClipboard.SetData(data) wx.TheClipboard.Close() ctc(text) A: The snippet I share here take advantage of the ability to format text files: what if you want to copy a complex output to the clipboard ? (Say a numpy array in column or a list of something) import subprocess import os def cp2clip(clist): #create a temporary file fi=open("thisTextfileShouldNotExist.txt","w") #write in the text file the way you want your data to be for m in clist: fi.write(m+"\n") #close the file fi.close() #send "clip < file" to the shell cmd="clip < thisTextfileShouldNotExist.txt" w = subprocess.check_call(cmd,shell=True) #delete the temporary text file os.remove("thisTextfileShouldNotExist.txt") return w works only for windows, can be adapted for linux or mac I guess. Maybe a bit complicated... example: >>>cp2clip(["ET","phone","home"]) >>>0 Ctrl+V in any text editor : ET phone home A: Use python's clipboard library! import clipboard as cp cp.copy("abc") Clipboard contains 'abc' now. Happy pasting! A: You can use winclip32 module! install: pip install winclip32 to copy: import winclip32 winclip32.set_clipboard_data(winclip32.UNICODE_STD_TEXT, "some text") to get: import winclip32 print(winclip32.get_clipboard_data(winclip32.UNICODE_STD_TEXT)) for more informations: https://pypi.org/project/winclip32/ A: On Windows, you can use this. No external dependencies neither have to open sub-process: import win32clipboard def to_clipboard(txt): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(txt) win32clipboard.CloseClipboard() A: My multiplatform solution base on this question: import subprocess import distutils.spawn def clipit(text): if distutils.spawn.find_executable("xclip"): # for Linux subprocess.run(["xclip", "-i"], input=text.encode("utf8")) elif distutils.spawn.find_executable("xsel"): # for Linux subprocess.run(["xsel", "--input"], input=text.encode("utf8")) elif distutils.spawn.find_executable("clip"): # for Windows subprocess.run(["clip"], input=text.encode("utf8")) else: import pyperclip print("I use module pyperclip.") pyperclip.copy(text) A: you can try this: command = 'echo content |clip' subprocess.check_call(command, shell=True) A: Code snippet to copy the clipboard: Create a wrapper Python code in a module named (clipboard.py): import clr clr.AddReference('System.Windows.Forms') from System.Windows.Forms import Clipboard def setText(text): Clipboard.SetText(text) def getText(): return Clipboard.GetText() Then import the above module into your code. import io import clipboard code = clipboard.getText() print code code = "abcd" clipboard.setText(code) I must give credit to the blog post Clipboard Access in IronPython.
{ "language": "en", "url": "https://stackoverflow.com/questions/579687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "265" }
Q: Add Percent Sign to Tabulator Cells How can I concatenate a percent sign onto the the otperc (etc) field? I thought about adding it in the database call but I don't want to convert it to a string and not be able to sort it. function addTable(data) { var table = new Tabulator("#table", { height:205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value) data: data.rows, //assign data to table layout:"fitColumns", //fit columns to width of table (optional) columns:[ //Define Table Columns {title:"Work Type", field:"WorkType"}, {title:"Total", field:"total"}, {title:"On Time", field:"otperc"} ], }); } Here's a sample of the data data = [ {WorkType: 'ALTERNATIVE REPAIR', total: '47', otperc: 38}, {WorkType: 'BORING', total: '16182', otperc: 44} ] I'd like the On Time numbers to indicate percentage: A: According to this docs, you can write a custom formatter to alter how the data is displayed, without altering the underlying data. Example: function addTable(data) { var table = new Tabulator("#table", { height:205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value) data: data.rows, //assign data to table layout:"fitColumns", //fit columns to width of table (optional) columns:[ //Define Table Columns { title: "Work Type", field: "WorkType" }, { title: "Total", field: "total" }, { title: "On Time", field: "otperc", formatter: cell => cell.getValue() + "%" } ], }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/75616462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'or' and 'and' in same if statement I am wondering why this returns true: def parrot_trouble(talking, hour): if hour < 7 or hour > 20 and talking == True: return True else: return False print(parrot_trouble(False, 6)) Is it because you can't have 'or' and 'and' operators in same if statement? Or other reason? A: This is, because AND has priority over OR, so you have TRUE OR (FALSE AND FALSE) resulting in TRUE The extensive list of Operator Precedence can be found here: Most importantly are () > not > and > or > So to give priority to your OR operator use () (hour < 7 or hour > 20) and talking == True => (TRUE OR FALSE) AND FALSE => FALSE A: To give some more background to the already posted answer: This is based on operator precedence as explained here: https://docs.python.org/3/reference/expressions.html The higher the precedence the stronger it binds its two parts. You can image that like addition and multiplication in maths. There, multiplications bind stronger. Here, the and binds stronger as written in a different answer. A: It's about the operator's precedence In order to make that work you will need to specify the order of operators with parantheses. def parrot_trouble(talking, hour): if (hour < 7 or hour > 20) and talking == True: return True else: return False print(parrot_trouble(False, 6)) What is in parantheses will be executed first and then compared to and.
{ "language": "en", "url": "https://stackoverflow.com/questions/65062347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: compile and execute java program with external jar file I understand this has been asked for multiple times, but I am really stuck here and if it is fairly easy, please help me. I have a sample java program and a jar file. Here is what is inside of the java program (WriterSample.java). // (c) Copyright 2014. TIBCO Software Inc. All rights reserved. package com.spotfire.samples; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.Random; import com.spotfire.sbdf.BinaryWriter; import com.spotfire.sbdf.ColumnMetadata; import com.spotfire.sbdf.FileHeader; import com.spotfire.sbdf.TableMetadata; import com.spotfire.sbdf.TableMetadataBuilder; import com.spotfire.sbdf.TableWriter; import com.spotfire.sbdf.ValueType; /** * This example is a simple command line tool that writes a simple SBDF file * with random data. */ public class WriterSample { public static void main(String[] args) throws IOException { // The command line application requires one argument which is supposed to be // the name of the SBDF file to write. if (args.length != 1) { System.out.println("Syntax: WriterSample output.sbdf"); return; } String outputFile = args[0]; // First we just open the file as usual and then we need to wrap the stream // in a binary writer. OutputStream outputStream = new FileOutputStream(outputFile); BinaryWriter writer = new BinaryWriter(outputStream); // When writing an SBDF file you first need to write the file header. FileHeader.writeCurrentVersion(writer); // The second part of the SBDF file is the metadata, in order to create // the table metadata we need to use the builder class. TableMetadataBuilder tableMetadataBuilder = new TableMetadataBuilder(); // The table can have metadata properties defined. Here we add a custom // property indicating the producer of the file. This will be imported as // a table property in Spotfire. tableMetadataBuilder.addProperty("GeneratedBy", "WriterSample.exe"); // All columns in the table needs to be defined and added to the metadata builder, // the required information is the name of the column and the data type. ColumnMetadata col1 = new ColumnMetadata("Category", ValueType.STRING); tableMetadataBuilder.addColumn(col1); // Similar to tables, columns can also have metadata properties defined. Here // we add another custom property. This will be imported as a column property // in Spotfire. col1.addProperty("SampleProperty", "col1"); ColumnMetadata col2 = new ColumnMetadata("Value", ValueType.DOUBLE); tableMetadataBuilder.addColumn(col2); col2.addProperty("SampleProperty", "col2"); ColumnMetadata col3 = new ColumnMetadata("TimeStamp", ValueType.DATETIME); tableMetadataBuilder.addColumn(col3); col3.addProperty("SampleProperty", "col3"); // We need to call the build function in order to get an object that we can // write to the file. TableMetadata tableMetadata = tableMetadataBuilder.build(); tableMetadata.write(writer); int rowCount = 10000; Random random = new Random(); // Now that we have written all the metadata we can start writing the actual data. // Here we use a TableWriter to write the data, remember to close the table writer // otherwise you will not generate a correct SBDF file. TableWriter tableWriter = new TableWriter(writer, tableMetadata); for (int i = 0; i < rowCount; ++i) { // You need to perform one addValue call for each column, for each row in the // same order as you added the columns to the table metadata object. // In this example we just generate some random values of the appropriate types. // Here we write the first string column. String[] col1Values = new String[] {"A", "B", "C", "D", "E"}; tableWriter.addValue(col1Values[random.nextInt(5)]); // Next we write the second double column. double doubleValue = random.nextDouble(); if (doubleValue < 0.5) { // Note that if you want to write a null value you shouldn't send null to // addValue, instead you should use theInvalidValue property of the columns // ValueType. tableWriter.addValue(ValueType.DOUBLE.getInvalidValue()); } else { tableWriter.addValue(random.nextDouble()); } // And finally the third date time column. tableWriter.addValue(new Date()); } // Finally we need to close the file and write the end of table marker. tableWriter.writeEndOfTable(); writer.close(); outputStream.close(); System.out.print("Wrote file: "); System.out.println(outputFile); } } The jar file is sbdf.jar, which is in the same directory as the java file. I can now compile with: javac -cp "sbdf.jar" WriterSample.java This will generate a WriterSample.class file. The problem is that when I try to execute the program by java -cp .:./sbdf.jar WriterSample I got an error message: Error: Could not find or load main class WriterSample What should I do? Thanks! A: You should use the fully qualified name of the WriterSample, which is com.spotfire.samples.WriterSample and the correct java command is: java -cp .:././sbdf.jar com.spotfire.samples.WriterSample
{ "language": "en", "url": "https://stackoverflow.com/questions/50501028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make wordpress spacious theme full width? Currently i have large sections of whitespace on the left and right margins on all my pages which i would like to remove. I have managed to amend the width of the page using the following CSS #main .inner-wrap { max-width: 97%; } However i am having difficult finding code to amend the width of the content? My website is www.monoalarms.co.uk/wp Thanks A: Actually, I see a lot of current containers being set: max-width in css. You can take a look at some classes: inner-wrap, elementor-widget-container, ... then set: - max-width: 100% !important; - Remove padding or margin if it needs A: .inner-wrap { max-width: 100% !important; float: left; width: 100%; } .inner-wrap .elementor-container { max-width: 94% !important; } header .inner-wrap { padding: 0 30px; } Try With this one
{ "language": "en", "url": "https://stackoverflow.com/questions/51398650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a new trace while removing the last one? I am new to shiny and plotly. What I'm trying to do is to add a trace first and then I want it to be replaced by a new one every time I click on a button. here is my minimal example: library(shiny) library(plotly) ui <- fluidPage(plotlyOutput("fig1"), numericInput("A", label = h5("A"), value = "", width = "100px"), numericInput("B", label = h5("B"), value = "", width = "100px"), actionButton("action3", label = "Add to plot"), actionButton("action4", label = "Remove point") ) server <- function(input, output) { A <- 1:5 B <- c(115, 406, 1320, 179, 440) data <- data.frame(A, B) fig <- plot_ly(data, x = A, y = B, type = 'scatter', mode = 'markers') output$fig1 <- renderPlotly(fig) observeEvent(input$action3, { vals <- reactiveValues(A = input$A, B = input$B) plotlyProxy("fig1") %>% plotlyProxyInvoke("addTraces", list(x = c(vals$A,vals$A), y = c(vals$B,vals$B), type = "scatter", mode = "markers" ) ) }) observeEvent(input$action4, { vals <- reactiveValues(A = input$A, B = input$B) plotlyProxy("fig1") %>% plotlyProxyInvoke("deleteTraces") }) } shinyApp(ui,server) I can add a new trace easily but they all remain on the plot. My solution was to add a new button to delete the trace but it did not work. I have already read this but I couldn't make it work. A: Based on what you described, it sounds like you want to add a trace and remove the most recent trace added at the same time when the button is pressed. This would still leave the original plot/trace that you started with. I tried simplifying a bit. The first plotlyProxyInvoke will remove the most recently added trace (it is zero-indexed, leaving the first plotly trace in place). The second plotlyProxyInvoke will add the new trace. Note that the (x, y) pair is included twice based on this answer. library(shiny) library(plotly) A <- 1:5 B <- c(115, 406, 1320, 179, 440) data <- data.frame(A, B) ui <- fluidPage(plotlyOutput("fig1"), numericInput("A", label = h5("A"), value = "", width = "100px"), numericInput("B", label = h5("B"), value = "", width = "100px"), actionButton("action3", label = "Add to plot"), ) server <- function(input, output, session) { fig <- plot_ly(data, x = A, y = B, type = 'scatter', mode = 'markers') output$fig1 <- renderPlotly(fig) observeEvent(input$action3, { plotlyProxy("fig1", session) %>% plotlyProxyInvoke("deleteTraces", list(as.integer(1))) plotlyProxy("fig1", session) %>% plotlyProxyInvoke("addTraces", list(x = c(input$A, input$A), y = c(input$B, input$B), type = 'scatter', mode = 'markers') ) }) } shinyApp(ui,server)
{ "language": "en", "url": "https://stackoverflow.com/questions/69091610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Logout so the back button doesn't return to profile The code I have below is an OnClick logout method from an app. All it does at present is return the user to the login page, however if the user presses the back button on the Android phone, it brings them back to the page they've just logged out from, which I don't want it to. How can I change my code so that it doesn't let the back button take the user back to their profile without logging in again? public void OpenMain(View view){ startActivity(new Intent(this, MainActivity.class)); } The php code for logging in is below: <?php require "conn.php"; $username = $_POST["username"]; $password = $_POST["password"]; $mysql_qry = "select * from users where username like '$username' and password like '$password';"; $result = mysqli_query($conn, $mysql_qry); if(mysqli_num_rows($result) > 0) { echo "Successful login"; } else{ echo "Login not successful"; } ?> A: You can add flags that specify that the new activity will replace the old one: public void openMain(View view){ Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); }
{ "language": "en", "url": "https://stackoverflow.com/questions/43217074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Local object value is being saved between function calls (maybe scopes misunderstanding) I am confused trying to solve a task of "flattening" a list of lists. For example, I've got a list [1, [2, 2, 2], 4] - I need to transform it to [1, 2, 2, 2, 4].I solved it that way: def flat_list(array, temp_list=[]): for item in array: if str(item).isdigit(): temp_list.append(item) else: temp_list = flat_list(item, temp_list) return temp_list But when I test it: assert flat_list([1, 2, 3]) == [1, 2, 3] assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4] assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7] the value of "temp_list" is being transferred between function calls. The value of "temp_list" in the beginning of the second assert is [1, 2, 3] - the value of "return" of first assert - but not the "[]". As I guess, this is because I have some misunderstanding of scopes and "return" instruction but I don't understand what exactly. A: It's a known issue in Python. Default parameter values are always evaluated when, and only when, the “def” statement they belong to is executed Ref: http://effbot.org/zone/default-values.htm In your code example, the temp_list's default value is evaluated when the def statement is executed. And thus it's set to an empty list. On subsequent calls, the list just keeps growing because the temp_list's default values are no longer evaluated and it keeps using the list instance it created the first time. This could be a work around: def flat_list(array, temp_list=None): if not temp_list: temp_list = [] for item in array: if str(item).isdigit(): temp_list.append(item) else: temp_list = flat_list(item, temp_list) return temp_list Here, we have passed None instead of the empty list. And then inside the function body we check the value and initialize an empty list as we need.
{ "language": "en", "url": "https://stackoverflow.com/questions/35071194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to wait until the user finished the tasks after grecaptcha.execute()? reCAPTCHA v2 invisible I would like to make my own website, where I use reCAPTCHA. However, I don't know how to wait after grecaptcha.execute() until the user has completed the tasks. Because now the link is called directly without passing the tasks. For the rest I use the standard Google Script https://developers.google.com/recaptcha/docs/invisible It is the reCAPTCHA v2 invisible. I would be happy about answers. <script src="https://www.google.com/recaptcha/api.js" async defer></script> <script> function onSubmit(token) { grecaptcha.execute().then(var vslg = document.getElementById("vslg").value; window.location.replace("url"); } </script> </head> <body> <a class="button"></a> <div class="topBar"> </div> <div class="underTopBar"> <form action="JavaScript:onSubmit()" class="flex-itemform form" method="POST" id="formV"> <table> <tr> <td> <div> <input type="text" id="vslg" required> </div> </td> <td> <div> <div class="g-recaptcha" data-sitekey="..." data-callback="onSubmit" data-size="invisible"> </div> <input type="submit" class="buttonDesign" value="Senden"> </div> </td> <tr> </table> </form> </div> A: I have spent more than 3 hours on this nonsense. It turned out to be a straightforward problem. I hope I can help somebody with this answer. First, you must realize that you need 2 JavaScript functions. 1- A one that is executed after the submit button is pressed. In this function, always use: event.preventDefault() to avoid form submission! You don't want to submit your form yet. grecaptcha.execute() to initiate the reCAPTCHA. You can execute this function with the submit button (onClick property). 2- A one that is executed after the reCAPTCHA is solved successfully. For this function, you only need: document.getElementById("form").submit() to submit your form. To execute this function, use data-callback property in your reCAPTCHA div element. As you can see in the docs, data-callback property is defined as The name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback. That's all you need. Make sure that your form only gets submitted with the second function you created, nothing else. A: The following code does this: * *The <button class="g-recaptcha"... is the Automatically bind the challenge to a button. It will automatically trigger the invisible recaptcha when the button is clicked. *Once the recaptcha is completed it will add a hidden field named g-recaptcha-response which contains the token and then run the onSubmit callback which submits the form. <head> <script src="https://www.google.com/recaptcha/api.js" async defer></script> <script> function onSubmit() { document.getElementById("formV").submit(); } </script> </head> <body> <a class="button"></a> <div class="topBar"> </div> <div class="underTopBar"> <form class="flex-itemform form" method="POST" id="formV"> <table> <tr> <td> <div> <button class="g-recaptcha buttonDesign" data-sitekey="..." data-callback="onSubmit" data-size="invisible">Senden</button> </div> </td> <tr> </table> </form> </div> Important: You still need to verify the token g-recaptcha-response server side. See Verifying the user's response. Without verifying the token, adding the recaptcha to the frontend doesn't stop anyone from submitting the form.
{ "language": "en", "url": "https://stackoverflow.com/questions/64324592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Div Br Image Column 1px Misalignment Only the very last image of the column misaligns by 1px when I code this way. I know 2 other ways to code to get the result without the misalignment, (using ul or using multiple div in a row without any br), but it's disappointing cuz this seemed even simpler to me. What's the reason this happens!? div.a { margin: 0; overflow: auto; padding: 0; text-align: center; word-wrap: break-word; } ul.b { list-style-type: none; margin: 0; padding: 0; text-align: center; } <div class="a"> <img src="http://www.gloryhood.com/images/free-will-1.png" alt="free will determinism and indeterminism" /> <br /> <img src="http://www.gloryhood.com/images/free-will-1.png" alt="free will determinism and indeterminism" /> <br /> <img src="http://www.gloryhood.com/images/free-will-1.png" alt="free will determinism and indeterminism" /> </div> <br /> <ul class="b"> <li><img src="http://www.gloryhood.com/images/free-will-2.png" alt="daniel wegner's conditions of human action" /></li> <li><img src="http://www.gloryhood.com/images/free-will-2.png" alt="daniel wegner's conditions of human action" /></li> </ul> Example page (I included the ul column just for comparison): http://www.gloryhood.com/articles/zzzztest.html A: Add this in you img class img { display: block; /*Add this*/ height: auto; margin: 0 auto;/*Add this*/ max-width: 100%; } Hope it will helps you. A: it is because of the <br /> at the end of the first 2 images, I solved it by putting a <br /> at the end of the last image and it worked. div.a { margin: 0; overflow: auto; padding: 0; text-align: center; word-wrap: break-word; } ul.b { list-style-type: none; margin: 0; padding: 0; text-align: center; } <div class="a"> <img src="http://www.gloryhood.com/images/free-will-1.png" alt="free will determinism and indeterminism" /> <br /> <img src="http://www.gloryhood.com/images/free-will-1.png" alt="free will determinism and indeterminism" /> <br /> <img src="http://www.gloryhood.com/images/free-will-1.png" alt="free will determinism and indeterminism" /> <br /> </div> <br /> <ul class="b"> <li><img src="http://www.gloryhood.com/images/free-will-2.png" alt="daniel wegner's conditions of human action" /></li> <li><img src="http://www.gloryhood.com/images/free-will-2.png" alt="daniel wegner's conditions of human action" /></li> </ul> A: I found another solution! You can just div each individual image. <div> <img src="link" alt="" /> </div> <div> <img src="link" alt="" /> </div> <div> <img src="link" alt="" /> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/29430710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: syntax of if condition within animate of jquery How do i write if condition within animate for the following? $($("#tabs > ul"), $(this).parent()).animate({ marginLeft: '+=' + marginleft }, '10000', 'swing'); A: Could fit your need: As IDs must be unique on context page, that selector is better $("#tabs > ul").animate({ marginLeft: '+=' + marginleft }, { step: function (fx) { if(someCondition) $(this).stop(true); } }, '10000', 'swing'); Or for more global condition, use @billyonecan's answer A: If I understand the question correctly, you can use the conditional operator: $($("#tabs > ul"), $(this).parent()).animate({ marginLeft: (condition ? 'value if true' : 'value if false') }, '10000', 'swing');
{ "language": "en", "url": "https://stackoverflow.com/questions/17544357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Make action bar "up navigation" trigger dialogfragment Can I make the action bar's "up" navigation trigger a confirmation dialogfragment that says "Are you sure you would like to go back?" A: Intercepting the up ActionBar button press is trivial because everything is done through onOptionsItemSelected. The documentation, recommends that you use android.R.id.home to go up with NavUtils (provided that you set the metadata for the parent activity so NavUtils doesn't throw an Exception, etc): @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } Your DialogFragment should offer an confirmation to actually go back. Since you're now working with the Fragment and not the Activity, you're going to want to pass getActivity() to NavUtils. NavUtils.navigateUpFromSameTask(getActivity()); and change onOptionsItemSelected() to @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: new ConfirmationDialog().show(getSupportFragmentManager(), "confirmation_dialog"); return true; } return super.onOptionsItemSelected(item); } ConfirmationDialog is your custom DialogFragment. Note that for this example, I am using the support Fragment APIs,. If you are not, make sure to change getSupportFragmentManager() to getFragmentManager(). A: Yes. Pressing the "up" button just calls the option menu callback with R.id.home. So you could just grab that, display the dialog box and if the positive button is pressed call NavUtils.navigateUpTo().
{ "language": "en", "url": "https://stackoverflow.com/questions/21102818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TFS Build 2008 - Why is everything getting dumped in one folder? When I build my solution, it dumps all the binaries into one folder. How can I cause it to split up the files by project like Visual Studio does? A: Just edit your TFSBuild.proj file for the build, and add this to opne of the property groups: <CustomizableOutDir>true</CustomizableOutDir> This will automatically then cause the build to output the build output as per normal (like Visual Studio).
{ "language": "en", "url": "https://stackoverflow.com/questions/2815702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python rename file - replace all underscores with space I am using python to rename all files in a directory with extension ".ext". The script is in the same folder as the files so no need to worry about path. How to replace all underscores in filenames with spaces? For example filename This_is_a_file 01 v2.22.ext to This is a file 01 v2.22.ext? I have tried the below code: import glob, re, os for filename in glob.glob('*.ext'): new_name = re.sub("_", " ", filename) # this line does work os.rename(filename, new_name) Edit: Sorry, I had a logic error elsewhere in my code. There were more replacement lines than I showed here but I was assigning new_name to replacements of filename instead of updating new_name at each step. The above code should work. A: it's a simple replacement, no need to use regex. use this instead: new_name = filename.replace('_', ' ') A: You could try something like this: import glob, re, os for filename in glob.glob('*.ext'): new_name = ' '.join(filename.split('_')) # another method os.rename(filename, new_name) Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/60180340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Algorithm mixing information of two arrays of objects in javascript? Problem I have this array const cards = [ {id: "29210z-192011-222", power: 0.9}, // Card A {id: "39222x-232189-12a", power: 0.2} // Card B ... ] My firestore database looks like this: cards (collection) -> cardId (document) -> userId (a "Foreign Key" to the card's owner, in the document data) So, I get the corresponding owner for each card I have in my array: const documentRefs = cards.map((card) => firestore.collection("cards").doc(card.id) ); const rivalPlayers = db.collection("cards") .getAll(...documentRefs) .then((docs) => { return docs.map(doc => { console.log(doc.data); // { userId: "219038210890-234-22-a" } /* TODO - Here I need to return an object containing the userId (from doc.data) and the power of the card which referenced him */ }) }) .catch(err => throw err); As you can see in the code, I need as result an array "rivalPlayers" looking like this: [{userId: "219038210890-234-22-a", power: 0.9}, {userId: "519aa821Z890-219-21-e", power: 0.2}] Pd: This array can't contain the current user, so I filter it Question Does anybody know how to mix the arrays information in this situation? I mean, in the moment I map the documents from firebase I have the userId (which correspond to a card from the cards array) and the cardId (doc.id, as each document id in my database is a card id), but I don't know how to get each power with a good performance. I would appreciate that the solution is written in modern javascript. Thanks. My best approach const rivalPlayers = db.collection("cards") .getAll(...documentRefs) .then((docs) => { return docs.map(doc => ({ userId: doc.data.userId, power: cards.filter(card => card.id === doc.id)[0].power // <----------- That is the main point of the question })).filter(player => player.userId !== currentUser.userId) // This part is irrelevant to my question }) .catch(err => throw err); Try this code fast I know that this scenario is a little long to build, as you have to recreate the firebase database, etc... Here is the same code without fetching data from firebase: const cards = [ {id: "29210z-192011-222", power: 0.9}, // Card A {id: "39222x-232189-12a", power: 0.2} // Card B ] const usersIds = [ { id: "39222x-232189-12a", // Firebase doc.id === card id data: { userId: "329u4932840" // Id of the owner of the card } }, { id: "29210z-192011-222", // Firebase doc.id === card.id data: { userId: "8u4394343" // Id of the owner of the card } } ] const rivalPlayers = usersIds.map(doc => ({ userId: doc.data.userId, power: cards.filter(card => card.id === doc.id)[0].power })); console.log(rivalPlayers) Try it on https://playcode.io/ for example. A: Put all the power values in a Map so you only need to iterate through cards once instead of running a filter() many times const cards = [{id: "29210z-192011-222", power: 0.9}, {id: "39222x-232189-12a", power: 0.2}]; const powerMap = new Map(cards.map(({id, power}) => [id, power])); const wantedId = "39222x-232189-12a" console.log('Power for id:', wantedId , 'is:', powerMap.get(wantedId))
{ "language": "en", "url": "https://stackoverflow.com/questions/63538940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to mount AWS EFS inside docker using docker-compose? I have an efs drive, with shared files, that i want to mount inside docker containers to be run on ECS. AWS has a suggested way to do it using task definition. However, I want to do it using docker-compose and not change task definitions that we manage through console etc. I am attaching snippet I am using below, but shared drive doesn't get mounted and gives following error per below. It comes as empty and doesnt show shared efs. Can someone suggests as to what am I doing incorrectly here and how can i change dockerfile or docker-compose yml to get desired results. docker-compose.yml version: "3.9" services: server: build: . image: xyz command: "gunicorn -w 4 -k uvicorn.workers.UvicornWorker app.server:server -b 0.0.0.0:8000" volumes: - type: volume source: efs_volume target: /mnt/efs_xyz volumes: efs_volume: driver: local driver_opts: type: "nfs4" o: "addr=fs-xxxxxx.efs.useast1.amazonaws.com,rw,nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport" device: ":/" Below is my Dockerfile FROM python:3.8-slim-buster RUN apt-get update -y && apt-get install -y \ vim \ g++ \ unixodbc-dev \ && rm -rf /var/lib/apt/lists/* COPY requirements.txt Docker* docker* .docker* ./app/ RUN python -m pip install --no-cache-dir -r requirements.txt Error when running docker-compose up Cannot start service server: error while mounting volume '/var/lib/docker/volumes/app_efs_volume/_data': failed to mount local volume: mount :/:/var/lib/docker/volumes/app_efs_volume/_data, data: addr=fs-0bb4dbbf.efs.us-east-1.amazonaws.com,nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport: invalid argument A: As per this answer, only type: nfs (not type: nfs4) allows to use addr=<hostname>.
{ "language": "en", "url": "https://stackoverflow.com/questions/68290180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: cloud_package.cspkg file was not created after installing "socket.io-servicebus" I'd like to use the "socket.io-servicebus" module to my node.js application. But I encountered that a problem. After installing the "socket.io-servicebus", cloud_package.cspkg file was not created by "Publish-AzureServiceProject" command. I'm using "Windows Azure PowerShell" on Windows7 64bit edition. Here is the procedure. * *New-AzureServiceProject test1 *Add-AzureNodeWebRole www *cd www *npm install socket.io-servicebus *Publish-AzureServiceProject -ServiceName xxx ... [ cloud_package.cspkg will not created ] By the way "Start-AzureEmulator -Launch" will be succeeded and we can test own application. Please give me some advices. thank you. A: It looks like the issue here is due to a known path length limitation. Azure has a limitation on paths in the package being more than 255 chars and in this case bringing in socket.io WITH all of it's dependencies is hitting that path. There are several possible work arounds here. A. - Zip up node modules and extract on the server. Basically you zip up your modules and publish the module zip within the package. Then you can use an Azure startup task (in your cscfg) on the server to unzip the files. Publish-AzureServicePackage will grab anything in the project, so in this case you just have a little script that you run before publishing which creates the node_modules archive and deletes node_modules. I am planning to do a blog post on this, but it is actually relatively easy to do. B. - Download node modules dynamically You can download modules in the cloud. This can also be done with a startup task as is shown here. If you look in that post you will see how you can author a startup task if you decide to do the archive route. Feel free to ping me with any questions.
{ "language": "en", "url": "https://stackoverflow.com/questions/16604211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Efficiently check if elements lie between closed intervals I have a tuple x with elements as x = (2, 3, 4, 5). I also have another data structure that holds closed intervals with the number of elements equal to the number of elements in the tuple x, as y = ((2,3), (3.5, 4.5), (6, 9), (4, 7)). Now, I can set up a nested loop and check if each element of x lies within the respective intervals in y. But the issue is that it takes too long for a tuple with 10000 elements. Although efficiency might not matter, I do want the code to run fast. Note: By efficient I do mean time wise, where the code runs faster than any other 'obvious' solutions. I was wondering if there was a more efficient way to do this using Python instead of the obvious nested loop? This seems to be only possible with the nested loops solution. I don't have any code as I can not figure the question out. If I could have hints as to how to make it efficient then please provide them. A: Welcome to SO. Although this is definitely not efficient for a small tuple, for a large one this will speed up the process greatly (from an O(n^2) solution to an O(n)). I hope this helps. x = (2, 3, 4, 5) y = ((2, 3), (3.5, 4.5), (6, 9), (4, 7)) for a, b in enumerate(y): if b[0] <= x[a] <= b[1]: print(f'{x[a]} is in between {b}.') else: print(f'{x[a]} is not in between {b}') For boolean values: interval = lambda t, i: [b[0] <= t[a] <= b[1] for a, b in enumerate(i)] x = (2, 3, 4, 5) y = ((2, 3), (3.5, 4.5), (6, 9), (4, 7)) print(interval(x, y)) All within linear (O(n)) time! Thanks for reading and have a great day. A: You can achieve this in linear time using one loop. You only have to iterate once on both of the tuples, something like this: x = (2, 3, 4, 5) y = ((2,3), (3.5, 4.5), (6, 9), (4, 7)) for index, number in enumerate(x): if number > y[index][1] or number < y[index][0]: print(f'{number} is NOT in {y[index}') else: print(f'{number} is in {y[index]}') the output is: 2 is in the interval (2, 3) 3 is NOT in the interval (3.5, 4.5) 4 is NOT in the interval (6, 9) 5 is in the interval (4, 7) As i said, this solution will take O(n), instead of O(n^2) A: What about something like this >>> x = (2, 3, 4, 5) >>> y = ((2,3), (3.5, 4.5), (6, 9), (4, 7)) >>> def f(e): ... p, (q, r) = e ... return q <= p <= r >>> list(map(f, zip(x,y))) [True, False, False, True]
{ "language": "en", "url": "https://stackoverflow.com/questions/74882492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is it possible to create a local view in PL SQL procedure? I'm looking for a solution that tell Oracle "this query is meant to be reused like a view" (and if I ask, it's that I don't want to/can't create a full global view if possible). With the following minimal model (I left out other colums): * *There are owners which own books. *A books have authors and chapters. *A chapters have books (ex: chapter included in another format of the book) and authors. *An authors have at least one _authors_related_data1_ and several _authors_related_data2_. And the same can go on with _authors_related_data3_, ..., _authors_related_dataN_. Thus the following create statement (I did not validate them against Oracle, it's more for the understanding of the question than for testing). create table owners( owner_id number not null, constraint pk_owners primary key (owner_id)); create table books( book_id number not null, constraint pk_books primary key (book_id)); create table authors( author_id number not null, constraint pk_authors primary key (author_id)); create table chapters( chapter_id number not null, constraint pk_chapters primary key (chapter_id)); create table owned_books( owner_id number not null, book_id number not null, constraint pk_owned_books primary key (owner_id, book_id), constraint fk_owned_books_1 foreign key (owner_id) references owners (owner_id), constraint fk_owned_books_2 foreign key (book_id) references books (book_id) ); create table book_authors( book_id number not null, author_id number not null, constraint pk_book_authors primary key (book_id, author_id), constraint fk_book_authors_1 foreign key (author_id) references authors (author_id), constraint fk_book_authors_2 foreign key (book_id) references books (book_id) ); create table chapter_authors( chapter_id number not null, author_id number not null, constraint pk_chapter_authors primary key (chapter_id, author_id), constraint fk_chapter_authors_1 foreign key (author_id) references authors (author_id), constraint fk_chapter_authors_2 foreign key (chapter_id) references chapters (chapter_id) ); create table book_chapters( chapter_id number not null, book_id number not null, constraint pk_book_chapters primary key (chapter_id, book_id), constraint fk_book_chapters_1 foreign key (chapter_id) references chapters (chapter_id) constraint fk_book_chapters_2 foreign key (book_id) references books (book_id) ); create table authors_related_data1( author_id number not null, constraint pk_authors_related_data1 primary key (author_id), constraint fk_authors_related_data1_1 foreign key (author_id) references authors (author_id) ); create table authors_related_data2( data_id number not null, author_id number not null, constraint pk_authors_related_data2 primary key (data_id), constraint authors_related_data2 foreign key (author_id) references authors (author_id) ); The queries (and the duplicate parts) that I want to do: with v_books as ( select books.book_id from owned_books inner join books on books.book_id = owned_books.book_id where owned_books.owner_id = P_OWNER_ID ), v_authors as ( select authors.author_id from v_books inner join book_authors on book_authors.book_id = v_books.book_id inner join authors on authors.author_id = book_authors.author_id union select authors.author_id from v_books inner join book_chapters on book_chapters.book_id = v_books.book_id inner join chapter_authors on chapter_authors.chapter_id = book_chapters.chapter_id inner join authors on authors.author_id = book_chapters.author_id ) select authors_related_data1.* from v_authors inner join authors_related_data1 on authors_related_data1.author_id = v_authors.author_id ; with v_books as ( select books.book_id from owned_books inner join books on books.book_id = owned_books.book_id where owned_books.owner_id = P_OWNER_ID ), v_authors as ( select authors.author_id from v_books inner join book_authors on book_authors.book_id = v_books.book_id inner join authors on authors.author_id = book_authors.author_id union select authors.author_id from v_books inner join book_chapters on book_chapters.book_id = v_books.book_id inner join chapter_authors on chapter_authors.chapter_id = book_chapters.chapter_id inner join authors on authors.author_id = book_chapters.author_id ) select authors_related_data2.* from v_authors inner join authors_related_data2 on authors_related_data2.author_id = v_authors.author_id ; The first part (with ...) is the same for both queries. A view like that would be great: create view v_owned_authors as ( with v_books as ( select books.book_id from owned_books inner join books on books.book_id = owned_books.book_id ) ( select authors.author_id from v_books inner join book_authors on book_authors.book_id = v_books.book_id inner join authors on authors.author_id = book_authors.author_id union select authors.author_id from v_books inner join book_chapters on book_chapters.book_id = v_books.book_id inner join chapter_authors on chapter_authors.chapter_id = book_chapters.chapter_id inner join authors on authors.author_id = book_chapters.author_id ) ; The previous queries would be as simple as: select authors_related_data2.* from v_owned_authors inner join authors_related_data2 on authors_related_data2.author_id = v_authors.author_id where v_owned_authors.owner_id = P_OWNER_ID But: * *The set of owned books might be too big, and the view would not have the P_OWNER_ID parameter and to lessen the owned books clause. So, for performance reason I'd like to avoid the view because I don't think Oracle will be able to optimize such use case. *For various (and legit) reasons, I can't. A: You could use a table function or a pipelined function Here's an example of a table function from: http://oracle-base.com/articles/misc/pipelined-table-functions.php CREATE TYPE t_tf_row AS OBJECT ( id NUMBER, description VARCHAR2(50) ); / CREATE TYPE t_tf_tab IS TABLE OF t_tf_row; / -- Build the table function itself. CREATE OR REPLACE FUNCTION get_tab_tf (p_rows IN NUMBER) RETURN t_tf_tab AS l_tab t_tf_tab := t_tf_tab(); BEGIN FOR i IN 1 .. p_rows LOOP l_tab.extend; l_tab(l_tab.last) := t_tf_row(i, 'Description for ' || i); END LOOP; RETURN l_tab; END; / -- Test it. SELECT * FROM TABLE(get_tab_tf(10)) ORDER BY id DESC; Here's an example of a pipelined function: CREATE OR REPLACE FUNCTION get_tab_ptf (p_rows IN NUMBER) RETURN t_tf_tab PIPELINED AS r t_tf_row%rowtype; BEGIN for z in (select id, desc from sometalbe) loop r.id := z.id; r.description := z.desc; PIPE ROW(r); END LOOP; RETURN; END; A: Would procedure like this meet your needs? create or replace procedure p_statement (cur in out sys_refcursor) is begin open cur for select 1 num from dual union select 2 num from dual; end; (I put there select from dual, instead you could replace it with your complex query and define variable to be fetch into accordingly) the actual call could be like this: declare mycur sys_refcursor; num number; begin p_statement(mycur); LOOP FETCH mycur INTO num; EXIT WHEN mycur%NOTFOUND; DBMS_OUTPUT.put_line(num); END LOOP; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/28971025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using Cloudflare ssl for nginx container show error: "ERR_SSL_VERSION_OR_CIPHER_MISMATCH" I'm trying to config ssl for My website, I use Cloudflare to generate a origin certificate. This is my nginx config: I can access my website by IP and view the certificate: But when I access by domain, it show ERR_SSL_VERSION_OR_CIPHER_MISMATCH How Can I fix it. I expect that my website have https when access to domain.
{ "language": "en", "url": "https://stackoverflow.com/questions/75256601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Arraylist Pass from fragment to activity Intent intent = new Intent(getActivity(), loadactivity.class); intent.putExtra("Arraylist", imagearraylist); startActivity(intent) A: Hope this will help you! Paste the following code in your activity. ArrayList<Object> imagearraylist = (ArrayList<Object>) getIntent().getSerializableExtra("Arraylist"); Reference: How to pass ArrayList<CustomeObject> from one activity to another? A: Use Interface Like Mentioned In Link Passing Data Between Fragments to Activity Or You Can Simply Use Public static ArrayList<String> imagearraylist; (Passing Huge Arraylist Through Intent May Leads To Crash) A: For this, you have to use interface public interface arrayInterface { public void onSetArray(ArrayList<T>); } Implement this interface in your activity public class YrActivity extends Activity implements arrayInterface.OnFragmentInteractionListener { private ArrayList<T> allData; @override public void arrayInterface(ArrayList<T> data) { allData = data; } } Then you have to send the data with listner arrayInterface listener = (arrayInterface) activity; listener.onSetArray(allData) And its done
{ "language": "en", "url": "https://stackoverflow.com/questions/58110161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: App not authenticating with React-Native I am learning React-Native and trying to do oAuth2 authentication. I have registered my app with the service and my redirect uri. When the user clicks on the "login' button on the app, it is supposed to do the following: onLoginPressed() { fetch("https://www.hackerschool.com/oauth/authorize?response_type=code&client_id=("+auth.client_id+")&redirect_uri=("+auth.redirect_uri+")") .then(response => _handleResponse(response)) .catch(error => this.setState({ isLoading: false, message: 'Something bad happened ' + error })); LinkingIOS.openURL("https://www.hackerschool.com/oauth/authorize?response_type=code&client_id=("+auth.client_id+")&redirect_uri=("+auth.redirect_uri+")"); } However, the response is the complete html render instead of the token that bounces me back to my redirect_uri which is my app. Any ideas as to what I am doing wrong? A: One thing to check is that Xcode is searching the library headers properly (especially with LinkingIOS). "This step is not necessary for libraries that we ship with React Native with the exception of PushNotificationIOS and LinkingIOS." Linking React Native Libraries in Xcode A: Is the LinkingIOS.openURL function supposed to run after a response from the server in the fetch block? If so, then you'll want to include it in a another then block. As it is written now, LinkingIOS.openURL will run right after the fetch line. Then, as they resolve or error out, the then and catch blocks of fetch will run.
{ "language": "en", "url": "https://stackoverflow.com/questions/29731829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java 3d Charts JavaGnuplotHybrid I want to write software for 3D charts in java.I found something like gnuplot and JavaGnuplotHybrid and this example: JGnuplot jg = new JGnuplot(); Plot plot0 = new Plot("2d plot") { String xlabel = "'x'", ylabel = "'y'"; }; double[] x = { 1, 2, 3, 4, 5 }, y1 = { 2, 4, 6, 8, 10 }, y2 = { 3, 6, 9, 12, 15 }; DataTableSet dts = plot0.addNewDataTableSet("Simple plot"); dts.addNewDataTable("2x", x, y1); dts.addNewDataTable("3x", x, y2); jg.execute(plot0, jg.plot2d); The code works and shows chart. I do not know how to begin 3d graph if someone could write such a beautiful simple example of a single point on the 3D graph ? A: Here is the code for an example 3d graph: public void plot3d() { JGnuplot jg = new JGnuplot(); Plot plot = new Plot("") { { xlabel = "x"; ylabel = "y"; zlabel = "z"; } }; double[] x = { 1, 2, 3, 4, 5 }, y = { 2, 4, 6, 8, 10 }, z = { 3, 6, 9, 12, 15 }, z2 = { 2, 8, 18, 32, 50 }; DataTableSet dts = plot.addNewDataTableSet("3D Plot"); dts.addNewDataTable("z=x+y", x, y, z); dts.addNewDataTable("z=x*y", x, y, z2); jg.execute(plot, jg.plot3d); } It produces the following figure: Here are more examples: 2D Plot, Bar Plot, 3D Plot, Density Plot, Image Plot...
{ "language": "en", "url": "https://stackoverflow.com/questions/33802575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: libgdx: Calculate points along CatmullRomSpline that are same distance apart? I am building a 3D game in which the camera follows a sequence of predefined paths (which are imported from curves drawn in Blender). At load time, I extract the Blender curve points and use these to create path splines using the CatmullRomSpline class. Screenshot indicates what I mean (I have shifted the camera aside to view the path - light blue boxes represent fixed points along the camera path). At the moment, I am using Blender to define how many points should be in my imported splines - this in turn determines the speed at which the camera moves along the path (fixed points). This works OK, but there is inconsistency between different splines (different number of control points etc). What I actually want is the ability to move along the spline by some fixed distance in each "tick", so that the overall camera movement is more consistent. I've changed my path calculation logic to take the spline length into consideration, and then use a 'step length' to calculate the spline points. However, I'm still getting inconsistent distances between spline points. I'm fairly sure I'm missing something obvious - any ideas? //duplicate first and last control points //ref: http://stackoverflow.com/questions/29198881/drawing-a-catmullromspline-in-libgdx-with-an-endpoint-and-startpoint splineDataset[0] = splineDataset[1].cpy(); splineDataset[splineDataset.length - 1] = splineDataset[splineDataset.length - 2].cpy(); CatmullRomSpline<Vector3> workingCatMull = new CatmullRomSpline<Vector3>(splineDataset, false); //calculate spline length trackLength = workingCatMull.approxLength(NUM_SPLINE_SAMPLES_FOR_LENGTH_CALC); float DISTANCE_PER_PATH_TICK = 0.01f; int numPathTicks = (int)(trackLength / DISTANCE_PER_PATH_TICK); for(int i = 0; i < numPathTicks; ++i) { //calculate spline point Vector3 workingVector = new Vector3(); float splinePercentage = ((float)i) / ((float)numPathTicks-1); workingCatMull.valueAt(workingVector, splinePercentage); //offset path point by specified value workingVector.add(positionOffset); //add spline point to camera path listOfPathPoints.add(workingVector); }
{ "language": "en", "url": "https://stackoverflow.com/questions/32034180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Only one connection to a remote api or each component its own connection I have created an api that connects to another outside api. Now i am not sure how to design my way of connections within my project. What is the better way one connection or each class each own connection. A: One connection manager with api usable from your classes would probably be best. By implementing as a service for other classes, it keeps all the code for connections in one place where it can be modified once instead of all over the place. Also, it us usually a good rule to keep your objects to a single purpose so each can do what it needs to do and then aggregate simple objects into components and services.
{ "language": "en", "url": "https://stackoverflow.com/questions/38043486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle exceptions: "ERROR] FATAL UNHANDLED EXCEPTION:" I created a class dubPrime that takes an integer that must be a double digit. If it isn't a double digit the program is supposed to throw an exception. However my program crashes and outputs "[ERROR] FATAL UNHANDLED EXCEPTION" whenever I try to create an object that is not a double digit. *I used the factory design pattern so that the object wouldn't be created if it doesn't meet the standards. Is there a way to circumvent this so that my program doesn't crash? private DubPrime(bool upArg, bool enabledArg, uint xArg){ x = xArg; up = upArg; enabled = enabledArg; } public static DubPrime GetDubPrime(bool upArg = true, bool enabledArg = true, uint xArg = lowerLimit){ //x must be double digit if(xArg<lowerLimit || xArg>upperLimit) throw new ArgumentException("x should be a double digit"); else{ return new DubPrime(upArg, enabledArg, xArg); } } Update: Whenever I try to add a try/catch block the compiler says "not all code paths return a value." Is it necessary to return something? Could I throw an exception and not have it return something? public static DubPrime GetDubPrime(bool upArg = true, bool enabledArg = true, uint xArg = lowerLimit){ try{ if(xArg<lowerLimit || xArg>upperLimit) throw new ArgumentException("x should be a double digit"); else{ return new DubPrime(upArg, enabledArg, xArg); } } catch(Exception e){ Console.WriteLine(e.Message); } } A: You need to outside of GetDubPrime catch the ArgumentException that you throw inside it. If nothing catches the exception the program exits. Something like: (...) try { x = GetDubPrime(...); } catch(ArgumentException ex) { // bad data, do something Console.WriteLine(ex.Message); x = 0; // or whatever is necessary } (...)
{ "language": "en", "url": "https://stackoverflow.com/questions/66926160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Does Data Sms Count Towards Android Sms Limit? I understand that Android has a 30 sms in 30 minutes limit, but does this also apply to data sms? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/38748228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ActionController::ParamaterMissing while running test. From Chapter 7 of Hartl's Tutorial Currently doing Hartl's (updated) Tutorial and I'm stuck at the end of Chapter 7 [7.5.3 to be specific, Production Deployment]. I'm running a test and getting the following error: 1) Error: UsersSignupTest#test_invalid_signup_information: ActionController::ParameterMissing: param is missing or the value is empty: user app/controllers/users_controller.rb:24:in `user_params' app/controllers/users_controller.rb:12:in `create' test/integration/users_signup_test.rb:8:in `block (2 levels) in <class:UsersSignupTest>' test/integration/users_signup_test.rb:7:in `block in <class:UsersSignupTest>' 2) Error: UsersSignupTest#test_valid_signup_information: ActionController::ParameterMissing: param is missing or the value is empty: user app/controllers/users_controller.rb:24:in `user_params' app/controllers/users_controller.rb:12:in `create' test/integration/users_signup_test.rb:19:in `block (2 levels) in <class:UsersSignupTest>' test/integration/users_signup_test.rb:18:in `block in <class:UsersSignupTest>' users_controller.rb class UsersController < ApplicationController def show @user = User.find(params[:id]) end def new @user = User.new end def create @user = User.new(user_params) if @user.save flash[:success] = "Welcome to the Sample App!" redirect_to @user else render 'new' end end private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end end users_signup_test.rb require 'test_helper' class UsersSignupTest < ActionDispatch::IntegrationTest test "invalid signup information" do get signup_path assert_no_difference 'User.count' do post users_path, params: { user: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } } end end test "valid signup information" do get signup_path assert_difference 'User.count', 1 do post users_path, params: { user: { name: "Example User", email: "user@example.com", password: "password", password_confirmation: "password" } } end follow_redirect! assert_template 'users/show' end end A: You have params, instead of user. Change this: params: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } } end end to this: user: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } } end end A: The signature of the post (and the other HTTP request methods) has change between Rails 4 and Rails 5. So send a user param in Rails 4 use this: post user_path, { user: { name: 'foo' } } Whereas in Rails 5 use this: post user_path, params: { user: { name: 'foo' } } Hartl's Rails Tutorial was updated to Rails 5 recently. But I guess you are still running Rails 4. That means: remove nesting of the params or update your app to Rails 5.
{ "language": "en", "url": "https://stackoverflow.com/questions/38253394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Install dependent project from git repositroy I have some trouble with dependency of composer. My basic project has the following json file: "require": { "klabs/side-menu-widget": "dev-master" }, "repositories": [ { "type": "git", "url": "git@bitbucket.org:klabsers/side-menu-widget.git" } ] And klabs/side-menu-widget has the following composer.json file: { "name": "klabs/side-menu-widget", "description": "Responsive side menu widget for Yii 2 framework", "type": "yii2-extension", "keywords": [ "yii", "extension", "widget", "yii2", "yii 2", "menu", "bootstrap" ], "homepage": "https://bitbucket.org/klabsers/side-menu-widget/overview", "license": "BSD-3-Clause", "authors": [ { "name": "Urmat Zhenaliev", "email": "sonkei@ya.ru", "homepage": "http://prosoft.kg", "role": "Developer" } ], "support": { "issues": "https://bitbucket.org/klabsers/side-menu-widget/issues", "source": "https://bitbucket.org/klabsers/side-menu-widget" }, "require": { "yiisoft/yii2": "*", "klabs/font-awesome-asset": "dev-master" }, "autoload": { "psr-4": { "klabs\\widgets\\menu\\side\\": "" } }, "repositories": [ { "type": "git", "url": "git@bitbucket.org:klabsers/font-awesome-asset.git" } ] } Take a not to "require": { "yiisoft/yii2": "*", "klabs/font-awesome-asset": "dev-master" }, This project (klabs/side-menu-widget) requires another git repository named klabs/font-awesome-asset, that has the following composer.json file: { "name": "klabs/font-awesome-asset", "description": "Font Awesome css framework asset manager for Yii 2 framework", "type": "yii2-extension", "keywords": [ "yii", "extension", "widget", "asset", "assets", "yii2", "yii 2", "menu", "font", "font-awesome", "awesome" ], "homepage": "https://bitbucket.org/klabsers/font-awesome-asset/overview", "license": "BSD-3-Clause", "authors": [ { "name": "Urmat Zhenaliev", "email": "sonkei@ya.ru", "homepage": "http://prosoft.kg", "role": "Developer" } ], "support": { "issues": "https://bitbucket.org/klabsers/font-awesome-asset/issues", "source": "https://bitbucket.org/klabsers/font-awesome-asset" }, "require": { "yiisoft/yii2": "*" }, "autoload": { "psr-4": { "klabs\\assets\\font_awesome\\": "" } } } But when I try to install klabs/side-menu-widget I get the error: And my quiestion is - Is it available to autoload git respository dependency without including it in my basic project and if yes what am I doing wrong? A: Seem that child composer file is ignored https://getcomposer.org/doc/04-schema.md#repositories Repositories are not resolved recursively. You can only add them to your main composer.json
{ "language": "en", "url": "https://stackoverflow.com/questions/38117841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableView repeating background with 2 images So I'm trying to make a UITableView that has a repeating background. I want the background to scroll with the text. The catch is that the background is 2 images. There is a top image that is about 550px in height, and then a repeater image that's 2px in height. I want the top image to scroll with the table view and then eventually go off the top and then the segment image just repeats. This view actually sits below a UITableView in a view controller. Here's my drawrect for the background. I call setNeedsDisplay when ever the tableview on top scrolls. -(void)drawRect:(CGRect) rect { CGRect topRect = CGRectMake(0, _tableViewRect.origin.y, 320, min( max(0, CGImageGetHeight(top) - _tableViewRect.origin.y), _tableViewRect.size.height)); CGRect segmentRect = CGRectMake(0, topRect.size.height, 320, _tableViewRect.size.height - topRect.size.height); if(topRect.size.height > 0) { CGImageRef newImageRef = CGImageCreateWithImageInRect(top, topRect); UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; [newImage drawAtPoint:CGPointMake(0,0)]; } [[UIImage imageWithCGImage: segment] drawAsPatternInRect:segmentRect]; } It works but it is very chuggy on my 3G. Does anyone have any optimization tips, or another way of doing this? Cheers A: Don't create a new image each time; cache your UIImage, then use CoreGraphics calls to reposition your CGContextRef to 'point' to the right area, blit the image there, and move on. If you were to profile the code above, I imagine that CGImageCreateWithImageInRect() was taking up the vast majority of your cycles. You should probably do this using contentOffset, rather than whatever _tableViewRect is. Also, looking at your code, while getting rid of the stuff above will help, I'm not sure it'll be enough, since you'll be redrawing a LOT. That said, here's a snippet that may work: //I'm not sure what _tableViewRect is, so let's just assume you've got //some variable, tableScrollY, that represents the scroll offset of your table CGContextRef context = UIGraphicsGetCurrentContext(); if (tableScrollY < top.size.height) { //okay, we need to draw at least PART of our image CGContextSaveGState(context); CGContextDrawImage(context, CGRectMake(0, -tableScrollY, top.size.width, top.size.height), top.CGImage); } This should be a replacement for the middle if(...) portion of your code. This is not tested, so you may need to futz with it a bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/1767695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Gradle not including dependencies in published pom.xml I have a Gradle project I'm using the maven-publisher plugin to install my android library to maven local and a maven repo. That works, but the generated pom.xml does not include any dependency information. Is there a workaround to include that information, or am I forced to go back to the maven plugin and do all the manual configuration that requires? Researching I realized that I'm not telling the publication where the dependencies are, I'm only specifying the output/artifact, so I need a way to link this MavenPublication to the dependencies, but I have not yet found how to do that in the documentation. ------------------------------------------------------------ Gradle 1.10 ------------------------------------------------------------ Build time: 2013-12-17 09:28:15 UTC Build number: none Revision: 36ced393628875ff15575fa03d16c1349ffe8bb6 Groovy: 1.8.6 Ant: Apache Ant(TM) version 1.9.2 compiled on July 8 2013 Ivy: 2.2.0 JVM: 1.7.0_60 (Oracle Corporation 24.60-b09) OS: Mac OS X 10.9.2 x86_64 Relevant build.gradle sections //... apply plugin: 'android-library' apply plugin: 'robolectric' apply plugin: 'maven-publish' //... repositories { mavenLocal() maven { name "myNexus" url myNexusUrl } mavenCentral() } //... android.libraryVariants publishing { publications { sdk(MavenPublication) { artifactId 'my-android-sdk' artifact "${project.buildDir}/outputs/aar/${project.name}-${project.version}.aar" } } repositories { maven { name "myNexus" url myNexusUrl credentials { username myNexusUsername password myNexusPassword } } } } Generated pom.xml: <?xml version="1.0" encoding="UTF-8"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>org.example.android</groupId> <artifactId>my-android-sdk</artifactId> <version>gradle-SNAPSHOT</version> <packaging>aar</packaging> </project> A: With gradle 3 implemention was introduced. Replace compile with implementation. Use this instead. pom.withXml { def dependenciesNode = asNode().appendNode('dependencies') configurations.implementation.allDependencies.each { def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', it.group) dependencyNode.appendNode('artifactId', it.name) dependencyNode.appendNode('version', it.version) } } A: I was able to work around this by having the script add the dependencies to the pom directly using pom.withXml. //The publication doesn't know about our dependencies, so we have to manually add them to the pom pom.withXml { def dependenciesNode = asNode().appendNode('dependencies') //Iterate over the compile dependencies (we don't want the test ones), adding a <dependency> node for each configurations.compile.allDependencies.each { def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', it.group) dependencyNode.appendNode('artifactId', it.name) dependencyNode.appendNode('version', it.version) } } This works for my project, it may have unforeseen consequences in others. A: Kotlin DSL version of the accepted answer: create<MavenPublication>("maven") { groupId = "com.example" artifactId = "sdk" version = Versions.sdkVersionName artifact("$buildDir/outputs/aar/Example-release.aar") pom.withXml { val dependenciesNode = asNode().appendNode("dependencies") val configurationNames = arrayOf("implementation", "api") configurationNames.forEach { configurationName -> configurations[configurationName].allDependencies.forEach { if (it.group != null) { val dependencyNode = dependenciesNode.appendNode("dependency") dependencyNode.appendNode("groupId", it.group) dependencyNode.appendNode("artifactId", it.name) dependencyNode.appendNode("version", it.version) } } } } } A: I'm upgraded C.Ross solution. This example will generate pom.xml with dependecies from compile configuration and also with special build type dependecies, for example if you use different dependencies for release or debug version (debugCompile and releaseCompile). And also it adding exlusions publishing { publications { // Create different publications for every build types (debug and release) android.buildTypes.all { variant -> // Dynamically creating publications name "${variant.name}Aar"(MavenPublication) { def manifest = new XmlSlurper().parse(project.android.sourceSets.main.manifest.srcFile); def libVersion = manifest['@android:versionName'].text() def artifactName = project.getName() // Artifact properties groupId GROUP_ID version = libVersion artifactId variant.name == 'debug' ? artifactName + '-dev' : artifactName // Tell maven to prepare the generated "*.aar" file for publishing artifact("$buildDir/outputs/aar/${project.getName()}-${variant.name}.aar") pom.withXml { //Creating additional node for dependencies def dependenciesNode = asNode().appendNode('dependencies') //Defining configuration names from which dependencies will be taken (debugCompile or releaseCompile and compile) def configurationNames = ["${variant.name}Compile", 'compile'] configurationNames.each { configurationName -> configurations[configurationName].allDependencies.each { if (it.group != null && it.name != null) { def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', it.group) dependencyNode.appendNode('artifactId', it.name) dependencyNode.appendNode('version', it.version) //If there are any exclusions in dependency if (it.excludeRules.size() > 0) { def exclusionsNode = dependencyNode.appendNode('exclusions') it.excludeRules.each { rule -> def exclusionNode = exclusionsNode.appendNode('exclusion') exclusionNode.appendNode('groupId', rule.group) exclusionNode.appendNode('artifactId', rule.module) } } } } } } } } } } A: I guess it has something to do with the from components.java directive, as seen in the guide. I had a similar setup and it made the difference to add the line into the publication block: publications { mavenJar(MavenPublication) { artifactId 'rest-security' artifact jar from components.java } } A: I was using the maven-publish plugin for publishing my aar dependency and actually I could not use the maven task in my case. So I used the mavenJava task provided by the maven-publish plugin and used that as follows. apply plugin 'maven-publish' publications { mavenAar(MavenPublication) { from components.android } mavenJava(MavenPublication) { pom.withXml { def dependenciesNode = asNode().appendNode('dependencies') // Iterate over the api dependencies (we don't want the test ones), adding a <dependency> node for each configurations.api.allDependencies.each { def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', it.group) dependencyNode.appendNode('artifactId', it.name) dependencyNode.appendNode('version', it.version) } } } } I hope that it helps someone who is looking for help on how to publish the aar along with pom file using the maven-publish plugin. A: now that compile is deprecated we have to use implementation. pom.withXml { def dependenciesNode = asNode().appendNode('dependencies') configurations.implementation.allDependencies.each { def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', it.group) dependencyNode.appendNode('artifactId', it.name) dependencyNode.appendNode('version', it.version) }
{ "language": "en", "url": "https://stackoverflow.com/questions/24743562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: How to add run-time processing of @NotNull annotation I was quite surprised to see that IntelliJ actually does runtime verification of @NotNull within IDEA when running/debugging a unit test. Is it possible for me to add this same feature to my maven build? (What jars/jvm settings do I require?) A: IDEA is using its own method of instrumenting bytecode to add such validations. For command line builds we provide javac2 Ant task that does the instrumentation (extends standard javac task). If you generate Ant build from IDEA, you will have an option to use javac2. We don't provide similar Maven plug-in yet, but there is third-party version which may work for you (though, it seems to be a bit old). A: I'd go the AOP way: First of all you need a javax.validation compatible validator (Hibernate Validator is the reference implementation). Now create an aspectj aspect that has a Validator instance and checks all method parameters for validation errors. Here is a quick version to get you started: public aspect ValidationAspect { private final Validator validator; { final ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } pointcut serviceMethod() : execution(public * com.yourcompany**.*(..)); before() : serviceMethod(){ final Method method = (Method) thisJoinPoint.getTarget(); for(final Object arg : thisJoinPoint.getArgs()){ if(arg!=null) validateArg(arg,method); } } private void validateArg(final Object arg, final Method method) { final Set<ConstraintViolation<Object>> validationErrors = validator.validate(arg); if(!validationErrors.isEmpty()){ final StringBuilder sb = new StringBuilder(); sb.append("Validation Errors in method ").append(method).append(":\n"); for (final ConstraintViolation<Object> constraintViolation : validationErrors) { sb.append(" - ").append(constraintViolation.getMessage()).append("\n"); } throw new RuntimeException(sb.toString()); } } } Use the aspectj-maven-plugin to weave that aspect into your test and / or production code. If you only want this functionality for testing, you might put the aspectj-plugin execution in a profile. A: There is a maven plugin closely affiliated with the IntelliJ functionality, currently at https://github.com/osundblad/intellij-annotations-instrumenter-maven-plugin. It is discussed under the IDEA-31368 ticket first mentioned in CrazyCoder's answer. A: You can do annotation validation in your JUnit tests. import java.util.Set; import javax.validation.ConstraintViolation; import junit.framework.Assert; import org.hibernate.validator.HibernateValidator; import org.junit.Before; import org.junit.Test; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; public class Temp { private LocalValidatorFactoryBean localValidatorFactory; @Before public void setup() { localValidatorFactory = new LocalValidatorFactoryBean(); localValidatorFactory.setProviderClass(HibernateValidator.class); localValidatorFactory.afterPropertiesSet(); } @Test public void testLongNameWithInvalidCharCausesValidationError() { final ProductModel productModel = new ProductModel(); productModel.setLongName("A long name with\t a Tab character"); Set<ConstraintViolation<ProductModel>> constraintViolations = localValidatorFactory.validate(productModel); Assert.assertTrue("Expected validation error not found", constraintViolations.size() == 1); } } If your poison is Spring, take a look at these Spring Unit Tests
{ "language": "en", "url": "https://stackoverflow.com/questions/7008284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: 301 url redirect .htaccess in Apache server How can i direct the search engines from one domain to other domain for better SEO optimization. I want to make 301 redirect from domain.uk to language directory of another domain domain.com/gr How can to change last line code? Thanks! RewriteEngine on RewriteCond %{HTTP_HOST} ^example-old\.uk$ [NC] RewriteRule ^(.*)$ http://example-new.com/gr [R=301,L] A: RewriteCond %{HTTP_HOST} ^example-old\.uk$ [NC] RewriteRule ^(.*)$ http://example-new.com/gr [R=301,L] You've not actually stated the problem you are having. However, if you want to redirect to the same URL-path, but with a /gr/ path segment prefix (language code) then you are missing a backreference to the captured URL path (otherwise there's no reason to have the capturing group in the RewriteRule pattern to begin with). For example: RewriteRule (.*) http://example-new.com/gr/$1 [R=301,L] The $1 backreference contains the value captured by the preceding (.*) pattern. A: I assume that is what you are looking for: RewriteEngine on RewriteCond %{HTTP_HOST} ^example-old\.uk$ [NC] RewriteRule ^ http://example-new.com/gr%{REQUEST_URI} [R=301,END] It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out... In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup. This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder. And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using distributed configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).
{ "language": "en", "url": "https://stackoverflow.com/questions/62756246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Choosing an STL container to store threads I am trying to choose the best STL container to hold Thread objects (I am writing a thread library). My problem is that I'm not very familiar with any of them, and while reading the api helps, I would like to consult someone who had used it before. Anyway - every Thread object has two important attributes: _id and _priority. I need to be able to access a thread by _id, so I naturally thought of a hash_map. I also want the objects to be sorted by _priority (different Thread objects can have the same priority), so I thought of a priority queue with pointers to the hash_map, but if I delete a thread who's not first on the queue it gets a little ugly. Is there a better solution? Thanks! A: To get two types of access you either need to combine two containers... or reuse a library that combines containers for you. Boost.MultiIndex was invented for precisely this kind of needs. The basics page shows an example that has employees accessible by id (unique) and sorted by name (non-unique), which is pretty much what you are going for. The key extractors are perhaps not obvious. Supposing that your thread ressemble: class Thread { public: std::size_t id() const; std::size_t priority() const; ... }; You should be able to write: #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/const_mem_fun.hpp> #include <boost/multi_index/member.hpp> // define a multiply indexed set with indices by id and name typedef multi_index_container< Thread, indexed_by< ordered_unique< const_mem_fun<Thread, std::size_t, &Thread::id> >, ordered_non_unique< const_mem_fun<Thread, std::size_t, &Thread::priority> > > > ThreadContainer; Which defines a container of thread uniquely identified by their id() and sorted according to their priority(). I encourage you to play around with the various indexes. Also, if you provide friend access to your class or specific getters that return mutable references, then using mem_fun instead of const_mem_fun you will be able to update your objects in place (for example, change their priority). It's a very complete (if daunting) library. A: Best solution is possibly std::map,, providing you a key / value pair. In your scenario the key has the type of your _id and the value the type Thread (assuming this is the name of your class). By copying all values to a std::vector you can sort by _priority with std::sort and a predicate. A: An easy solution would be to keep the std::unordered_map to provide the key --> thread lookup, and then use a std::set to implement your priority queue.
{ "language": "en", "url": "https://stackoverflow.com/questions/10276086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unable to install "org.Hs.eg.db" in Rstudio I tried to install the package org.Hs.eg.db from the bio-conductor, but the Rstudio failed to install. The returning warning message is as followed: enter image description here And my SessionInfo() is as followed: My .LibPaths() is as followed: D:/Program Files/R/R-3.2.3/library The output of the installed.packages is as followed: Could anynone help to debug this, it has plagued me for half a month, I tried all sorts of means, still no good result. Thank you so much!
{ "language": "en", "url": "https://stackoverflow.com/questions/35534193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I configure Server-Side custom_hooks in GitLab? I've tried below approach and it works fine. However, it just commits and pushes from my local to git then it will push to the remote server. git remote add origin https://code.company.com/autodeployment/fiver.git git remote set-url --add --push origin https://code.company.com/autodeployment/fiver.git git remote set-url --add --push origin fiver@server01.company.com:/var/fiver/fiver.git I wanted to commit and push from my local to Git and Git should have a custom_hook where the remote server will auto-fetch or the Git will auto push to the remote server. A: Don't bother with hooks for this. Simply define a push mirror. This is available in CE version if you wonder (only pull mirrors need the EE version). Go to your repo > settings > repository > mirroring settings and just follow the guide. The only very small drawback I have experienced so far is that there is a 5 minutes limit between pushes. But it is rarely a blocker in real life as you can still push manually to all your remotes if you really need to. Reference: https://docs.gitlab.com/ee/user/project/repository/repository_mirroring.html
{ "language": "en", "url": "https://stackoverflow.com/questions/59327404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Concat array field inside an array of object into one string field in mongodb aggregate I would like to concat the array field values inside an array of objects into one string field. Heres the existing document format: { "no" : "123456789", "date" : ISODate("2020-04-01T05:19:02.263+0000"), "notes" : [ { "_id" : ObjectId("5b55aabe0550de0021097bf0"), "term" : "BLA BLA" }, { "_id" : ObjectId("5b55aabe0550de0021097bf1"), "term" : "BLA BLA BLA" }, { "_id" : ObjectId("5b55aabf0550de0021097ed2"), "term" : "BLA" } ], "client" : "John Doe" } The required document format: { "no" : "123456789", "date" : ISODate("2020-04-01T05:19:02.263+0000"), "notes" : "BLA BLA \n BLA BLA BLA \n BLA", "client" : "John Doe" } The attempt with $project : { "$project": { "notes": { "$map": { "input": "$notes", "as": "u", "in": { "name": { "$concat" : [ "$$u.term", "\\n" ] } } } } } } but this returns this : { "no" : "123456789", "date" : ISODate("2020-04-01T05:19:02.263+0000"), "client" : "John Doe" "notes" : [ { "name" : "BLA \n" }, { "name" : "BLA BLA \n" }, { "name" : "BLA BLA BLA \n" } ] } How to get it to the required format? Any idea would be appreciated! Edit : If we try to add array field values together, how can we do it it this way without grouping? Existing format : { "sale" : { "bills" : [ { "billNo" : "1234567890", "billAmt" : NumberInt(1070), "tax" : NumberInt(70) } ] }, "no" : "123456789", "date" : ISODate("2020-04-01T05:19:02.263+0000") } Required : { "no" : "123456789", "date" : ISODate("2020-04-01T05:19:02.263+0000"), "total" : NumberInt(1140) } A: You can use $reduce to convert an array of strings into single string: db.collection.aggregate([ { $addFields: { notes: { $reduce: { input: "$notes.term", initialValue: "", in: { $cond: [ { "$eq": [ "$$value", "" ] }, "$$this", { $concat: [ "$$value", "\n", "$$this" ] } ] } } } } } ]) Mongo Playground
{ "language": "en", "url": "https://stackoverflow.com/questions/61158633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Prime factorization in prolog I'm new to Prolog. I read this code which finds prime factors of an integer: factors(1,[1]) :- true, !. factors(X,[Factor1|T]) :- X > 0, between(2,X,Factor1), NewX is X // Factor1, (X mod Factor1) =:= 0, factors(NewX,T), !. And changed it to this one: factors(1,[[1,1]]) :- true, !. factors(X,[Factor1|T]) :- X > 0, ( is_list(Factor1), length(Factor1, 2), Factor1 = [Base|A], A = [Pow], between(2,X,Base), between(1,100,Pow), NewX is X / (Base ** Pow), (X mod Base) =:= 0, (NewX mod Base) =\= 0 ), factors(NewX,T), !. Well the first one works perfect, but the latter doesn't respond to queries. i.e. when I enter: factors(2,[[2,1],[1,1]]). I get 'true', but when I enter: factors(2,X). I get 'false'. A: Because Base and Pow aren't bound to anything yet (they are parts of the X that you pass), you can't compute NewX (and the betweens might not work, either). A: When you enter factors(2,X), Factor1 is not bound and is_list(Factor1) fails. I think your code is_list(Factor1), length(Factor1, 2), Factor1 = [Base|A], A = [Pow] can be abbreviated to Factor1 = [Base,Pow]. Since Factor1 is not used anywhere else, you can move [Base,Pow] into the head of the clause. You can omit true, it has no effect here. The parenthesis haven't any effect, neither. So your code could be written as: factors(1,[[1,1]]) :- !. factors(X,[[Base,Pow]|T]) :- X > 0, between(2,X,Base), between(1,100,Pow), NewX is X / (Base ** Pow), (X mod Base) =:= 0, (NewX mod Base) =\= 0, factors(NewX,T), !. On my system (using SICStus), one must use NewX is X // floor(Base ** Pow) to prevent that NewX becomes a float which leads to an error when passed to mod as argument. Edit: I originally wrote that the last cut had no effect. That is not true because between/2 creates choice points. I removed that part of my answer and put the cut back into the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/23664333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using "rem" combined with "vw" for flexible websites With the following CSS, I get a precise, proportional scaling layout: html { font-size: 1vw; } body { font-size: 1.6rem; // 16px @ 1000px screen width } .some-div { padding: 2rem; // 20px @ 1000px screen width } The thing I like about this approach, is that I can maintain a consistent ratio in between media queries. So for example, the result (text, line-breaks/hyphenation, proportions) will look exactly the same on every smartphone, whether it's 480px, 460px or 440px wide. On larger screens, I simply set the root font-size to a fixed unit, so the UI won't get "too bold" and behaves like a traditional website: html { font-size: 16px; } No hundreds or thousands lines of "responsive code" required, like you usually see in bootstrap websites and other "traditional workflows". I even use this approach, if I don't need proportional scaling. Simply because I have it ready to go, when I need it at some point. But the thing is, I've never seen this in the wild and I'm wondering why? Are there any flaws with this approach? Why not just use this in general? A: In principle, it's good. In practice, though, it has at least the following problems: * *not all fonts look good at all sizes and not all browsers do a good job at approximating them. Most problems appear when elements start being animated and, because of the approximation techniques, text looks blurry while the animation is in progress. What's worse is that animating other elements in the page affects text that is not being animated (shouldn't budge), producing a weird effect. (i.e: text blurs when opening/closing the menu...). To work around this problem, some problematic fonts have been optimized for values of font-size expressed in px (they look good at 15px and 16px - not so much at 15.5px). The blurring effect still happens, but it's not as noticeable at some values. *this technique needs an exception on narrow mobile devices. One needs to be able to read text even on narrow screens Other than that, Bootstrap 4 does use rem for padding. They tried to do it in v3 as well, but reverted due to poor browser support.
{ "language": "en", "url": "https://stackoverflow.com/questions/54390184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to have a function within a function? Is it possible to have a function within a function? Something like this: Public Class Form1 Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click Sub anim() Handles form2.Shown Me.Refresh() Do Until Me.Location.X = 350 form2.Location = New Point(Me.Location.X + 1, 250) ' System.Threading.Thread.Sleep(0.5) Loop form2.close() End Sub End Sub End Class A: It is not possible to have a fully fledged nested function definition in VB.NET. The language does support multi-line lambda expressions which look a lot like nested functions: Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click Dim anim = Sub() Me.Refresh() ... End Sub End Sub There are some notable differences though: * *Cannot have a Handles clause. *Cannot be Implements or Overrides. *The instance of the lambda is named, not the Sub definition. *In this case anim is actually a delegate and not a function. A: It is possible to have a function within a function, called lambda expressions. In your case, however, it is unclear to me how it can be useful. * *Lambda Expressions (Visual Basic) @ MSDN
{ "language": "en", "url": "https://stackoverflow.com/questions/21205567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to split an NSArray into two equal pieces? I have an NSArray, and I want to split it into two equal pieces (if odd "count" then add to the latter new array) - I want to split it "down the middle" so to speak. The following code does exactly what I want, but is there a better way?: // NOTE: `NSArray testableArray` is an NSArray of objects from a class defined elsewhere; NSMutableArray *leftArray = [[NSMutableArray alloc] init]; NSMutableArray *rightArray = [[NSMutableArray alloc] init]; for (int i=0; i < [testableArray count]; i=i+1) { if (i < [testableArray count]/2) { [leftArray addObject:[testableArray objectAtIndex:i]]; } else { [rightArray addObject:[testableArray objectAtIndex:i]]; } } Once leftArray and rightArray are made, I will not change them, so they do not need to be "mutable". I think there may be a way to accomplish the above code with the ObjectsAtIndexes method or some fast enumeration method?, but I cannot get the following code to work (or other variations): NSArray *leftArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]]]; NSArray *rightArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]]]; Does anyone know if I am going in the right direction with this or point me in the correct direction? Thanks! A: You also have the option of using -subarrayWithRange: detailed in the NSArray documentation: NSArray *firstHalfOfArray; NSArray *secondHalfOfArray; NSRange someRange; someRange.location = 0; someRange.length = [wholeArray count] / 2; firstHalfOfArray = [wholeArray subarrayWithRange:someRange]; someRange.location = someRange.length; someRange.length = [wholeArray count] - someRange.length; secondHalfOfArray = [wholeArray subarrayWithRange:someRange]; This method returns new, autorelease-d arrays. A: Have you tried adding nil to the end of the -initWithObjects: method? NSArray *leftArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]], nil]; NSArray *rightArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]], nil]; A: If you want an extra object on first array (in case total items are odd), use following code modified from Alex's answer: NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", nil]; //NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", nil]; //NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", nil]; //NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", nil]; //NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", nil]; NSArray *arrLeft; NSArray *arrRight; NSRange range; range.location = 0; range.length = ([arrayTotal count] % 2) ? ([arrayTotal count] / 2) + 1 : ([arrayTotal count] / 2); arrLeft = [arrayTotal subarrayWithRange:range]; range.location = range.length; range.length = [arrayTotal count] - range.length; arrRight = [arrayTotal subarrayWithRange:range]; NSLog(@"Objects: %lu", (unsigned long)[arrLeft count]); NSLog(@"%@", [arrLeft description]); NSLog(@"Objects: %lu", (unsigned long)[arrRight count]); NSLog(@"%@", [arrRight description]);
{ "language": "en", "url": "https://stackoverflow.com/questions/1768081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: What counts towards the 500-item limit in firestore batch writes? I have the following code in a cloud function which is returning an error with the message Error: 3 INVALID_ARGUMENT: maximum 500 writes allowed per request console.log(`${projectId} doClassifySources: Got ${_.size(output)} items`) const lastClassification = new Date().toJSON() const batch = firestore.batch() batch.update(projectRef, {lastClassification}) _.forEach(output, item => { batch.set(projectRef.collection('output').doc(encodeURIComponent(item.url)), { classifiedAt: admin.firestore.FieldValue.serverTimestamp(), ...item }, { merge: true }) }) return batch.commit().then(() => lastClassification) Yet the firebase logs show this right before the error is thrown: 12:28:19.963 PM classifySources ZklZYB5hq96J43CroKgP doClassifySources: Got 310 items That looks to me like the batch should contain 310 items, well below the 500 limit. Am I missing something in how that 500-item limit is calculated? Does the merge: true influence that in any way? Is it to do with the spread of item in the object being written (i.e. does that increase the number of writes needed)? A: With some additional testing, it appears that using admin.firestore.FieldValue.serverTimestamp() counts as an extra 'write'. With the code as above, I'm limited to 249 items (i.e. when output.length >= 250, the code will fail with that error message. If I remove the reference to serverTimeStamp(), I can get up to 499 items per write. I can't find this documented anywhere, and perhaps it is a bug in the firebase library, so I will post an issue there and see what happens.
{ "language": "en", "url": "https://stackoverflow.com/questions/54671543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Get error during using condition inside the map items.map(item => { return( <tr key={item.id}> <td>{item.id}</td> <td>{item.heading}</td> <td style={{width:"7.5%"}}> <img className="bar-sm"src={item.image} alt="pic error" style= {{width:'70px',height:'35px'}}/> </td> <td> if (item.status === 0) { return ( <> <button type="button" className="btn btn-sm btn-secondary btn-toggle" data-toggle="button" aria-pressed="false" autocomplete="off"onClick={() =>Switch(item.status,item.id)}> <div className="handle"></div> </button> </> ) } </td> <td>{item.slug}</td> <td>{item.category.name}</td> A: Try using this kind of sintax "? :" for the conditional instead of if/else
{ "language": "en", "url": "https://stackoverflow.com/questions/64136004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I create a set of characters in Scala? I'd like to create a Set of character ranges in Scala, something like A..Za..z0..9. Here's my take: scala> ('A' to 'Z').toSet.union(('a' to 'z').toSet).union(('0' to '9').toSet) res3: scala.collection.immutable.Set[Char] = Set(E, e, X, s, x, 8, 4, n, 9, N, j, y, T, Y, t, J, u, U, f, F, A, a, 5, m, M, I, i, v, G, 6, 1, V, q, Q, L, b, g, B, l, P, p, 0, 2, C, H, c, W, h, 7, r, K, w, R, 3, k, O, D, Z, o, z, S, d) This can't be the idiomatic way to do this. What's a better way? A: ('0' to 'z').filter(_.isLetterOrDigit).toSet A: A more functional version of your code is this: scala> Traversable(('A' to 'Z'), ('a' to 'z'), ('0' to '9')) map (_ toSet) reduce (_ ++ _) Combining it with the above solutions, one gets: scala> Seq[Seq[Char]](('A' to 'Z'), ('a' to 'z'), ('0' to '9')) reduce (_ ++ _) toSet If you have just three sets, the other solutions are simpler, but this structure also works nicely if you have more ranges or they are given at runtime. A: How about this: scala> ('a' to 'z').toSet ++ ('A' to 'Z') ++ ('0' to '9') res0: scala.collection.immutable.Set[Char] = Set(E, e, X, s, x, 8, 4, n, 9, N, j, y, T, Y, t, J, u, U, f, F, A, a, 5, m, M, I, i, v, G, 6, 1, V, q, Q, L, b, g, B, l, P, p, 0, 2, C, H, c, W, h, 7, r, K, w, R, 3, k, O, D, Z, o, z, S, d) Or, alternatively: scala> (('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')).toSet res0: scala.collection.immutable.Set[Char] = Set(E, e, X, s, x, 8, 4, n, 9, N, j, y, T, Y, t, J, u, U, f, F, A, a, 5, m, M, I, i, v, G, 6, 1, V, q, Q, L, b, g, B, l, P, p, 0, 2, C, H, c, W, h, 7, r, K, w, R, 3, k, O, D, Z, o, z, S, d) A: I guess it can't be simpler than this: ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9') You might guess that ('A' to 'z') will include both, but it also adds some extra undesirable characters, namely: ([, \, ], ^, _, `) Note: This will not return a Set but an IndexedSeq. I assumed you don't mind the implementation, but if you do, and do want a Set, just call toSet to the result. A: If you want to generate all the possible characters, doing this should generate all the values a char can take: (' ' to '~').toSet
{ "language": "en", "url": "https://stackoverflow.com/questions/8556255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Google Play store: edit one of the images of my app I see guides out there on how to upload a new version of your app to Google store, but in my case I'm not interested in uploading a new apk, I would just like to change one of the uploaded preview images of my app: What would be the easiest way to achieve this? A: Hi you have to go in the Play console, in "Store presence" section of your app, and in "Store listing", here you can change the listing of your app : the description, screenshots,... and all the information
{ "language": "en", "url": "https://stackoverflow.com/questions/59962959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I share my iPhone app for translators? Possible Duplicate: Creating Localization Files for iOS i have my iPhone company app in English language and we are international company, so how can I share my App for all translators f.e. by simulator or something else ? f.e. translator translate the text and need view effect on iPhone, how can I do this? A: It looks like you are searching for localization for your application. Please follow this link: Localization example link 1 Localization example Link 2 Link 3 Best link: Best Link... Hope it works for you. A: You can look at incorporating the Greenwich framework into your app. I've not used it myself, but saw it demo'd at a conference recently. It will let the translators make the changes to the app that you distribute to them as an ad-hoc build and then see them running in your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/12934620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: Trying to Launch Default Player Picker Lobby using Google Play Services, running into NullPointerException I have been stuck on this problem regarding my android application for the past four days. I am trying to launch the default Player Picker UI screen from Google Play Services, and whenever I do, I run into a NullPointerException: 04-03 13:12:22.045: E/AndroidRuntime(13042): FATAL EXCEPTION: main 04-03 13:12:22.045: E/AndroidRuntime(13042): java.lang.NullPointerException: Appropriate Api was not requested. 04-03 13:12:22.045: E/AndroidRuntime(13042): at com.google.android.gms.internal.er.b(Unknown Source) 04-03 13:12:22.045: E/AndroidRuntime(13042): at com.google.android.gms.common.api.b.a(Unknown Source) 04-03 13:12:22.045: E/AndroidRuntime(13042): at com.google.android.gms.games.Games.c(Unknown Source) 04-03 13:12:22.045: E/AndroidRuntime(13042): at com.google.android.gms.internal.gn.getSelectOpponentsIntent(Unknown Source) 04-03 13:12:22.045: E/AndroidRuntime(13042): at com.geti.geti.graphics.MultiplayerLobbyView.startInviteGame(MultiplayerLobbyView.java:102) 04-03 13:12:22.045: E/AndroidRuntime(13042): at com.geti.geti.graphics.MultiplayerLobbyView.onClick(MultiplayerLobbyView.java:302) 04-03 13:12:22.045: E/AndroidRuntime(13042): at android.view.View.performClick(View.java:4475) 04-03 13:12:22.045: E/AndroidRuntime(13042): at android.view.View$PerformClick.run(View.java:18786) 04-03 13:12:22.045: E/AndroidRuntime(13042): at android.os.Handler.handleCallback(Handler.java:730) 04-03 13:12:22.045: E/AndroidRuntime(13042): at android.os.Handler.dispatchMessage(Handler.java:92) 04-03 13:12:22.045: E/AndroidRuntime(13042): at android.os.Looper.loop(Looper.java:137) 04-03 13:12:22.045: E/AndroidRuntime(13042): at android.app.ActivityThread.main(ActivityThread.java:5419) 04-03 13:12:22.045: E/AndroidRuntime(13042): at java.lang.reflect.Method.invokeNative(Native Method) 04-03 13:12:22.045: E/AndroidRuntime(13042): at java.lang.reflect.Method.invoke(Method.java:525) 04-03 13:12:22.045: E/AndroidRuntime(13042): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187) 04-03 13:12:22.045: E/AndroidRuntime(13042): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 04-03 13:12:22.045: E/AndroidRuntime(13042): at dalvik.system.NativeStart.main(Native Method) I am following this: https://developers.google.com/games/services/android/realtimeMultiplayer. Here is my relevant code (I removed the imports): public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener, OnClickListener { private static final int RC_SIGN_IN = 0; private GoogleApiClient mGoogleApiClient; private boolean mIntentInProgress; private boolean mSignInClicked; private ConnectionResult mConnectionResult; public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API, null) .addScope(Plus.SCOPE_PLUS_LOGIN) .build(); findViewById(R.id.sign_in_button).setOnClickListener(this); findViewById(R.id.sign_out_button).setOnClickListener(this); findViewById(R.id.goButton).setOnClickListener(this); } public GoogleApiClient getApiClient() { return mGoogleApiClient; } private void resolveSignInError() { if (mConnectionResult.hasResolution()) { try { mIntentInProgress = true; mConnectionResult.startResolutionForResult(this, RC_SIGN_IN); } catch (SendIntentException e) { mIntentInProgress = false; mGoogleApiClient.connect(); } } } protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } protected void onStop() { super.onStop(); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } @Override public void onConnectionFailed(ConnectionResult result) { if (!mIntentInProgress) { mConnectionResult = result; if (mSignInClicked) { resolveSignInError(); } } } protected void onActivityResult(int requestCode, int responseCode, Intent intent) { if (requestCode == RC_SIGN_IN) { if (requestCode == RC_SIGN_IN) { if (responseCode != RESULT_OK) { mSignInClicked = false; } } mIntentInProgress = false; if (!mGoogleApiClient.isConnecting()) { mGoogleApiClient.connect(); } } } @Override public void onConnected(Bundle connectionHint) { mSignInClicked = false; if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) { Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); String personName = currentPerson.getDisplayName(); Toast.makeText(this, "User if connected! Welcome " + personName +"!", Toast.LENGTH_LONG).show(); } } @Override public void onConnectionSuspended(int cause) { mGoogleApiClient.connect(); } @Override public void onClick(View v) { if (v.getId() == R.id.sign_in_button) { findViewById(R.id.sign_in_button).setVisibility(View.GONE); findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE); } if (v.getId() == R.id.sign_in_button && !mGoogleApiClient.isConnecting()) { mSignInClicked = true; resolveSignInError(); } if (v.getId() == R.id.sign_out_button) { if (mGoogleApiClient.isConnected()) { Plus.AccountApi.clearDefaultAccount(mGoogleApiClient); mGoogleApiClient.disconnect(); mGoogleApiClient.connect(); findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE); findViewById(R.id.sign_out_button).setVisibility(View.GONE); } } if (v.getId() == R.id.goButton) { goToTitleScreen(); } } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } public void goToTitleScreen() { Intent intent = new Intent(this, TitleScreen.class); startActivity(intent); finish(); } } And my MultiplayerLobby: public class MultiplayerLobbyView extends MainActivity implements RoomUpdateListener, RoomStatusUpdateListener, RealTimeMessageReceivedListener { final static int RC_SELECT_PLAYERS = 10000; final static int RC_WAITING_ROOM = 10002; boolean mPlaying = false; final static int MIN_PLAYERS = 2; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); super.onCreate(savedInstanceState); setContentView(R.layout.multiplayer_lobby); findViewById(R.id.quickGame).setOnClickListener(this); findViewById(R.id.invitePlayers).setOnClickListener(this); } private RoomConfig.Builder makeBasicRoomConfigBuilder() { RoomConfig.Builder builder = RoomConfig.builder(this); builder.setRoomStatusUpdateListener(this); builder.setMessageReceivedListener(this); return builder; } boolean shouldStartGame(Room room) { int connectedPlayers = 0; for (Participant p : room.getParticipants()) { if (p.isConnectedToRoom()) { ++connectedPlayers; } } return (connectedPlayers >= MIN_PLAYERS); } private void startQuickGame() { // auto-match criteria to invite one random automatch opponent. // You can also specify more opponents (up to 3). Bundle am = RoomConfig.createAutoMatchCriteria(1, 1, 0); // build the room config: RoomConfig.Builder roomConfigBuilder = makeBasicRoomConfigBuilder(); roomConfigBuilder.setAutoMatchCriteria(am); RoomConfig roomConfig = roomConfigBuilder.build(); // create room: Games.RealTimeMultiplayer.create(getApiClient(), roomConfig); // prevent screen from sleeping during handshake getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // go to game screen } private void startInviteGame() { GoogleApiClient mClient = getApiClient(); Intent intent = Games.RealTimeMultiplayer.getSelectOpponentsIntent(mClient, 1, 4, true); try { startActivityForResult(intent, RC_SELECT_PLAYERS); }catch (NullPointerException e) { System.out.println("Error."); } } public void onActivityResult(int request, int response, Intent data) { if (request == RC_SELECT_PLAYERS) { if (response != Activity.RESULT_OK) { // user canceled return; } // get the invitee list Bundle extras = data.getExtras(); final ArrayList<String> invitees = data.getStringArrayListExtra(Multiplayer.EXTRA_INVITATION); // get auto-match criteria Bundle autoMatchCriteria = null; int minAutoMatchPlayers = data.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0); int maxAutoMatchPlayers = data.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0); if (minAutoMatchPlayers > 0) { autoMatchCriteria = RoomConfig.createAutoMatchCriteria( minAutoMatchPlayers, maxAutoMatchPlayers, 0); } else { autoMatchCriteria = null; } startQuickGame(); } } @Override public void onConnectedToRoom(Room room) { // TODO Auto-generated method stub } @Override public void onDisconnectedFromRoom(Room room) { } @Override public void onP2PConnected(String participantId) { // TODO Auto-generated method stub } @Override public void onP2PDisconnected(String participantId) { // TODO Auto-generated method stub } @Override public void onPeerDeclined(Room room, List<String> peers) { if (!mPlaying && shouldCancelGame(room)) { Games.RealTimeMultiplayer.leave(getApiClient(), null, room.getRoomId()); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } private boolean shouldCancelGame(Room room) { // TODO Auto-generated method stub return false; } @Override public void onPeerInvitedToRoom(Room arg0, List<String> arg1) { // TODO Auto-generated method stub } @Override public void onPeerJoined(Room arg0, List<String> arg1) { // TODO Auto-generated method stub } @Override public void onPeerLeft(Room room, List<String> peers) { if (!mPlaying && shouldCancelGame(room)) { Games.RealTimeMultiplayer.leave(getApiClient(),null, room.getRoomId()); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } @Override public void onPeersConnected(Room room, List<String> peers) { if (mPlaying) { String mNewParticipant = new String(); room.getParticipantIds().add(mNewParticipant); } else if (shouldStartGame(room)) { //start } } @Override public void onPeersDisconnected(Room arg0, List<String> arg1) { // TODO Auto-generated method stub } @Override public void onRoomAutoMatching(Room room) { // TODO Auto-generated method stub } @Override public void onRoomConnecting(Room room) { // TODO Auto-generated method stub } @Override public void onJoinedRoom(int statusCode, Room room) { if (statusCode != GamesStatusCodes.STATUS_OK) { Toast.makeText(this, "Error!", Toast.LENGTH_LONG).show(); return; } Intent i = Games.RealTimeMultiplayer.getWaitingRoomIntent(getApiClient(), room, Integer.MAX_VALUE); startActivityForResult(i, RC_WAITING_ROOM); } @Override public void onLeftRoom(int statusCode, String roomId) { // TODO Auto-generated method stub } @Override public void onRoomConnected(int statusCode, Room room) { if (statusCode != GamesStatusCodes.STATUS_OK) { // let screen go to sleep getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // show error message, return to main screen. Toast.makeText(this, "Error!", Toast.LENGTH_LONG).show(); goToTitleScreen(); } } @Override public void onRoomCreated(int statusCode, Room room) { if (statusCode != GamesStatusCodes.STATUS_OK) { Toast.makeText(this, "Error!", Toast.LENGTH_LONG).show(); return; } // get waiting room intent Intent i = Games.RealTimeMultiplayer.getWaitingRoomIntent(getApiClient(), room, Integer.MAX_VALUE); startActivityForResult(i, RC_WAITING_ROOM); } @Override public void onClick(View v) { if (v.getId() == R.id.quickGame) { startQuickGame(); } else if (v.getId() == R.id.invitePlayers) { startInviteGame(); } } @Override public void onRealTimeMessageReceived(RealTimeMessage message) { // TODO Auto-generated method stub } } I figured out that the method that is throwing me the exception is: private void startInviteGame() { GoogleApiClient mClient = getApiClient(); Intent intent = Games.RealTimeMultiplayer.getSelectOpponentsIntent(mClient, 1, 4, true); try { startActivityForResult(intent, RC_SELECT_PLAYERS); }catch (NullPointerException e) { System.out.println("Error."); } } Am I getting my GoogleApiClient correctly? Or is there something I am missing? I figured the getter in MainActivity would be sufficient enough to grab the client. A: I was playing around and ran into the same error a minute ago. Here's what worked for me. Have a look on the Accessing the Developer APIs page. The important part is: @Override public void onCreate(Bundle savedInstanceState) { // set requested clients (games and cloud save) setRequestedClients(BaseGameActivity.CLIENT_GAMES | BaseGameActivity.CLIENT_APPSTATE); … } The flags BaseGameActivity.CLIENT_GAMES | BaseGameActivity.CLIENT_APPSTATE ask for the Play Games and the Cloud Save APIs. There's also a different option to get the same thing if you're extending the BaseGameActivity class. In the CollectAllTheStars sample they pass the requested APIs to the BaseGameActivity constructor: public MainActivity() { // request that superclass initialize and manage the AppStateClient for us super(BaseGameActivity.CLIENT_APPSTATE); } This game is only using Cloud Save so it only has the CLIENT_APPSTATE flag.
{ "language": "en", "url": "https://stackoverflow.com/questions/22845921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bootstrap move navbar below other divs on large screens I am building a responsive page using bootstrap 3.1.1 and I would like to move the navbar so that it is below some other divs when viewed on non-smartphone screens. See the image below for an example. I've attempted to do this using the bootstrap pull/push classes (see code) but I can't seem to get the combination right. It is displaying as I intend for smartphone, but not larger devices. http://www.bootply.com/118321 HTML <div class="row"> <div class="col-xs-12 col-sm-push-12"> <div class="navbar navbar-inverse" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> </ul> </div> </div> </div> </div> <div class="container"> <div class="col-sm-6 col-sm-pull-12"> <h1>First Title Heading</h1> </div> <div class="col-sm-6 col-sm-pull-12"> <h1>Second Title Heading</h1> </div> </div> </div> A: It can be easily done using jQuery. Have two divs, one at the top and another at the bottom. Now, when you have a large screen size, give the html of the navbar to the above div and to the bottom one if the screen size is small. Here's what it would look like: if (screenSize > 1280px) $(#topnav).html('Your navbar HTML here'); else $(#bottomnav).html('Your navbar HTML here'); where topnav and bottomnav are the two divs. The only thing you now need to figure out is how to get the screen size. Here's how it can be done: $(window).resize(function(){ var screenSize = $(window).width(); }); Now just insert your HTML in there and it should work. A: You have to use 'pull' to put your element in the left and top and 'push' to put it on the right and bottom. So you're using these classes in the wrong way. invert the two and it will work !
{ "language": "en", "url": "https://stackoverflow.com/questions/22149480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SQL Server Case Sensitivity in Foreign Key We're having issues trying to update all of our user to lowercase usernames in SQL Server. We're doing this to support recent changes in our app. Specifically the following query is failing with an FK Constraint error on another table that references [User].[Username] Update [User] Set [Username] = 'someuser' where [username] = 'SomeUser' The user 'someuser' does exist in the foreign table already and the casing matches 'SomeUser'. The FK isn't set to Cascade on Update at the moment. I was going to go that route, but there are quite a few references to the [User].[Username] column and when I started going down that road it was a bit messy. Besides, I'd rather tackle the root cause - why is SQL enforcing the case match on the Key? I'm not the best with the internals of SQL Server, but I have cheched the COLLATION using the guidance of another SO question (http://stackoverflow.com/questions/1411161/sql-server-check-case-sensitivity) and I get these results. SELECT SERVERPROPERTY('COLLATION') => SQL_Latin1_General_CP1_CI_AS SELECT DATABASEPROPERTYEX('MyDB', 'Collation') SQLCollation; => SQL_Latin1_General_CP1_CI_AS select table_name, column_name, collation_name from information_schema.columns where table_name = 'User' => User Username SQL_Latin1_General_CP1_CI_AS select table_name, column_name, collation_name from information_schema.columns where table_name = 'ForeignTable' => ForeignTable User_Username SQL_Latin1_General_CP1_CI_AS I'm out of ideas on what to check. Hoping someone has a solution out there. I'm happy to check any settings in SQL (though you might have to guide me to where they're at in Management Studio or the Query to run to get them) or provide any additional detail if I'm haven't given enough info. UPDATE: Error as requested Msg 547, Level 16, State 0, Line 4 The UPDATE statement conflicted with the REFERENCE constraint "FK_ForeignTable_User". The conflict occurred in database "MyDB", table "dbo.ForeignTable", column 'User_Username'. The statement has been terminated. A: Based on the fact that all collations align, then one reason may be a trigger firing on update. This is why the exact error message is important. For example, do you have an audit trigger attempting to log the update into a case sensitive column? Saying that, I've never tried to create an FK between 2 different collations (I can't test right now): not sure if it would work. One factual way to test for SomeUser vs someuser would be a simple GROUP BY: do you get one count per value or one for both values Edit: check for trailing spaces...
{ "language": "en", "url": "https://stackoverflow.com/questions/4127548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 4 CSRF not correct I'm on Rails So I was messing around with my cookies and I might have deleted some important ones related to csrf. Now whenever I submit a form on my app I get: ActionController::InvalidAuthenticityToken When I dig around in these requests it looks like this is why I am getting these errors. When I actually debug through my request I get different values for form_authenticity_token and request.headers['X-CSRF-Token'] but I have no idea why. it seems like request.headers['X-CSRF-Token'] is the one that actually matches the meta tag on my page (and hidden field tag in the form) and its form_authenticity_token that is incorrect. Any thoughts? A: So, weirdly enough, the reason I was seeing this was totally unrelated to anything else I thought I was seeing. I had added this line to config/initializers/assets.rb Rails.application.config.assets.prefix = '' because on my production app I am using a cdn and its mapped to http://assets.mydomain.com and I didn't want it to resolve to http://assets.mydomain.com/assets/myasset.js Unfortunately on production it looks like it was causing this issue, weirdly enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/25517095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deserializing JSON object to runtime type in WinRT (C#) I have a small WinRT client app to my online service (Azure Web Service). The server sends a JSON encoded object with (with potential additional metadata) to the client and the client's responsibility would be to deserialize this data properly into classes and forward it to appropriate handlers. Currently, the objects received can be deserialized with a simple TodoItem todo = JsonConvert.DeserializeObject<TodoItem>(message.Content); However, there can be multiple types of items received. So what I am currently thinking is this: * *I include the type info in the header serverside, such as "Content-Object: TodoItem" *I define attributes to TodoItem on the client side (see below) *Upon receiving a message from the server, I find the class using the attribute I defined. *I call the deserialization method with the resolved type (Example of the attribute mentioned in 2.) [BackendObjectType="TodoItem"] public class TodoItem My problem with this approach however is the Type to Generics in the deserialization as I can't call: Type t = ResolveType(message); JsonConvert.DeserializeObject<t>(message.Content); I tried finding some solutions to this and getting method info for the DeserializeObject and calling it using reflection seemed to be the way to go. However, GetMethod() does not exist in WinRT and I was not able to find an alternative I could use to retrieve the generic version of the DeserializeObject (as fetching by the name gives me the non-generic overload). I don't mind using reflection and GetMethod as I can cache (?) the methods and call them every time a message is received without having to resolve it every time. So how do I achieve the latter part and/or is there another way to approach this? A: Alright, I feel like this was not really a problem at all to begin with as I discovered the DeserializeObject(string, Type, JsonSerializerSettings) overload for the method. It works splendidly. However, I would still like to hear some feedback on the approach. Do you think using attributes as a way to resolve the type names is reasonable or are there better ways? I don't want to use the class names directly though, because I don't want to risk any sort of man-in-the-middle things be able to initialize whatever. A: Just a few minutes ago we have posted the alternative way to do what you want. Please look here, if you will have any questions feel free to ask: Prblem in Deserialization of JSON A: Try this http://json2csharp.com/ Put your Json string here it will generate a class then public static T DeserializeFromJson<T>(string json) { T deserializedProduct = JsonConvert.DeserializeObject<T>(json); return deserializedProduct; } var container = DeserializeFromJson<ClassName>(JsonString);
{ "language": "en", "url": "https://stackoverflow.com/questions/17745824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: From plugin to theme folder: reference not working as expected In a given wordpress theme, the javascipt and jquery files are located at /functions/extended/js/ Originally they were located in a plugin folder. I need to retarget the references to a folder within the theme. my previous code: if ( is_front_page() ) : wp_dequeue_script( 'theme-script' ); wp_dequeue_script( 'theme-slider' ); wp_enqueue_script( 'xt-script', plugin_dir_url( __FILE__ ) . 'js/functions.js', array( 'jquery', 'xt-slider' ), '' , true ); wp_enqueue_script( 'xt-slider', plugin_dir_url( __FILE__ ) . 'js/jquery.flexslider-min.js', array( 'jquery', ), '' , true ); wp_localize_script( 'xt-slider', 'featuredSliderDefaults', array( 'prevText' => __( 'Previous', 'xt' ), 'nextText' => __( 'Next', 'xt' ) )); if ( get_theme_mod( 'xt_slider_transition' ) == 'slide' ) : wp_enqueue_script( 'xt-slider-slide', plugin_dir_url( __FILE__ ) . 'js/slider-slide.js', array( 'jquery', ), '' , true ); elseif ( get_theme_mod( 'xt_slider_transition' ) == 'fade' ) : wp_enqueue_script( 'xt-slider-fade', plugin_dir_url( __FILE__ ) . 'js/slider-fade.js', array( 'jquery', ), '' , true ); endif; endif; my new code doesn't seem to do the trick; the scripts don't get loaded: if ( is_front_page() ) : wp_dequeue_script( 'theme-script' ); wp_dequeue_script( 'theme-slider' ); wp_enqueue_script( 'xt-script', bloginfo('template_url') . '/functions/extended/js/functions.js', array( 'jquery', 'xt-slider' ), '' , true ); wp_enqueue_script( 'xt-slider', bloginfo('template_url') . '/functions/extended/js/jquery.flexslider-min.js', array( 'jquery', ), '' , true ); wp_localize_script( 'xt-slider', 'featuredSliderDefaults', array( 'prevText' => __( 'Previous', 'xt' ), 'nextText' => __( 'Next', 'xt' ) )); if ( get_theme_mod( 'xt_slider_transition' ) == 'slide' ) : wp_enqueue_script( 'xt-slider-slide', bloginfo('template_url') . '/functions/extended/js/slider-slide.js', array( 'jquery', ), '' , true ); elseif ( get_theme_mod( 'xt_slider_transition' ) == 'fade' ) : wp_enqueue_script( 'xt-slider-fade', bloginfo('template_url') . '/functions/extended/js/slider-fade.js', array( 'jquery', ), '' , true ); endif; endif; I've tried get_bloginfo, bloginfo, and get_template_directory_uri(). No bun. A: You are looking for get_template_directory()
{ "language": "en", "url": "https://stackoverflow.com/questions/22517464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get the price of tokens with web3js I wanted to know if it was possible to get the price of tokens with web3.js For example I would like to get the price of WBTC on Uniswap and on SushiSwap If you have any documentation or tutorials I'm interested Thanks in advance A: If you need any price information you could use chainlink oracle. Here is official docs for evm data feeds; https://docs.chain.link/docs/using-chainlink-reference-contracts/ . For a simple implementation example you can take a look at freeCodeCamp.org 's 32-hour course/lesson4 on youtube. Also you can take a look at uniswap API ; https://docs.uniswap.org/protocol/V2/reference/API/entities A: If you want it to be compatible across multiple chains and multiple DEXs, the easiest way I could think of is to call the router by using the method getAmountsOut. router.methods.getAmountsOut(amountIn, [inAddress, outAddress]).call() amountIn would be 1 * Math.pow(10, inAddress token decimals) inAddress is WBTC address outAddress is USDC address The output will be: 100000000,22397189858 Output[0] is amount in. Output[1] is amount out. You then have to divide that by (1 * Math.pow(10, out address decimal), where you will get WBTCprice: 22397.189858 The only caveat of doing this method is that you need to know the stable pair that exist on that dex. Some dex may use WBTC/USDT, some may use WBTC/USDC.
{ "language": "en", "url": "https://stackoverflow.com/questions/73221666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update SQLite table based on checkbox value in Flask? I have SQLite database which contains data regarding products such as Product Name, Description and Like which shows if the user likes or doesn't like the product. A user search for different products which populate a table with the name, description and a checkbox which is clicked in if the value of Like is 1 in the database and unchecked if not. I have implemented the button through (as seen in index.html) <form method = "POST"> <input type="checkbox" name="like" {% if product.like == 1 %} checked {% else %} {% endif %}> I now want the user to be able to check and uncheck the boxes in the table, and then press a button that updates the Like column in the database, how do I do this? (I can't even access the value of the button in app.py. When trying print(requests.form['like']) on the line after name=requests.form['search'] it returns BadRequestKeyError: The browser sent a request that this server could not understand. KeyError: 'like') app.py ... product = [] @app.route('/', methods = ['POST']) def index(): name = None if request.method == 'POST': name = request.form['search'] if name is not None or name != "": query_product = Products.query.filter(Products.productname==name).first() if (query_product is not None) and (query_product not in product): company.append(query_company) print(company, file = sys.stderr) return render_template('index.html', companies = company) Products class class Products(db.Model): index = db.Column(db.Integer(), primary_key = True) productname = db.Column(db.String(), primary_key = False) description = db.Column(db.String(), primary_key = False) like = db.Column(db.Integer(), primary_key = False) ...more columns index.html <!-- /templates/index.html --> {% extends 'base.html' %} {% block content %} <form method="POST"> <input type="text" placeholder="Search for Product.." name="search"> <button type="submit" name="submit">Search</button> <button type="submit" name="update" value = company.index style = margin-left:45%>Update</button> <div class="product-container" style="overflow: auto; max-height: 80vh"> <div class="table-responsive"> <table class="table" id="products"> <thead> <tr> <th scope="col">Product Name</th> <th scope="col">Description</th> <th scope="col">Like</th> </tr> </thead> <tbody> {% for product in products %} <tr {{company.index}}> <th scope="row">{{ product.productname}}</th> <td> {{ product.description }} </td> <td><form method = "POST"> <input type="checkbox" name="like" {% if product.like == 1 %} checked {% else %} {% endif %}></form></td> {% endfor %} </tbody> </table> </div> </div> {% endblock %} A: I guess you need to do this with javascript and add another route to your backend which then updates the database. maybe something like this, if it should happen automatically: <input type="checkbox" onchange="updateLike('productId', this.checked)"> <script> async function updateLike(productId, doesLike) { let response = await fetch("http://localhost/products/productId/like", { method:"POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ productId: productId, like: doesLike }) }); } </script> or you could add a button which sends the request to the server. <input type="checkbox" name="like"/> <button onclick="updateLike('productId', document.querySelector('input[name=like]').checked)">confirm</button>
{ "language": "en", "url": "https://stackoverflow.com/questions/58431932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why isn't this MySQL statement working? I have a table Seats with the columns, SeatID, Date, RouteID and Seats. The primary key is SeatsID. The value of seats is 50, and I wish to subtract whatever the user has entered into $tickettotal from 50 and then insert the new value. The user also has to enter which RouteID and Date they wish to travel. I want these to be inserted into the Seats table along with the new value of Seats. If another user enters the same Date and RouteID then the Seats should be updated. Otherwise a new record should be inserted with SeatID, Date, RouteID, and the reduced value for Seats. I thought this statement should do it but I keep getting errors back such as Can't find string terminator '"' anywhere before EOF, although when i put " at the end of the statement i just get another syntax error line 108, near ""') ON DUPLICATE KEY UPDATE Seats=Seats-'"$tickettotal" . Update I now have it inserting fine, although on a duplicate entry of both Date and RouteID it doesn't update Seats: it still just inserts a new value. The Seats - $tickettotal isn't working either. $dbh->do("INSERT INTO $Stable(Date,RouteID) VALUES ('$Tdate','$Rid') ON DUPLICATE KEY UPDATE Seats=Seats-'$tickettotal'"); Update Answer Because i didn't have a unique column, I created one using both date and RouteID added together so. $Tdate =~ s/-//gi; $dateandrid = $Tdate . $Rid; The first line removes the hyphens and the second puts them together. Then using these statements get the desired effect i wanted. $dbh->do("INSERT INTO $Stable(RouteAndDate,Date,RouteID) VALUES ('$dateandrid','$Tdate','$Rid') ON DUPLICATE KEY UPDATE Seats=Seats"); $dbh->do("INSERT INTO $Stable(RouteAndDate,Date,RouteID) VALUES ('$dateandrid','$Tdate','$Rid') ON DUPLICATE KEY UPDATE Seats=Seats-'$tickettotal'"); A: You must avoid SQL Injection with parameter binding: $dbh->do( qq{ INSERT INTO $Stable(Date, RouteID) VALUES (?, ?) ON DUPLICATE KEY UPDATE Seats=Seats-? }, undef, $Tdate, $Rid, $tickettotal );
{ "language": "en", "url": "https://stackoverflow.com/questions/29020373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic view dimensions for different Devices Possible Duplicate: How to write app for multiple screen resolutions? My Question is Suppose application has to rendered views dynamically for different devices say for example 1.Frame to display images (eg 90 X 90 for mdpi 140 X 140 for hdpi) 2.ListView Height (eg 120X 120 for mdpi 150 X 150 for hdpi) Like if i have many things to set according to device size What is the standard way to implement this instead of hard coding values in respective activities? Before loading application i want to calculate all dynamic view dimensions Thanks in advance. Any Sample code really helps me a lot A: use images in drawable-mdpi and drawable-hdpi for different height set use dimension in values res/values-mdpi/dimen.xml res/values-hdpi/dimen.xml dp, dip will change according to the density. use px in different dimension
{ "language": "en", "url": "https://stackoverflow.com/questions/13606499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Abline not fitting to barplot I'm trying to ad an abline plot to a barplot grafic but the x-axis don't seem to fit. So this is my code: #Emotion im FB darstellen y <- FB$Ärger[FB$Episode ==1] #Subset erstellen data <- factor(y, levels = c(1:7)) #faktorisieren table(data) #barplot erstellen barplot(table(data), main = "E1 - Ärger", xlab = "Rating", ylab = "Häufigkeit", ylim = c(0, 8)) #w2v integrieren abline(v=1,col="red") abline(v=2,col="red") abline(v=3,col="red") abline(v=4,col="red") abline(v=5,col="red") abline(v=6,col="red") abline(v=7,col="red") abline(v=index(my.xts.data)[endpoints(my.xts.data, "days")] And this is what I get: Ideally abline(v=1) should show up in the center of the first bar and so one. But the scale of the abline x-axis seems to be shorter than the one of the barplot. Any ideas how I cold make both of them fit? Thanks a lot! Lorena A: The problem is that barplot automatically adds a space of 0.2 before each bar. This means you have two options. One is to get rid of the spaces, then subtract 0.5 from the value of each abline to make it match up to the centre of the bar: Rating <- factor(c(1, 2, 2, 2, 2, 2, 3, 3, 4, 5), levels = 1:7) barplot(table(Rating), main = "E1 - Ärger", xlab = "Rating", ylab = "Häufigkeit", space = 0) abline(v = seq(7) - 0.5, col = "red") The other option is to leave the spaces by starting at 0.7 and incrementing by 1.2 for each bar: barplot(table(Rating), main = "E1 - Ärger", xlab = "Rating", ylab = "Häufigkeit") abline(v = seq(0.7, 8, 1.2), col = "red") To make this easier, you could define a function that does the calculation for you: add_vlines <- function(x) abline(v = (x * 1.2) - 0.5, col = "red") So you could just do: add_vlines(1:7) to get the lines you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/62061859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }