text
stringlengths
15
59.8k
meta
dict
Q: I am unable to accept Android SDK licenses when installing Android SDK for flutter through command line I tried everything mention on different questions on github and stackoverflow but failed. I also tried uninstalling and re-installing sdk 2 times. When i run sdkmanager --licenses it shows unknown command : --licenses When I run flutter doctor -v ,it shows one issue found SDK licenses not accepted What I Have: JDK 8 Platform-tools 30.0.1 Build-tools 28.0.3 SDK Tool 25.2.5[Obsolete](I could not prevent it from downloading as it is required for the Andorid emulator) SDK Platform API 28 Emulator: Android 9(API 28) Intel x86 Atom System Image A: 1) Open your terminal 2) Type flutter doctor --android-licenses 3) If you don't see y/n option , continue hitting enter key to read through the license 4) When you get option to press Y/N , press Y to accept every license. A: You should run flutter clean in terminal. Then restart your IDE. It will resolve the issues A: To accept licences run this flutter doctor --android-licenses then y to accept
{ "language": "en", "url": "https://stackoverflow.com/questions/61949423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting duplicate output I'm trying to write a bash script that looks for a file in one directory and replaces it with one of the same name from a source directory. When I run the find command, it seems to be setting my $path twice for f in build-res/$1/*.png; do file="$(basename "$f")" echo "Looking for $file in $TMP" path="$(find $TMP -type f -name "$file")" if [[ -z $path ]]; then echo "Could not find $file in $TMP" else echo "Replacing file at $path with $file" echo "__path__" echo $path echo "---" fi done Running one iteration of this loop outputs something like Replacing file at tmp/trx//images/background/background_iphone5.png tmp/trx//images/background_iphone5.png with background_iphone5.png __path__ tmp/trx//images/background/background_iphone5.png tmp/trx//images/background_iphone5.png --- Notice how path repeats itself with a space between. Why would this be happening? Another note, why is it coming back with // in the path as well? This doesn't seem to be an issue, more so just curious. A: If you look closely this is not the same path: tmp/trx//images/background/background_iphone5.png tmp/trx//images/background_iphone5.png --> tmp/trx//images/background/background_iphone5.png tmp/trx//images/background_iphone5.png This is the result output of find which finds 2 files with the same name in different subdirectories of /tmp. Just FYI, if you want to control how deep find can descend into subdirs, there's an option for that: -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the command line arguments. -maxdepth 0 means only apply the tests and actions to the command line arguments. Or if you want just a single result you can use -quit Exit immediately. No child processes will be left running, but no more paths specified on the command line will be processed. For example, find /tmp/foo /tmp/bar -print -quit will print only /tmp/foo.
{ "language": "en", "url": "https://stackoverflow.com/questions/30108789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I'm getting "Parameters: [unauthRoleName] must have values" when adding cognito authorization ans api key authorization to my data model in amplify I have a graphql api with the following model: type NewFeatureNotification @model @auth(rules: [{allow: public, operations: [read]}, {allow: groups, groups: ["AdminPortal"], operations: [read, create, update, delete]}]) { id: ID! title: String description: String date: AWSDate featureType: String productIdentifier: Int } I added an authentication option with an existing user pool and that worked fine, I also created a user group to restrict permissions. The issue appeared when I tried to add authorization rules to my model, the rules should allow access to read action with the api key and read, create, update and delete can be access with an authenticated user that belongs to the AdminPortal Group rules: [{allow: public, operations: [read]}, {allow: groups, groups: ["AdminPortal"], operations: [read, create, update, delete]}] but when I try to deploy this change with amplify push I get the following error: Parameters: [unauthRoleName] must have values . I also try to do the same thing from the amplify studio but I get the same error.
{ "language": "en", "url": "https://stackoverflow.com/questions/72717333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing @preAuthorize(custom_implementation) with MockMvc I added @preAuthorize("@securityService.hasPermission()") on top of my controller method and created related bean with given method- @Configuration public class SecurityConfig { @Bean public PreAuthorizationSecurityService securityService() { return new PreAuthorizationSecurityService(); } } Now, I'm using MockMvc for testing my controller. When I add SecurityConfig.class to ContextConfiguration of the test class,controller method checks for permission. But, I want to mock PreAuthorizationSecurityService in a way that my class doesn't have to import SecurityConfig.class for testing purposes. A: If you just want to declare a mock of your service instead of importing the entire SecurityConfig, you can easily do so by declaring this in your test config : @Configuration public class TestConfig { @Bean public PreAuthorizationSecurityService mockedSecurityService() { //providing you use Mockito for mocking purpose return mock(PreAuthorizationSecurityService.class); } } And then set your mock to return true when needed. You can also provide your own mocked implementation that always return true. That said, this is not the usual way to use Spring Security. And you should consider refactoring your app to use the standard role-based system, it will save you some trouble. I don't know what your PreAuthorizationSecurityService looks like and if this can apply in your situation but in most cases, it should and that's what you should aim for. With this standard role based approach, Spring Security Test (v4+ I think) easily allows you to mock connected user with given roles with annotation like @WithMockUser.
{ "language": "en", "url": "https://stackoverflow.com/questions/46447791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple DataBases in Spring-Boot With mariaDB I need to know the simple steps to Access the Repository and Entity Classes from Multiple Databases. Example: I have User table in DB1 and Email in DB2 have to access from a single Service Request. DB 1 spring.datasource.url = jdbc:mysql://localhost:3306/dbName1?useSSL=false spring.datasource.username = user spring.datasource.password = password spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.hibernate.ddl-auto = update DB 2 spring.datasource.url = jdbc:mysql://localhost:3306/dbName2?useSSL=false spring.datasource.username = user spring.datasource.password = password spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect OTHER PROPERTIES spring.jpa.properties.hibernate.jdbc.batch_size=20 spring.jpa.properties.hibernate.order_inserts=true spring.jpa.properties.hibernate.order_updates=true spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true spring.servlet.multipart.max-file-size=100MB spring.servlet.multipart.max-request-size=100MB A: Solution 1: You could create a user that has access to both databases and then use fully qualified table names when querying for the external table. MySQL supports the dbname.tablename syntax to access tables outside the current database scope. This requires that the currently connected user has the appropriate rights to read from the requested table in another physical db. Solution 2: You can configure two datasources as described here: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-two-datasources A: (Not a direct answer.) If you will be using text other than plain English, consider these settings: Hibernate XML: <property name="hibernate.connection.CharSet">utf8mb4</property> <property name="hibernate.connection.characterEncoding">UTF-8</property> <property name="hibernate.connection.useUnicode">true</property> Connection url: db.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&character_set_server=utf8mb4 A: @Table(name="tablename", catalog="db2") worked for me
{ "language": "en", "url": "https://stackoverflow.com/questions/52270332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NSIS execwait will not launch any network located exe, using a variable (execwait '$PATHTOEXE' ) My code for a NSIS execwait will not launch any network located exe, using a variable (execwait '$PATHTOEXE') even though it contains the full path to the exe. Yes, the variable contains the correct path and syntax for a path, along with the correct name of the exe. The user has full administrator (full control) rights to the folder/exe on the network. The exe launches immediately when the execwait has the full path i.e. execwait 'P:\folder\folder\setup.exe'. It does not launch the app with execwait '$PATHTOEXE' - the best I've gotten on occasion is the msiexec command line msg box to pop up. I've used a msg box to make sure the global variable contains the correct path (e.g. P:\folder\folder\setup.exe) which is identical to the typed path that works. Yes I have tried adding double quotes '"$PATHTOEXE"'. I have tried adding the execwait 'msiexec /i $PATHTOEXE' with and without double quotes. I have tried making the variable just to the root directory and adding the setup.exe to the line (i.e. execwait '$PATHTOEXE\setup.exe') with and without double quotes. The particular setup.exe was created by install shield. Anyone have an idea of what I may be doing wrong? A: Try Process Monitor to see which path it tries to execute when it fails...
{ "language": "en", "url": "https://stackoverflow.com/questions/16619022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CouchDb unhandled 'error' event - Node js I'm new to Node and CouchDb and I'm trying to get my hands on it. I'm struggling to make a piece of code to work. I would like to create a table users, insert a new user and 'at the same time' getting another user. I'm getting this error when starting up node app.js : antoine@ubuntu:~/projects/couchDb$ node app.js Database users exists. {"error":"conflict","reason":"Document update conflict."} Leaving saveDoc events.js:48 throw arguments[1]; // Unhandled 'error' event ^ Error: socket hang up at createHangUpError (http.js:1107:15) at Socket.onend (http.js:1188:27) at TCP.onread (net.js:369:26) And here is my very code, is there something wrong? (When I remove the getDoc function the error goes away) I'm using couchDB 1.0.1 and node 0.6.12 The jdoe4 and jdoe documents are already present in the users database. var dbHost = "127.0.0.1"; var dbPort = 5984; var dbName = 'users'; var couchdb = require('felix-couchdb'); var client = couchdb.createClient(dbPort, dbHost); var user = { name: { first: 'John', last: 'Doe' } } var db = client.db(dbName); db.exists(function(err, exists) { if (!exists) { db.create(); console.log('Database ' + dbName + ' created.'); } else { console.log('Database ' + dbName + ' exists.'); } db.saveDoc('jdoe4', user, function(err, doc) { if( err) { console.log(JSON.stringify(err)); } else { console.log('Saved user.'); } console.log('Leaving saveDoc'); }); db.getDoc('jdoe', function(err,doc) { if( err) { console.log(JSON.stringify(err)); } else { console.log(JSON.stringify(doc)); } console.log('Leaving getDoc'); }); }); A: It seems to be a library problem => Github Issue Socket Hangout Look here if you dont know which library fit more your needs. A: I quickly realized that felix-couchdb is not compatible with node 8 (I know you're not using version 8, but you will someday), so I switched to nano couchdb and here's the following code: * *It will check if the db is created *It will insert only if the key given is unique *It will get the user with a key var couchdb = require('nano')('http://localhost:5984') , dbName = 'users' , db = couchdb.use(dbName) ; var user = { name: { first: 'John', last: 'Doe' } } couchdb.db.create(dbName, function(err, db_body) { db.insert(user, 'jdoe4', function(err, doc, header) { if( err) { console.log('Cannot save user'); } else { console.log('Saved user.'); } console.log('Leaving saveDoc'); }); db.get('jdoe', function(err, doc) { if( err) { console.log('Cannot get user'); } else { console.log(JSON.stringify(doc)); } console.log('Leaving getDoc'); }); }); One thing worth noting is that, while this will get them at the "same time," it's still making 3 requests to the db, 1 to check if it exists, 1 to insert (or not), 1 to get.
{ "language": "en", "url": "https://stackoverflow.com/questions/11729999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way to set year in crontab parameter list? I want to set a cronjob for a specific date and time. For example, date time like this 2017 July 12, 12 35. Is it possible to set Year in the crontab parameter list? I can set without the year field. A: There is no parameter to specify the year in crontab. You can move the year logic to the bash script and add that script to crontab. A: No. Crontab is for events that REPEAT on cycles within the year. It's got no capacity for scheduling events on a particular year, nor even for events that happen in some years and not others. It's just not something the designers of cron needed to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/44924448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Attribute not Backed by Database not Updating I'm trying to create a User model for my Ruby on Rails app that has a password field that is not saved in the database, but for some reason, it's not being updated correctly. class User < ActiveRecord::Base attr :password validates_presence_of :email, :password_digest def password! password_digest = Digest::SHA1.hexdigest(password) end def password?(password) password_digest == Digest::SHA1.hexdigest(password) end end I'm using a very basic form to update the email and password. = form_for @user do |f| -if @user.errors.any? #error_explanation %h2= "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:" %ul - @user.errors.full_messages.each do |msg| %li= msg .field = f.label :email = f.email_field :email, :required => true .field = f.label :password = f.password_field :password, :required => true .actions = f.submit 'Save' In my controller I'm trying to use the basic update mechanism, though I am willing to add more code if I absolutely have to. class UsersController < ApplicationController def create @user = User.new(params[:user]) @user.password! respond_to do |format| if @user.save format.html { redirect_to @user, notice: 'User was successfully created.' } format.json { render json: @user, status: :created, location: @user } else format.html { render action: "new" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end end When this update is processed it throws a TypeError with the message: can't convert nil into String. I've tried a few different ways to fix this, including manually setting the password using params[:user][:password] but it won't work. Can anyone spot the bug I'm missing? A: In your password! method, you need to specify that you want to access the instance variable password_digest. Change to: def password! self.password_digest = Digest::SHA1.hexdigest(password) end
{ "language": "en", "url": "https://stackoverflow.com/questions/9486182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Host Sinatra Web Site in Team City Whenever I open my team city triggered runs to looks at the results, I want to provide a tab where I can see my Ruby-Sinatra web server. Ideally that should result in a Same Domain Error because team city tabs are i-frames, If I give a html page with a hyper link to the web server. How can I go about it A: For the Same Domain Issue, I set the X-Frame-Option to *, This way it worked in IE and Firefox as it explicitly understood the option. However in Chrome it did not understand the * option so bypassed it all together, which did the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/51582325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using "rowversion" as primary key column I am using SQL Server 2012 and I want to create a "changes" table - it will be populated with data from other table when the second table columns values are changed. I am adding to the "changes" table "datatime2", and "rowversion" columns in order to track when the changes are made. Is it ok to use "rowversion" as primary key? I have read here that it will be changed, if the current row is updated and that's why it is not a good candidate for "primary key" making foreign keys invalid. Anyway, if it won't be used as a foreign key and the rows of "changes" table will never be updated (only new rows will be inserted) is it ok to use the "rowversion" as PK or I should use additional column? A: Some good info here: Careful reading of the MSDN page also shows that duplicate rowversion values are possible if SELECT INTO statements are used improperly. Something to watch out for there. I would stick with an Identity field in the original data, carried over into the change tracking table that has its own Identity field.
{ "language": "en", "url": "https://stackoverflow.com/questions/14808328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xib Size - seems to think its longer than it is This is a bit of a strange one, but basically I am having a problem whereby the xib size of my initial view controller seems to be longer than the screen. So, if you have an ad banner set to be on the bottom of the screen... If I run the app in simulator, it does not show on iPhone 3GS/4/4S devices, yet WILL show on the iPhone 5. I have tried changing the xib size settings, I even created a new xib file, but the same problem is occuring which leads me to believe it is hardcoded somewhere, but I cannot think where to look for this. It is basically like it thinks the bottom of the screen is about 30-50px more than what it actually is... Hence why the iPhone5 displays ok as it has the taller screen. Any help would be appreciated! A: Its bcoz of the StatusBar. It reserve 20px of screen . You can remove this space by do change in Status bar is initially hidden in plist and set status bar to NONE in IB. A: The iPhone 5 has a taller screen. The most flexible way to lay out your xib is via AutoLayout. Here is a tutorial to get you started: http://www.raywenderlich.com/20881/beginning-auto-layout-part-1-of-2 http://www.raywenderlich.com/20897/beginning-auto-layout-part-2-of-2 Basically, you want the ad banner to be contrained to the bottom of the view.
{ "language": "en", "url": "https://stackoverflow.com/questions/14895028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is SimpleCursorAdapter constructor supposed to observe column order in constructor? I am testing a basic SQLite query and using a SimpleCursorAdapter to populate a ListView containing LinearLayout's that contain TextViews of the column data, but when I change the order of the TextView's, the data in the TextView's move with the order, not with the R.id. In the example below, the order of the TextView's is @+id/rowid and @+id/name, and the data from the cursor correctly populates. However if I modify the row.xml to change the order of the EditText's (I cut the entire TextView element and paste it on the opposite side of the other TextView), the data from the cursor stays in the same order, ie. the DatabaseHelper.NAME data from the cursor goes into the @+id/rowid EditText, and the _id data from the cursor goes into @+id/name Is this normal behaviour? I expected the SimpleCursorAdapter 'from' columns to populate the 'to' views in their respective order in the constructor. Example code: Cursor usersCursor; String query = String.format("SELECT _id, %s FROM %s", DatabaseHelper.NAME, DatabaseHelper.TABLE); cursor = db.getReadableDatabase().rawQuery(query, null); usersCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.row, usersCursor, new String[] { "_id", DatabaseHelper.NAME }, new int[] { R.id.rowid, R.id.name }, 0); userList.setAdapter(usersCursorAdapter); and the R.layout.row.xml is: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/rowid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:textSize="36sp" /> </LinearLayout> A: The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter. Source Try cleaning your project and running it again. My guess is that the R.id values in your R.java file don't match the ones in the compiled Java code. This is entirely possible if you only changed the XML files. R.java will be regenerated, but the classes which use R.id are not recompiled with the new values. Since R.id contains final constants, the compiler can optimize the byte code by using the constant value directly rather than loading it from a variable. This directly causes the problem you are seeing when R.java changes but the rest of your code is not recompiled.
{ "language": "en", "url": "https://stackoverflow.com/questions/25719126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is Page Control not reflecting where I am on the UIScrollView? After editing my UIScrollView size, page control stopped working. You can see there are only 3 slides. But (1) Page Control isn't reflecting which slide I'm on and (2) I can only scroll from slide 1 to slide 3. Here's my code: func setupSlideScrollView(slides : [Slide]) { scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 154) scrollView.contentSize = CGSize(width: 188 * CGFloat(slides.count) + CGFloat((slides.count - 1) * 10), height: 153) scrollView.isPagingEnabled = true var lastCellMaxX: CGFloat = 0 let constantSpacingBetweenCell: CGFloat = 10 for i in 0 ..< slides.count { slides[i].frame = CGRect(x: lastCellMaxX, y: 0, width: 220, height: 153) scrollView.addSubview(slides[i]) lastCellMaxX += 188 + constantSpacingBetweenCell } } func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageIndex = round(scrollView.contentOffset.x/scrollView.frame.size.width) pageControl.currentPage = Int(pageIndex) } A: func scrollViewDidScroll(_ scrollView: UIScrollView) { // This will always round down to zero // since the contentOffset.x will always be smaller than the frame width... let pageIndex = round(scrollView.contentOffset.x/scrollView.frame.size.width) // Possible logic to correct this? let pageIndex = scrollView.contentOffset.x / (width of a slide) pageControl.currentPage = Int(pageIndex) } -- Updated due to chat -- Your scrollview's frame is fine. However, you need to add a stackview to hold all your slides in order to scroll through it. Scrollviews are a bit tricky since you can't just add views and expect it to be scrollable. Here is test code I used to create a scrollView that contains stackviews. func createSlideshow() { scrollView.translatesAutoresizingMaskIntoConstraints = false let slide1 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375)) slide1.backgroundColor = UIColor.red let slide2 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375)) slide2.backgroundColor = UIColor.blue let slide3 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375)) slide3.backgroundColor = UIColor.yellow let slides: [UIView] = [slide1, slide2, slide3] let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .horizontal stackView.alignment = .center stackView.distribution = .equalCentering stackView.spacing = 10 for slide in slides { stackView.addArrangedSubview(slide) slide.widthAnchor.constraint(equalToConstant: slide.frame.width).isActive = true slide.heightAnchor.constraint(equalTo: stackView.heightAnchor).isActive = true } scrollView.addSubview(stackView) stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true stackView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor).isActive = true stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true }
{ "language": "en", "url": "https://stackoverflow.com/questions/55306756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CakePHP simple retrieve data I can't handle with retrieving data from model. My table is : CREATE TABLE grades( id INT NOT NULL, value nvarchar(2) NOT NULL ); INSERT grades(id, value) VALUES (1,N'A'), (2,N'F'), (8,N'B+'), (10,N'C') and i tried in controller var $uses = array( 'Grade'); function index(){ $this->Grade->read(); $this->set ( 'grade', $this->Grade->data ); $this->set ( 'res' ); $res = $this->Grade->find(array( 'conditions' => array('id' => 2) )); } and in view <?php debug($res);?> returns array(). I need it to work like 'SELECT * FROM grades WHERE id = 2;' I need it to return something like~ 2, F A: function index(){ $res = $this->Grade->find('first', array( 'conditions' => array('id' => 2) )); $this->set('res', $res); } I highly suggest you go through the CakePHP Book's Tutorials & Examples. There are so many things wrong or strange with your code that I'm not going to even try to explain it all, but above is how you could find a Grade based on an id. A: Your find-statement looks good, but you don't set it for the view $this->set ( 'res' ); Try: $res = $this->Grade->find(array( 'conditions' => array('id' => 2) )); $this->set('res', $res); With that you do your find, save the result in $res and give it to the view using the set(). A: it simply works, when I erase line $this->Grade->read(); and it solved my problem, no one knows.
{ "language": "en", "url": "https://stackoverflow.com/questions/20454200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: ffmpeg video concate not working when one video is generated from a single image what I am doing is generating a video of 5 secs from a single image using FFmpeg. for that I'm using the following command: -loop 1 -i image.jpg -c:v libx264 -t 5 -pix_fmt yuv420p -crf 25 -s 1280x720 Out.mp4. Now I want to concatenate this video with another one. I am able to do this for other videos with the following command -y -i input1.mp4 -i input2.mp4 -strict experimental -filter_complex [0:v]scale=1280x720,setsar=1:1[v0][1:v]scale=1280x720,setsar=1:1[v1];[v0][0:a][v1][1:a] concat=n=2:v=1:a=1 -ab 48000 -ac 2 -ar 22050 -s 1280x720 -r 30 vcodec mpeg4 -b 2097k output.mp4 But when I join the video generated from the image, the videos do not join as the second input does not have an audio because it is generated from the image.So is there any way to join these two videos using -filter_complex in FFmpeg? A: Change your image to video to include a silent audio track: -loop 1 -i image.jpg -f lavfi -i anullsrc -c:v libx264 -t 5 -pix_fmt yuv420p -crf 25 -s 1280x720 Out.mp4. Concat filter requires paired inputs.
{ "language": "en", "url": "https://stackoverflow.com/questions/47845199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: When does Soundcloud provide additional access? Soundcloud API has 15K play limit. When does Soundcloud provide additional access? Soundcloud API has 15K play limit. When does Soundcloud provide additional access? A: Please refer to: https://developers.soundcloud.com/docs/api/rate-limits#play-requests Rate limits are reset every 24 hours and code to handle hitting the limit is provided.
{ "language": "en", "url": "https://stackoverflow.com/questions/34589575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Enzyme Returns More Nodes Than Exist When Using Mount component.tsx import React, { ChangeEvent, FormEvent, useEffect, useState } from "react"; import { Form, FormControl, FormGroup, FormLabel } from "react-bootstrap"; import Button from "react-bootstrap/Button"; import Card from "react-bootstrap/Card"; import { useHistory } from "react-router-dom"; import { StorageKeys } from "../ProtectedRoute"; import "./styles.scss"; const Login = () => { const history = useHistory(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const handleSetEmail = (event: ChangeEvent<HTMLInputElement>) => setEmail(event.target.value); const handleSetPassword = (event: ChangeEvent<HTMLInputElement>) => setPassword(event.target.value); const handleSubmit = (event: FormEvent<HTMLElement>) => { event.preventDefault(); console.log("email::", email); console.log("password::", password); localStorage.setItem(StorageKeys.TOKEN, "TODO: Auth"); history.push("/"); }; useEffect(() => { localStorage.removeItem(StorageKeys.TOKEN); }, []); return ( <div id="login"> <Card id="loginCard"> <Card.Header>Login</Card.Header> <Card.Body> <Form onSubmit={handleSubmit}> <FormGroup> <FormLabel>Email address</FormLabel> <FormControl type="email" id="email" placeholder="Enter email" value={email} onChange={handleSetEmail} required={true} /> </FormGroup> <FormGroup> <FormLabel>Password</FormLabel> <FormControl type="password" id="password" placeholder="Password" value={password} onChange={handleSetPassword} required={true} /> </FormGroup> <div className={"button-container"}> <Button id="submit" variant="primary" type="submit"> Submit </Button> </div> </Form> </Card.Body> </Card> </div> ); }; export default Login; This works when using shallow to render the component: login.test.tsx import { mount, shallow } from "enzyme"; import React from "react"; import Login from "./index"; describe("Login Component", () => { test("can properly submit form", () => { jest.spyOn(window.localStorage.__proto__, "removeItem"); const wrapper = shallow(<Login />); // This works just find, finds only the one #email input. const emailInput = wrapper.find("#email"); emailInput.simulate("change", { target: { value: testLoginData.email } }); }); }); When using mount this throws the error: Error: Method “simulate” is meant to be run on 1 node. 2 found instead import { mount, shallow } from "enzyme"; import React from "react"; import Login from "./index"; describe("Login Component", () => { test("can properly submit form", () => { jest.spyOn(window.localStorage.__proto__, "removeItem"); const wrapper = mount(<Login />); const emailInput = wrapper.find("#email"); // This will now complain about there being too many nodes. emailInput.simulate("change", { target: { value: testLoginData.email } }); }); }); What gives? I need to use mount for the test that I'm working on, why is it finding multiple elements when there is for sure ONLY ONE. I can patch it to work using the following, but I shouldn't have to... right?! emailInput.at(0).simulate("change", { target: { value: testLoginData.email } }); A: So it's because your <FormControl is the first with this id and <input is second(or vice versa). There are wide list of approaches: * *.at(0) will work, but this way you will never know if you(because of error in the code) renders multiple elements. It might happen if conditions in conditional rendering {someFlag && <.... that suppose to be mutually exclusive are not. So really, it's a bad way. *Mock FormControl to be final element - so <input will not be returned anymore by .find()(honestly never used that, just assume it will work - but still looks messy and need additional boilerplate code for each test file, so not really handful way): jest.mock('../FormControl.jsx', () => null); *use hostNodes() to filter only native elements(like <span> to be returned): const emailInput = wrapper.find("#email").hostNodes(); I vote for 3rd option as most reliable and still safe for catching code logic's errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/64985803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSF Bean return HTML to DataTable This is my dataTable and I need my bean property status is like this: <span class="label label-warning">Warning</span> but it is printing the text, not compiling the html and dataTable or column doesn't have the espace option. Is there a way to solve this? <h:dataTable value="#{pedidoController.orderList}" var="order" styleClass="table table-striped"> <h:column> <f:facet name="header">#</f:facet> #{order.orderNo} </h:column> <h:column> <f:facet name="header">Cliente</f:facet> #{order.client} </h:column> <h:column> <f:facet name="header">Data</f:facet> #{order.date} </h:column> <h:column> <f:facet name="header">Status</f:facet> #{order.status} </h:column> </h:dataTable> A: Use h:outputText to display the data and not the implicit JSF output. Check this related question and see if it solves your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/10437097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add two slanted columns inside full-width container I'm after this: What I have is: <div class="row slantrow"> <div class="row slant-inner"> <div class="col-md-6 slant-left"> <p>text</p> </div> <div class="col-md-6 slant-right"> <p>text in another div</p> </div> </div> </div> And CSS: .slant-left { } .slant-right { background-color: antiquewhite; } .slantrow { background-color: bisque; } .slant-inner { width: 1100px; margin: 0 auto; } I need DIV1 (should be 60% of the width) and DIV2 (should be 40% of the width) combined to have the width of page content. Problems: * *Adding slanted border to the DIV2 *Getting the background color of DIV2 to go outside it's parent container What would be the recommended way to achieve the look from the image? A: Use one more div slant-middle in between slant-left and slant-right with same background color as slant-left and rotate it to 45deg. transform: rotateZ(45deg); -ms-transform: rotateZ(45deg); -moz-transform: rotateZ(45deg); -webkit-transform: rotateZ(45deg); -o-transform: rotateZ(45deg); A: You can use a pseudo-element to achieve this result. See the snippet below (see full page for a more accurate result): * { box-sizing: border-box; } .slantrow { background-color: bisque; } .slant-inner { display: flex; width: 1100px; margin: 0 auto; } .slant-inner p { position: relative; } /* Avoid paragraph being overlapped by the slanted box */ .slant-left { width: 60%; padding-right: 5%; } .slant-right { position: relative; width: 40%; padding-left: 5%; background-color: antiquewhite; } .slant-right::before { content: ''; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background-color: inherit; transform-origin: bottom left; transform: skewX(10deg); } <div class="row slantrow"> <div class="row slant-inner"> <div class="col-md-6 slant-left"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean et augue at ipsum semper auctor a ut ante. Vivamus lacinia mollis semper. Aliquam fringilla eros at tortor semper, eget finibus urna tincidunt. Nulla mollis vestibulum elit vitae elementum. Nam lacinia elit id lacus bibendum, eget placerat augue auctor. Fusce viverra odio sapien, et auctor tellus accumsan eget. Duis ullamcorper eget elit nec varius. Nunc a nisl quis nunc bibendum lobortis vitae in risus. Ut eu pellentesque augue. Nulla ut nibh laoreet, egestas velit id, ultrices arcu. Curabitur eget iaculis orci. </p> </div> <div class="col-md-6 slant-right"> <p>Aenean varius sollicitudin nulla. Proin in nisi urna. Aliquam ullamcorper dui vitae augue fringilla cursus vel finibus justo. Nullam tortor urna, rutrum et vulputate congue, consequat vitae nunc. Integer sit amet nibh blandit, venenatis velit ut, scelerisque quam. Phasellus quis leo eu quam sagittis egestas vel at eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. </p> </div> </div> </div> A: This is how I would do it, by using css clip-path, in case you do not have to support IE. .slantrow { position: relative; background-color: bisque; } .slant-inner { } .slant-left { width: 60%; } .slant-right { width: 40%; /*background-color: antiquewhite;*/ } .slant { position: absolute; top: 0; right: 0; bottom: 0; /* Play with `left` here */ /* Used -15px, as the default gutter with in BS is 30px, you can adjust this based on your setup */ left: calc(50% - 15px); background-color: antiquewhite; /* Play with `calc()` here */ -webkit-clip-path: polygon(0% 0%, 100% 0%, 100% 100%, calc(0% + 15px) 100%); clip-path: polygon(0% 0%, 100% 0%, 100% 100%, calc(0% + 15px) 100%); } <div class="slantrow"> <div class="slant"></div> <div class="container slant-inner"> <div class="row"> <div class="col-6 slant-left"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ipsum lectus, lacinia sed facilisis vel, euismod at quam. Pellentesque in urna dui. Duis ut elit id erat interdum tempor. Nam at lectus sit amet dolor interdum cursus a non enim.</p> </div> <div class="col-6 slant-right"> <p>Morbi et pretium ex. Ut eros sapien, tincidunt et tincidunt eu, semper in libero. Nunc luctus ornare massa ut porta.</p> </div> </div> </div> </div> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/48463304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Oracle Date Function Translation to BigQuery SQL Need help translating this function to BigQuery from Oracle, the from_tz and timestamp formatting are giving me trouble: trunc(from_tz(to_timestamp(trunc(llc.DATE) || ' ' || llc.HOUR, 'DD-MON-YY HH24MISS'), 'UTC') at time zone 'America/New_York') as the_date A: Consider the below approach. I used timestamp functions to create the query. with sample_data as ( select date('2017-08-04') as date, time(10,00,00) as hour ) select format_timestamp( "%d-%b-%y %H%M%S", timestamp_trunc(timestamp(concat(date, ' ',hour),"UTC"),DAY,"America/New_York")) as out_format from sample_data NOTE: I created the sample data based from the query you have presented on your question. Let me know if I used incorrect data so I can edit the answer. Output:
{ "language": "en", "url": "https://stackoverflow.com/questions/71959258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does git merge origin/master not generate a commit message? As I know that the git pull origin master is kinda alias of git fetch origin followed with git merge origin/master. However, when using git merge command for merging a change from other branch to master, there is usually an automatically generated commit message. Question: why does git merge origin/master not generate a merge commit message automatically like in the usual case? A: Check the git-pull documentation: --ff --no-ff --ff-only Specifies how a merge is handled when the merged-in history is already a descendant of the current history. --ff is the default unless merging an annotated (and possibly signed) tag that is not stored in its natural place in the refs/tags/ hierarchy, in which case --no-ff is assumed. --ff is used as default, which resolves the merge as a fast-forward if possible, and creates a merge commit when not possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/64244613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: DataTables regex search not working as expected for exact match I want to search a column of my DataTable for an exact value and return only the row that contains that value. I've read that the way to do this is to do a regex search for the specific value, however when I attempt this an exact regex search returns nothing. For example in the following table I want to return only the row that contains an id=0 <table id="searchTable" class="formTable display dataTable" cellspacing="0" style="width: 100%;"> <thead> <tr> <th>id</th> <th>Position</th> <th>Office</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>Accountant</td> <td>Tokyo</td> </tr> <tr> <td>1</td> <td>Chief Executive Officer (CEO)</td> <td>London</td> </tr> <tr> <td>2</td> <td>Junior Technical Author</td> <td>San Francisco</td> </tr> <tr> <td>10</td> <td>Software Engineer</td> <td>London</td> </tr> <tr> <td>20</td> <td>Software Engineer</td> <td>San Francisco</td> </tr> </tbody> </table> When the document is loaded I attempt to use the search api as described here. var table = null; $(document).ready(function(){ table = $('#searchTable').DataTable( { "sPaginationType": "full_numbers", "iDisplayLength": 5 } ); table.columns(0).search('/0/',true,false).draw(); } ); JS fiddle showing the regex failing A: The trick was to put the start character symbol '^' before the value being searched on and end character symbol '$' after the value. Without giving these two symbols the regex will always return nothing. Fixed portion: var table = null; $(document).ready(function(){ table = $('#searchTable').DataTable( { "sPaginationType": "full_numbers", "iDisplayLength": 5 } ); table.columns(0).search('^0$',true,false).draw(); } ); A: In case somebody else face this problem. In my case the problem was related to searching for string characters that have special meaning in a regular expression (eg. "AC (JLHA2) - GB/T1179-2008" will give nothing even if the data exists in the table). I was able to fix this by using $.fn.dataTable.util.escapeRegex() to escape all special characters. Here is the fix: var table = null; $(document).ready(function(){ table = $('#searchTable').DataTable( { "sPaginationType": "full_numbers", "iDisplayLength": 5 } ); // Escape the expression so we can perform a regex match var val = $.fn.dataTable.util.escapeRegex('AC (JLHA2) - GB/T1179-2008'); table.columns(0).search(val ? '^' + val + '$' ; '', true, false).draw(); } );
{ "language": "en", "url": "https://stackoverflow.com/questions/35575108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIScrollView inside of UIViewController not scrolling horizontally I have created a UIScrollView inside of a UIViewController. I have added a UIView inside of my UIScrollView with one label inside of the UIView. The plan is to eventually add 3 very large UIButtons that is why I need a scroll view. I have not used storyboard and it is done all programmatically. I cannot get the UIScrollView to work. class ChooseCategoryPostViewController: UIViewController, UIScrollViewDelegate { let scrollView: UIScrollView = { let sv = UIScrollView() sv.backgroundColor = .green return sv }() let myView: UIView = { let view = UIView() view.backgroundColor = .red return view }() let test: UILabel = { let label = UILabel() label.text = "test label" label.font = UIFont.boldSystemFont(ofSize: 15) label.textAlignment = .center return label }() override func viewDidLoad() { view.addSubview(scrollView) scrollView.addSubview(myView) scrollView.anchor(top: topTitle.bottomAnchor, left: nil, bottom: nil, right: nil, paddingTop: 200, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: view.frame.width, height: 200) myView.anchor(top: scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 1700, height: 200) myView.addSubview(test) test.anchor(top: myView.topAnchor, left: nil, bottom: nil, right: myView.rightAnchor, paddingTop: 20, paddingLeft: 0, paddingBottom: 0, paddingRight: 20, width: 0, height: 0) } override func viewDidLayoutSubviews() { scrollView.isScrollEnabled = true // Do any additional setup after loading the view scrollView.contentSize = CGSize(width: view.frame.width, height: 200) } A: You need to make sure that the width of the scroll view contentSize is greater than the width of the scroll view itself. Something as simple as the following should cause horizontal scrolling to happen: override func viewDidLayoutSubviews() { scrollView.isScrollEnabled = true // Do any additional setup after loading the view scrollView.contentSize = CGSize(width: view.frame.width * 2, height: 200) }
{ "language": "en", "url": "https://stackoverflow.com/questions/63165068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mariadb 10.3.13 table_open_cache problems Just upgraded mysql 5.6 to mariadb 10.3.13 - now when the server hits open_tables = 2000, my php queries stop working - if I do a flush tables it starts working correctly again. This never happened when I was using mysql - now I can't go a day without having to login and do a flush tables to get things working again Use WHM / Cpanel to administer my VPS and on the last WHM release it started warning me that the version of MySql (really can't remember what version it was - it was what was loaded when I got my VPS) that I was running was soon coming to an end and I would need to upgrade to SQL 5.7 or MariaDB xxx. Had been wanting to move to MariaDB for awhile anyway, so that is what I did - WHM recommended the 10.3.13 version. After some more watching and looking it appears that what makes my open_tables hits the 2000 max was the automatic CPANEL backup routines - which also backup all of my databases at one get go. Doesn't crash anything just causes problems with my PHP application connections - I don't thing the connections get rejected - they just don't return any data .... Turned all of the automatice WHM/CPANEL backups off and things have settled down a little. table_definition_cache 400 table_open_cache 2000 I still do a mysqldump via cron to do my database backups - only two live databases and they still make the tables_open grow to that 2000 max - just not as fast. I now run a script that runs every hour to show me some of the variables and here is what I am seeing after doing a flush tables command both open_tables and open_table_definitions start increasing until open_table_definitions hits 400 it stops increasing while open_tables keeps increasing thru the day. then when the mysqldumps happen in the early morning hours tables_open hits 2000 (the max setting) and my php queries are not executed I do not get a PHP error. I ran the following command so that I could see what was happening on the db side. SET GLOBAL general_log = 'ON' Looking at the log, when everything is running OK I see my application connecting, preparing the statement, executing the statement and then disconnecting .... I did the same thing when it started acting up (i.e. my php application starts to not get a result again) Looking at the log I see my application connecting, then preparing the statement and then instead of seeing it execute the statement, it prepares the same statement 2 more times and then disconnects ... I logged into mysql and did a flush tables command and everything goes back to normal - application connects, prepares a statement, executes it, disconnects ... But this never happened before I moved to MariaDB - I never messed with the MySQL server stuff at all - the only time MySQL was restarted was when I did a CENTOS 6 system update and had to reboot the server - would go months without doing a thing on the server .... A: Looks like the system was the culprit - I changed the open_table_cache to 400 and my php application is no longer having any issues preparing statements, even after the nightly backups of the databases. Looking at older mysql documentation, mysql 5.6.7 had a table_open_cache setting of 400, so when I upgraded to mariadb 10.3.13 that default setting was changed to 2000 which is when I started having problems. Not quite sure what the following is telling me, but might be of interest .... su - mysql -bash-4.1$ ulimit -Hn 100 -bash-4.1$ ulimit -Sn 100 -bash-4.1$ exit logout [~]# ulimit -Hn 4096 [~]# ulimit -Sn 4096
{ "language": "en", "url": "https://stackoverflow.com/questions/55027076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a "good" R value when comparing 2 signals using cross correlation? I apologize for being a bit verbose in advance: if you want to skip all the background mumbo jumbo you can see my question down below. This is pretty much a follow up to a question I previously posted on how to compare two 1D (time dependent) signals. One of the answers I got was to use the cross-correlation function (xcorr in MATLAB), which I did. Background information Perhaps a little background information will be useful: I'm trying to implement an Independent Component Analysis algorithm. One of my informal tests is to (1) create the test case by (a) generate 2 random vectors (1x1000), (b) combine the vectors into a 2x1000 matrix (called "S"), and multiply this by a 2x2 mixing matrix (called "A"), to give me a new matrix (let's call it "T"). In summary: T = A * S (2) I then run the ICA algorithm to generate the inverse of the mixing matrix (called "W"), (3) multiply "T" by "W" to (hopefully) give me a reconstruction of the original signal matrix (called "X") In summary: X = W * T (4) I now want to compare "S" and "X". Although "S" and "X" are 2x1000, I simply compare S(1,:) to X(1,:) and S(2,:) to X(2,:), each which is 1x1000, making them 1D signals. (I have another step which makes sure that these vectors are the proper vectors to compare to each other and I also normalize the signals). So my current quandary is how to 'grade' how close S(1,:) matches to X(1,:), and likewise with S(2,:) to X(2,:). So far I have used something like: r1 = max(abs(xcorr(S(1,:), X(1,:))) My question Assuming that using the cross correlation function is a valid way to go about comparing the similarity of two signals, what would be considered a good R value to grade the similarity of the signals? Wikipedia states that this is a very subjective area, and so I defer to the better judgment of those who might have experience in this field. As you might realize, I'm not coming from a EE/DSP/statistical background at all (I'm a medical student) so I'm going through a sort of "baptism through fire" right now, and I appreciate all the help I can get. Thanks! A: (edit: as far as directly answering your question about R values, see below) One way to approach this would be to use cross-correlation. Bear in mind that you have to normalize amplitudes and correct for delays: if you have signal S1, and signal S2 is identical in shape, but half the amplitude and delayed by 3 samples, they're still perfectly correlated. For example: >> t = 0:0.001:1; >> y = @(t) sin(10*t).*exp(-10*t).*(t > 0); >> S1 = y(t); >> S2 = 0.4*y(t-0.1); >> plot(t,S1,t,S2); These should have a perfect correlation coefficient. A way to compute this is to use maximum cross-correlation: >> f = @(S1,S2) max(xcorr(S1,S2)); f = @(S1,S2) max(xcorr(S1,S2)) >> disp(f(S1,S1)); disp(f(S2,S2)); disp(f(S1,S2)); 12.5000 2.0000 5.0000 The maximum value of xcorr() takes care of the time-delay between signals. As far as correcting for amplitude goes, you can normalize the signals so that their self-cross-correlation is 1.0, or you can fold that equivalent step into the following: ρ2 = f(S1,S2)2 / (f(S1,S1)*f(S2,S2); In this case ρ2 = 5 * 5 / (12.5 * 2) = 1.0 You can solve for ρ itself, i.e. ρ = f(S1,S2)/sqrt(f(S1,S1)*f(S2,S2)), just bear in mind that both 1.0 and -1.0 are perfectly correlated (-1.0 has opposite sign) Try it on your signals! with respect to what threshold to use for acceptance/rejection, that really depends on what kind of signals you have. 0.9 and above is fairly good but can be misleading. I would consider looking at the residual signal you get after you subtract out the correlated version. You could do this by looking at the time index of the maximum value of xcorr(): >> t = 0:0.001:1; >> y = @(a,t) sin(a*t).*exp(-a*t).*(t > 0); >> S1=y(10,t); >> S2=0.4*y(9,t-0.1); >> f(S1,S2)/sqrt(f(S1,S1)*f(S2,S2)) ans = 0.9959 This looks pretty darn good for a correlation. But let's try fitting S2 with a scaled/shifted multiple of S1: >> [A,i]=max(xcorr(S1,S2)); tshift = i-length(S1); >> S2fit = zeros(size(S2)); S2fit(1-tshift:end) = A/f(S1,S1)*S1(1:end+tshift); >> plot(t,[S2; S2fit]); % fit S2 using S1 as a basis >> plot(t,[S2-S2fit]); % residual Residual has some energy in it; to get a feel for how much, you can use this: >> S2res=S2-S2fit; >> dot(S2res,S2res)/dot(S2,S2) ans = 0.0081 >> sqrt(dot(S2res,S2res)/dot(S2,S2)) ans = 0.0900 This says that the residual has about 0.81% of the energy (9% of the root-mean-square amplitude) of the original signal S2. (the dot product of a 1D signal with itself will always be equal to the maximum value of cross-correlation of that signal with itself.) I don't think there's a silver bullet for answering how similar two signals are with each other, but hopefully I've given you some ideas that might be applicable to your circumstances. A: A good starting point is to get a sense of what a perfect match will look like by calculating the auto-correlations for each signal (i.e. do the "cross-correlation" of each signal with itself). A: THIS IS A COMPLETE GUESS - but I'm guessing max(abs(xcorr(S(1,:),X(1,:)))) > 0.8 implies success. Just out of curiosity, what kind of values do you get for max(abs(xcorr(S(1,:),X(2,:))))? Another approach to validate your algorithm might be to compare A and W. If W is calculated correctly, it should be A^-1, so can you calculate a measure like |A*W - I|? Maybe you have to normalize by the trace of A*W. Getting back to your original question, I come from a DSP background, so I get to deal with fairly noise-free signals. I understand that's not a luxury you get in biology :) so my 0.8 guess might be very optimistic. Perhaps looking at some literature in your field, even if they aren't using cross-correlation exactly, might be useful. A: Usually in such cases people talk about "false acceptance rate" and "false rejection rate". The first one describes how many times algorithm says "similar" for non-similar signals, the second one is the opposite. Selecting a threshold thus becomes a trade-off between these criteria. To make FAR=0, threshold should be 1, to make FRR=0 threshold should be -1. So probably, you will need to decide which trade-off between FAR and FRR is acceptable in your situation and this will give the right value for threshold. Mathematically this can be expressed in different ways. Just a couple of examples: 1. fix some of rates at acceptable value and minimize other one 2. minimize max(FRR,FAR) 3. minimize aFRR+bFAR A: Since they should be equal, the correlation coefficient should be high, between .99 and 1. I would take the max and abs functions out of your calculation, too. EDIT: I spoke too soon. I confused cross-correlation with correlation coefficient, which is completely different. My answer might not be worth much. A: I would agree that the result would be subjective. Something that would involve the sum of the squares of the differences, element by element, would have some value. Two identical arrays would give a value of 0 in that form. You would have to decide what value then becomes "bad". Make up 2 different vectors that "aren't too bad" and find their cross-correlation coefficient to be used as a guide. (parenthetically: if you were doing a correlation coefficient where 1 or -1 would be great and 0 would be awful, I've been told by bio-statisticians that a real-life value of 0.7 is extremely good. I understand that this is not exactly what you are doing but the comment on correlation coefficient came up earlier.)
{ "language": "en", "url": "https://stackoverflow.com/questions/1289415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why the memory is not allocated to the array? I was required at college to build a function in C that reads a number of values from a file and then dynamically allocates memory to an array passed by reference using pointers (it must use pointers) and after that we were required to display the values read using another function. I tried 2 aproaches that I've displayed here: #include <stdio.h> #include <stdlib.h> #include <malloc.h> ///Read an 1d array from the file stuff.txt inside of a function /// and dinamically allocate memory /// after that display on the screen the values readed from file void getDataFirstFunction(int **a, int *n) { FILE *f; f = fopen("stuff.txt" ,"r"); if(!f) { printf("ERROR WHILE OPENING THE FILE!!"); exit(0); } else { int d; fscanf(f,"%d",&(*n)); ///we dinamically alocate memory a = calloc((*n),sizeof(int)); int i=0; while(!feof(f)) { fscanf(f,"%d",&a[i++]); } } ///if I try to display the values here it works ///but when I try to read display them in the display ///function it is not going to work anymore fclose(f); } int * getData(int **a,int *n) { FILE *f; f = fopen("stuff.txt" ,"r"); if(!f) { printf("ERROR WHILE OPENING THE FILE!!"); exit(0); } else { int d; fscanf(f,"%d",&(*n)); ///we dinamically alocate memory a = calloc((*n),sizeof(int)); int i=0; while(!feof(f)) { fscanf(f,"%d",&a[i++]); } } ///if I try to display the values here it works fclose(f); return a; } void displayValues(int *a,int n) { for(int i=0;i<n;i++) { printf("%d\n",a[i]); } } int main() { int *a,*b,n,m; getData(a,&n); getDataFirstFunction(b,&m); displayValues(a,n); displayValues(b,m); return 0; } However the first function declared with void doesen't work and I can't understand why, because I've intentionally wrote a parameter that is a double pointer so when I allocate memory that memory it is not lost when the variables on the stack are dealocated by the compiler after the function finish it's execution. The second function named getData does make sense and it works but I don't know if I can make the first function with void to work because it seems like the memory is allocated only to the variable on the stack and then when it finish the execution the reference to the memory location dissapears without having memory allocated to the pointer in main so when I do try to display values on screen the program freezes and then I get nothing. Thanks in advance. A: Inside your functions, a is a copy of a pointer to pointer. Here you assigned something else to that copy: a = calloc((*n),sizeof(int)); That does not have any effect outside of the function. Outside of your functions, a is a pointer to int, it would make sense to write a pointer to int there. You could do that (via the copy used within your functions) for example like *a = calloc((*n),sizeof(int)); For that effect outside of your functions you should call with the address of the pointer to int getData(&a,&n); With this int * getData(int **a,int *n) you could assign the returned pointer to int to a outside of your function. But don't here getData(a,&n);. And for returning a pointer to int, this line is not appropriate return a; because it returns a pointer to pointer to int. Which does happen to contain the right value (freshly allocated pointer to int), but that is still incorrect by type. ... Note: You are relying very much on your fscanf()s working, so the n you are using for size might be uninitialised... And you should not use while(!feof(f)), Why is “while ( !feof (file) )” always wrong? And d seems unused inside of your functions... So please heed the recommendation in the comment by M.M. about reading compiler warnings.
{ "language": "en", "url": "https://stackoverflow.com/questions/65662727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to improve digit recognition of a model trained on MNIST? I am working on handprinted multi-digit recognition with Java, using OpenCV library for preprocessing and segmentation, and a Keras model trained on MNIST (with an accuracy of 0.98) for recognition. The recognition seems to work quite well, apart from one thing. The network quite often fails to recognize the ones (number "one"). I can't figure out if it happens due to preprocessing / incorrect implementation of the segmentation, or if a network trained on standard MNIST just hasn't seen the number one which looks like my test cases. Here's what the problematic digits look like after preprocessing and segmentation: becomes and is classified as 4. becomes and is classified as 7. becomes and is classified as 4. And so on... Is this something that could be fixed by improving the segmentation process? Or rather by enhancing the training set? Edit: Enhancing the training set (data augmentation) would definitely help, which I am already testing, the question of correct preprocessing still remains. My preprocessing consists of resizing, converting to grayscale, binarization, inversion, and dilation. Here's the code: Mat resized = new Mat(); Imgproc.resize(image, resized, new Size(), 8, 8, Imgproc.INTER_CUBIC); Mat grayscale = new Mat(); Imgproc.cvtColor(resized, grayscale, Imgproc.COLOR_BGR2GRAY); Mat binImg = new Mat(grayscale.size(), CvType.CV_8U); Imgproc.threshold(grayscale, binImg, 0, 255, Imgproc.THRESH_OTSU); Mat inverted = new Mat(); Core.bitwise_not(binImg, inverted); Mat dilated = new Mat(inverted.size(), CvType.CV_8U); int dilation_size = 5; Mat kernel = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_CROSS, new Size(dilation_size, dilation_size)); Imgproc.dilate(inverted, dilated, kernel, new Point(-1,-1), 1); The preprocessed image is then segmented into individual digits as following: List<Mat> digits = new ArrayList<>(); List<MatOfPoint> contours = new ArrayList<>(); Imgproc.findContours(preprocessed.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); // code to sort contours // code to check that contour is a valid char List rects = new ArrayList<>(); for (MatOfPoint contour : contours) { Rect boundingBox = Imgproc.boundingRect(contour); Rect rectCrop = new Rect(boundingBox.x, boundingBox.y, boundingBox.width, boundingBox.height); rects.add(rectCrop); } for (int i = 0; i < rects.size(); i++) { Rect x = (Rect) rects.get(i); Mat digit = new Mat(preprocessed, x); int border = 50; Mat result = digit.clone(); Core.copyMakeBorder(result, result, border, border, border, border, Core.BORDER_CONSTANT, new Scalar(0, 0, 0)); Imgproc.resize(result, result, new Size(28, 28)); digits.add(result); } A: I believe that your problem is dilation process. I understand that you wish to normalize image sizes, but you shouldn't break the proportions, you should resize to maximum desired by one axis (the one that allows largest re-scale without letting another axis dimension to exceed the maximum size) and fill with background color the rest of the image. It's not that "standard MNIST just hasn't seen the number one which looks like your test cases", you make your images look like different trained numbers (the ones that are recognized) If you maintained the correct aspect ration of your images (source and post-processed), you can see that you did not just resize the image but "distorted" it. It can be the result of either non-homogeneous dilation or incorrect resizing A: There are already some answers posted but neither of them answers your actual question about image preprocessing. In my turn I don't see any significant problems with your implementation as long as it's a study project, well done. But one thing to notice you may miss. There are basic operations in mathematical morphology: erosion and dilation (used by you). And there complex operations: various combinations of basic ones (eg. opening and closing). Wikipedia link is not the best CV reference, but you may start with it to get the idea. Usually in its better to use opening instead of erosion and closing instead of dilation since in this case original binary image changes much less (but the desired effect of cleaning sharp edges or filling gaps is reached). So in your case you should check closing (image dilation followed by erosion with the same kernel). In case extra-small image 8*8 is greatly modified when you dilate even with 1*1 kernel (1 pixel is more than 16% of image) which is less on larger images). To visualize the idea see the following pics (from OpenCV tutorials: 1, 2): dilation: closing: Hope it helps. A: So, you need a complex approach cause every step of your computing cascade based on the previous results. In your algorithm you have the next features: * *Image preprocessing As mentioned earlier, if you apply the resizing, then you lose information about the aspect ratios of the image. You have to do the same reprocessing of digits images to get the same results that was implied in the training process. Better way if you just crop the image by fixed size pictures. In that variant you won't need in contours finding and resizing digit image before training process. Then you could make a little change in your crop algorithm for better recognizing: simple find the contour and put your digit without resizing at the center of relevant image frame for recognition. Also you should pay more attention to the binarization algorithm. I have had experience studying the effect of binarization threshold values on learning error: I can say that this is a very significant factor. You may try another algorithms of binarization to check this idea. For example you may use this library for testing alternate binarization algorithms. *Learning algorithm To improve the quality of recognition you use cross-validation at the training process. This helps you to avoid the problem of overfitting for your training data. For example you may read this article where explained how to use it with Keras. Sometimes higher rates of accuracy measure doesn't say anything about the real recognition quality cause trained ANN not found the pattern in the training data. It may be connected with the training process or the input dataset as explained above, or it may cause by the ANN architecture choose. *ANN architecture It's a big problem. How to define the better ANN architecture to solve the task? There are no common ways to do that thing. But there are a few ways to get closer to the ideal. For example you could read this book. It helps you to make a better vision for your problem. Also you may find here some heuristics formulas to fit the number of hidden layers/elements for your ANN. Also here you will find a little overview for this. I hope this will helps. A: After some research and experiments, I came to a conclusion that the image preprocessing itself was not the problem (I did change some suggested parameters, like e.g. dilation size and shape but they were not crucial to the results). What did help, however, were 2 following things: * *As @f4f noticed, I needed to collect my own dataset with real-world data. This already helped tremendously. *I made important changes to my segmentation preprocessing. After getting individual contours, I first size-normalize the images to fit into a 20x20 pixel box (as they are in MNIST). After that I center the box in the middle of 28x28 image using the center of mass (which for binary images is the mean value across both dimensions). Of course, there are still difficult segmentation cases, such as overlapping or connected digits, but the above changes answered my initial question and improved my classification performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/58398983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What is default settings to reffer to file location in xcode project? What is default settings to reffer to file location in xcode project ? i have doubts between them * *relative to build project *relative to project *relative to enclosing group *relative to source path *Absolute path A: This doesn't seem to be well documented. As I read "How Files are Referenced" in the "Xcode Project Management Guide": * *If the file is in the project's folder, you get a reference relative to an enclosing group. *If the file is created by one of the targets, you get a reference relative to the build product. *Otherwise, I think, you get an absolute path. A: By default - Eclosing-Group*. *Beginning Xcode (James Bucanek) Chapter 5, p.76
{ "language": "en", "url": "https://stackoverflow.com/questions/3271971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Xcode 5 simulator cannot be installed, does not show up in xcode In Xcode 5, i have a problem with installing simulators. They don`t show up in the downloads section of preferences for Xcode. And the 6.1 simulator cannot be run when it says its installed. Only shows up with a question mark besides it. When i click check and install, it says nothing new found. How to fix this? When i try to run an app, no simulators show as installed: A: It shows you installed all the simulators. Just Quit the Xcode and open again. It wil show you a window same as below. Also please cross check that, the downlaoded SDK's are available under Application->Xcode.app->right-click->Show Package Contents ->Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs Also cross check the Base SDK and Target devices.
{ "language": "en", "url": "https://stackoverflow.com/questions/20739494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get wkhtmltopdf with a Dockerized Rails App with running ruby:3.0.4-alpine for use with Wicked PDF I'm trying to upgrade a Dockerized Rails app to Ruby 3+ and Rails 7. Due to other project dependencies, I've landed on this version of Ruby Docker image ruby:3.0.4-alpine. Here's my Dockerfile: FROM ruby:3.0.4-alpine RUN apk --update add --no-cache build-base bash git vim curl postgresql-dev openssl-dev nodejs npm yarn tzdata less \ imagemagick postgresql-client gcompat RUN mkdir /app WORKDIR /app COPY Gemfile Gemfile.lock package.json yarn.lock ./ RUN yarn set version berry RUN bundle update --bundler RUN bundle install --jobs 5 ADD . /app RUN yarn install RUN yarn install --frozen-lockfile \ && RAILS_SECRET_KEY_BASE=secret_key_base RAILS_ENV=production bundle exec rails assets:precompile apipie:cache \ && rm -rf node_modules EXPOSE 5000 VOLUME ["/app/public", "/usr/local/bundle"] CMD bash -c "bundle exec puma -C config/puma.rb" At this point the only dependency in my Rails app that doesn't work with this Dockerfile is wkhtmltopdf. I would prefer to install wkhtmltopdf with the Alpine Package Keeper (apk) as part of RUN apk --update add --no-cache. But, it appears that the latest version of Alpine that has the wkhtmltopdf package available is Alpine 3.14. The release notes for Alpine 3.15 state "qt5-qtwebkit, kdewebkit, wkhtmltopdf, and py3-pdfkit have been removed due to known vulnerabilities and lack of upstream support for qtwebkit." So other than switching off of Alpine Linux, which would present other dependency issues. I would prefer not to do as that seems to be the version used by most Dockerized Rails apps for the foreseeable future, what are my options? I also tried using the wkhtmltopdf_binary gem, but that was last updated in 2016. When I try to export a PDF using wicked_pdf with wkhtmltopdf installed by that gem, I get this error: /usr/local/bundle/gems/wkhtmltopdf-binary-0.12.6.5/bin/wkhtmltopdf:61:in `<top (required)>': Invalid platform, must be running on Ubuntu 16.04/18.04/20.04 CentOS 6/7/8, Debian 9/10, archlinux amd64, or intel-based Cocoa macOS (missing binary: /usr/local/bundle/gems/wkhtmltopdf-binary-0.12.6.5/bin/wkhtmltopdf_alpine_3.16.0_i386). (RuntimeError) from /usr/local/bundle/bin/wkhtmltopdf:25:in `load' from /usr/local/bundle/bin/wkhtmltopdf:25:in `<main>' I believe I'm getting this error because the docker image ruby:3.0.4-alpine is running Alpine 3.16 and Alpine dropped support for wkhtmltopdf on version 3.14. The wkhtmltopdf_binary gem hasn't been updated since 2016, so it wouldn't target more recent versions of Alpine. So, what are my options to work around this? Is there a way to script a compatible installation of the wkhtmltopdf in my Dockerfile? If so, how would I do that? I haven't been able to find another gem that targets more recent versions of Alpine that install wkhtmltopdf. Is there one out there that I'm missing? This has to be a common problem (Rails app running on Docker Alpine image with Ruby 3+ that needs to export PDFs using wkhtmltopdf). Or, is there another way to export PDFs in ruby that doesn't depend on wkhtmltopdf that I haven't found? (I've found other NodeJS options, but that introduces a whole other set of dependencies, so a Docker/Ruby solution is preferable.)
{ "language": "en", "url": "https://stackoverflow.com/questions/72833181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javac is making all names of my code into myclass.class I was just trying to compile my java code then I did this in the cmd: chdir C:\All_files (my directory) javac Hello.java then when I did this: java Hello 오류: 기본 클래스 hello을(를) 찾거나 로드할 수 없습니다. (Error: cannot find class hello) then I did this: javac myclass then it worked. How do I fix that? Here is my code: public class Hello { public static void main(String[] args) { System.out.println("Hello Windows 10"); } } I want to know how do I make javac produce the right title for the compiled class. A: What do you want to fix? First you compiled your source file with javac Hello.java... Then you tried to run it with java Hello... However the command java requires a fully qualified class name. What you supplied (Hello) seems to me, like the name of he .class file, without extension. When you tried with java myclass, it worked, because it is the fully qualified class name of your class... See: java and javaw reference
{ "language": "en", "url": "https://stackoverflow.com/questions/45951452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Config script passing value to another script I got these two scripts, configScript.sh and genScript.sh. The first one works precisely how I want to. I would like the second one to maintain the the option chosen last time the config file ran, and then display the correct echodepending on that. As it is now it always displays the second option. Is this doable? #!/bin/bash -x func() { echo " Choose 1 - Option 1 2 - Option 2 " echo -n " Enter selection: " read select case $select in 1 ) echo " Option 1 chosen" export OPTION=one . ./genScript.sh ;; 2 ) echo " Option 2 chosen" option="two" export OPTION=one . ./genScript.sh ;; esac } clear func #!/bin/bash func2() { if [ ${OPTION} == "one" ] ; then echo "Option one" else echo "Option two" fi } func2 To clarify, if I run configScript.sh and choose option it outputs Option one as I want. If I then run genScript.sh I want it as well to output Option one Edit* Updated the code A: Perhaps "export option" instead of "export searchBar". A: Try this code: #!/bin/bash -x func() { echo " Choose 1 - Option 1 2 - Option 2 " echo -n " Enter selection: " read select case $select in 1 ) echo " Option 1 chosen" OPTION=one export OPTION ./genScript.sh ;; 2 ) echo " Option 2 chosen" OPTION=two export OPTION ./genScript.sh ;; esac } clear func #!/bin/bash func2() { if [ ${OPTION} == "one" ] ; then echo "Option one" else echo "Option two" fi } func2 and finally run the configScript.sh with this command: . ./configScript.sh from the shell. A: I wonder if you actually have a comment line before your shebang line: #! must be the first 2 characters in the file. I also wonder if you're actually executing these scripts with sh instead of bash. Change [ "$option" == "one" ] to [[ $option == "one" ]] Instead of exporting, the config script needs to store the value: declare -p OPTION > ~/.my_config And then the other script can do . ~/.my_config if [[ $OPTION == "one" ]]; ...
{ "language": "en", "url": "https://stackoverflow.com/questions/20252755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to return correct status code when enumeration of IEnumerable fails. ASP.NET WebApi NOTE: The following problem happens only during testing of the controller. Here is refined question How to properly integration test Web Api controller with IEnumerable results? Is there any way to avoid calling ToList method but still return correct status code in case of exception from deferred LINQ execution to keep controllers as simple as possible? E.g. I have such API endpoint: public class EntityController : ApiController { ... public IHttpActionResult Get() { return Ok(Session.Query<Entity>()); } } Above code will always return successful status code, but with ToList it will not be successful in case of any trouble executing the query. public class EntityController : ApiController { ... public IHttpActionResult Get() { return Ok(Session.Query<Entity>().ToList()); } } The reason why it work like that is clear, but is there any smarter way to return proper status code and keep controller simple? A: You could debug the action, then look what exception gets thrown. Then you can easily try-catch this line of code and if if fails, you give something different then 500 back. try { return //...; } catch (//your Exception) { return //... As Example BadRequest or something different } Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/31450326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: selecting text in quotes How do I select the text found in double quotes? # cat list.txt File "abc.txt" not found. I want to return only abc.txt I am not sure which is the best tool for this purpose. A: To find all text within double quotes, try this. grep -o '"[^"]*"' list.txt The single quotes are to prevent the pattern from the shell; the actual pattern says to match a double quote, followed by a sequence of characters which are not double quote, followed by another double quote. The -o option to grep says to only print the matches (the default is to print the whole line when there is a match on the pattern). A: perl -nle'print $1 while /"([^"]*)"/g' list.txt With GNU grep if you have one occurrence per line: grep -Po '(?<=")[^"]*(?=")' list.txt A: kent$ echo 'File "abc.txt" not found.'|sed -r 's/.*"([^"]*)".*/\1/g' abc.txt A: echo 'File "abc.txt" not found.' | awk '{print substr($2,2,length($2)-2)}'
{ "language": "en", "url": "https://stackoverflow.com/questions/7724343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assign variable value of string I'm new to Javascript - I tried searching the web was not able this situation into context. Here is the situation: import * as People from ./People.json import * as Education from ./Education.json import * as Vehicle from ./Vehicle.json ... function transpose(str : string) { let data = {}; if(validate(str)) //validate function returns true if valid string data = str //data takes in the string value and uses variable name runFile(data); //runFile expects data to be a JSON type ... } Essentially how do I convert str (string variable into a variable) if suppose str = "People" then data will be equal to the variable People or if str = "Vehicle" data will be Vehicle variable. I know this can be done with a map of {"People": People, "Vehicle": Vehicle} it just seems like there should be a better way? I also looked into eval(str) but that doesn't seem to do the trick. Any help would be appreciated. Thanks A: A "map" really is the best way. Good news is that you can save a few keystrokes with shorthand property names (ES2015): import * as People from ./People.json import * as Education from ./Education.json import * as Vehicle from ./Vehicle.json const lookup = {People,Education,Vehicle}; // equivalent to {"People":People, ...} function transpose(str : string) { let data = {}; if(validate(str)) //validate function returns true if valid string data = lookup[str] //data takes in the string value and uses variable name runFile(data); //runFile expects data to be a JSON type ... } A: Useful if you want to pass in JSON as a parameter to the transpose function. function transpose(jsonObj, str) { let data = {}; if(validate(str)) { data = jsonObj[str]; runFile(data); //runFile expects data to be a JSON type } ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/51255796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Click on a URL from an R string output Suppose I have an output from the cat function of R which is a URL. For example: cat("https://en.wikipedia.org/wiki/Statistics") # Output: https://en.wikipedia.org/wiki/Statistics Is there any command on the cat function or any other thing so that the output https://en.wikipedia.org/wiki/Statistics becomes a clickable URL in the R console? A: As you mentioned in the comments you are using RStudio. It is not specified why it has to be the console in R, but I assume there is a good reason to display the links within RStudio and I assume the viewer pane on the right next to the console also works for you. If that is the case you could do the following: library(DT) # for datatable() function library(shiny) # for tags$a() function data <- data.frame(link = toString(tags$a(href = paste0("http://google.de"), "google"))) datatable(data, escape = FALSE) Very close to the console ;) A: It would depend on how the output is being viewed. If this output is going to an HTML file, then all you need to do is set this as the location for a hyperlink. <a href="https://en.wikipedia.org/wiki/Statistics">https://en.wikipedia.org/wiki/Statistics</a> But if, for example, you are just viewing the output in notepad, then I don't believe notepad has the functionality for hyperlinks. I don't believe the R console directly supports hyperlinks or not. But it looks like from this: http://rmarkdown.rstudio.com/lesson-2.html that you can maybe use R Markdown to do what you want. A: This is not currently possible in RStudio, unfortunately. However, it is an open issue which you can upvote if you think it should be prioritised.
{ "language": "en", "url": "https://stackoverflow.com/questions/43923974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: getting var_dump() but no jquery action / login system checklogin.php <?php session_start(); $host="localhost"; // Host name $username="root"; // Mysql username $password="bonjour3"; // Mysql password $db_name="itit"; // Database name $tbl_name="members"; // Table name // Connect to server and select databse. $mysqli = new mysqli("$host", "$username", "$password", "$db_name")or die("cannot connect"); // Define $myusername and $mypassword $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; $sql = $mysqli->prepare("SELECT * FROM $tbl_name WHERE username=? and password=?"); $sql->bind_param('ss',$myusername,$mypassword); $sql->execute(); $sql->store_result();//apply to prepare statement $numRows = $sql->num_rows; if($numRows === 1){ $_SESSION['username'] = $myusername; var_dump($_SESSION['username']); } else { echo "Wrong Username or Password"; session_destroy(); } ?> The above script runs when someone logs in using this form: templates/indexforms.php <?php session_start(); ?> <form id="login" method="post" action="checklogin.php"> <h1>Member Login</h1> <p>Username:<input name="myusername" type="text" id="myusername"></p> <p>Password:<input name="mypassword" type="password" id="mypassword"></p> <input type="submit" name="Submit" value="Login"> </form> The above template gets loaded into index.php (below). I am trying to write an SPA so everything is being loaded and unloaded into the "main" div using jquery. index.php <?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>it IT</title> <script src="reqscripts/jquery.js" type="text/javascript"></script> <script src="js/application.js" type="text/javascript"></script> </head> <body> <div id="main"></div> </body> </html> Here is the jquery/ajax code which loads and unloads elements: js/application.js $(document).ready(function() { $("#main").load("templates/indexforms.php", function () { //When login form is submitted $("#login").submit(function(e) { e.preventDefault(); $.post("checklogin.php", $(this).serialize(), function() { //ajax post call $("#main").load("templates/login_success.php"); //load template $("#login").remove(); //remove form }); }); $(document).on("click", "#logoutlinkdiv a", function(e) { e.preventDefault(); $("#main").empty(); $("#main").load("templates/logout.php"); }); $(document).on("click", "#loginlinkdiv a", function(e) { e.preventDefault(); $("#main").empty(); $("#main").load("templates/indexforms.php"); }); }); }); After login, the jquery loads a "login_success.php" template: templates/login_success.php <?php session_start(); ?> <h1>Login Successful</h1> <h2>Username: <? echo $_SESSION['username']?></h2> <div id="logoutlinkdiv" > <a href = "#" >Log out</a> </div> If you click the "logoutlinkdiv" link, the jquery loads a template "logout.php": templates/logout.php <?php session_start(); session_destroy(); ?> <div id="loginlinkdiv" > <h2>You have been logged out.</h2> <a href = "#">Log in</a> </div> If you click the "Log in" link on the above template...the indexforms.php template gets loaded (above). Then, I try to login again. The checklogin.php script gets run and 'string(4) "obey"' gets displayed. This makes sense because I did a var_dump() for the username (obey) in the if block of checklogin.php. However, it seems like the jquery doesn't get executed...because the login_success.php page never loads. If I reload "index.php" and login again...it works - Basically, I don't understand why the flow of my program is acting like this. UPDATE Here is what I see in the firebug console under the NET tab. A bunch of requests stack up - until I go to login for a second time. Then, the requests clear...and only one request remains: I load the index page and I see: GET http://localhost/~Eamon/ 200 OK GET http://localhost/~Eamon/templates/indexforms.php 200 OK I click the login link and see: POST http://localhost/~Eamon/checklogin.php 200 OK GET jquery.js 304 Not Modified GET application.js 304 Not Modified GET http://localhost/~Eamon/templates/login_success.php 200 OK I click the logout link and see: GET http://localhost/~Eamon/templates/logout.php 200 OK Then I click the link that brings me to the login page again, and I see: GET http://localhost/~Eamon/templates/indexforms.php 200 OK Then, I enter my info and log in again and all the requests clear, and I only see: POST http://localhost/~Eamon/checklogin.php 200 OK I think I should be seeing: POST http://localhost/~Eamon/checklogin.php 200 OK GET jquery.js 304 Not Modified GET application.js 304 Not Modified A: After a little research, I think I fixed it...I had to change my jquery to this: ... $(document).on("click", "#loginlinkdiv a", function(e) { e.preventDefault(); location.reload(); $("#main").load("templates/indexforms.php"); }); ... I don't think that application.js was being executed (on second login) because index.php didn't reload the script upon clicking the "loginlinkdiv" link...the only way I could think to do this was to use location.reload(); which I think is reloading index.php - and the script is being read again. Anyone who can clarify why this works (or maybe suggest a better answer) gets kudos.
{ "language": "en", "url": "https://stackoverflow.com/questions/17177171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Firebase declaring data types Im trying to save my object in firebase database in order to retrieve it later again. {title: "Zombie", start: Tue Jan 30 2018 00:00:00 GMT+0100 (CET), end: Tue Feb 06 2018 23:59:59 GMT+0100 (CET), color: {primary: "#696969", secondary: "#D1E8FF"}, priority: "Low", …} However, whenever I save the data to the firebase database, it stores everything as a string. Since, the start and end attributes are date objects, and to be able to store them in a calendar, they need to remain objects. When firebase saves the whole object, it converts everything to a string including the start and end attributes. Is there a way to store the object into firebase as it is shown above? Or like in Angular through an "any" data type? Edit: What firebase returns (everything was converted to a string): {color: {primary: "#696969", secondary: "#D1E8FF"}, end: "2018-02-06T22:59:59.999Z", priority: (and so forth).......} Thank you very much!!! A: In TypeScript, you can convert a string date to an actual date using: const start = new Date(item.start); Or if it's bound in a template, you can just use the date pipe: {{ item.start | date }}
{ "language": "en", "url": "https://stackoverflow.com/questions/48530654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get Field value in User Defined Java Class in kettle? I am trying to get the Link field in the User Defined Java Class step from my below transformation. Here is the code which I have written in User Defined Java Class: private String link; public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { Object[] r=getRow(); if (r == null) { setOutputDone(); return false; } if (first) { link = getParameter("Link"); first = false; } String linkField = get(Fields.In, link).getString(r); logBasic("link:" + link); return true; } When I run the above code, here is the error that I get at the User Defined Java Class Step: 2016/06/28 11:26:57 - User Defined Java Class.0 - ERROR (version 5.4.0.1-130, build 1 from 2015-06-14_12-34-55 by buildguy) : Unexpected error 2016/06/28 11:26:57 - User Defined Java Class.0 - ERROR (version 5.4.0.1-130, build 1 from 2015-06-14_12-34-55 by buildguy) : org.pentaho.di.core.exception.KettleStepException: 2016/06/28 11:26:57 - User Defined Java Class.0 - Unable to find In field helper for field name 'null' 2016/06/28 11:26:57 - User Defined Java Class.0 - 2016/06/28 11:26:57 - User Defined Java Class.0 - at org.pentaho.di.trans.steps.userdefinedjavaclass.TransformClassBase.get(TransformClassBase.java:628) 2016/06/28 11:26:57 - User Defined Java Class.0 - at Processor.processRow(Processor.java:15) 2016/06/28 11:26:57 - User Defined Java Class.0 - at org.pentaho.di.trans.steps.userdefinedjavaclass.UserDefinedJavaClass.processRow(UserDefinedJavaClass.java:1018) 2016/06/28 11:26:57 - User Defined Java Class.0 - at org.pentaho.di.trans.step.RunThread.run(RunThread.java:62) 2016/06/28 11:26:57 - User Defined Java Class.0 - at java.lang.Thread.run(Thread.java:745) 2016/06/28 11:26:57 - User Defined Java Class.0 - Finished processing (I=0, O=0, R=1, W=0, U=0, E=1) To confirm the fields, here is the snapshot of Preview Data till the Filter rows step: Where am I going wrong? A: I figured out where I was missing. In the User Defined Java Class, in the Parameters tab below, I need to explicitly define the field name and it's alias, such as:
{ "language": "en", "url": "https://stackoverflow.com/questions/38068146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Liquibase update or liquibase migrate? What is the difference b/t liquibase ... migrate and liquibase ... update ? I cannot find any documentation on the migrate command at http://www.liquibase.org/documentation/command_line.html A: migrate is a simply an (undocumented) alias for update: 687 if (this.command.equalsIgnoreCase("migrate")) { 688 this.command = "update"; 689 } liquibase.integration.commandline.Main
{ "language": "en", "url": "https://stackoverflow.com/questions/43724434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to do a Applicative in F#? Given the following type and member function type Result<'TSuccess, 'TError> = | Success of 'TSuccess | Error of 'TError list with member this.apply fn = match (fn, this) with | Success(f), Success(x) -> Success(f x) | Error(e), Success(_) -> Error(e) | Success(_), Error(e) -> Error(e) | Error(e1), Error(e2) -> Error(List.concat [e1;e2]) and the following inline function let inline (<*>) (f: ^A) (t:^A) = let apply' = (^A : (member apply : ^A -> ^A) (t, f)) apply' And this call site let y () = Success (fun x -> x + 1) <*> (Success 3) I get the following error let y () = Success (fun x -> x + 1) <*> (Success 3);; -----------^^^^^^^^^^^^^^^^^^^^^^^^ /Users/robkuz/stdin(473,12): error FS0001: Type constraint mismatch. The type Result<'a,'c> is not compatible with type Result<('a -> 'b),'c> The resulting type would be infinite when unifying ''a' and ''a -> 'b' This whole thing is an attempt to emulate Haskells Applicative and the signature should be (<*>) :: forall f a b. Apply f => f (a -> b) -> f a -> f b But I dont afaik there is no way to express that in F# Any ideas on how to make that happen? A: In general, I think it is not a good idea to try to emulate Haskell patterns in F#. In Haskell, lot of code is written as very generic, because monads and applicatives are used more frequently. In F#, I prefer writing more specialized code, because you do not need to write code polymorphic over monads or applicatives and it just makes it easier to see what is going on. So, I do not think I would ever want to write <*> operator that works over any "applicative" in practice in F#. That said, the issue with your code is that the <*> operator uses the same ^A type parameter for both arguments and the result (while they are different types in the call) - if you use three separate type parameters it works fine: let inline (<*>) (f: ^B) (t:^A) : ^C = let apply' = (^A : (member apply : ^B -> ^C) (t, f)) apply'
{ "language": "en", "url": "https://stackoverflow.com/questions/37949413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Two different id's for retrieving draggable object? I have this piece of code, which works perfectly in retrieving coordinates for an draggable object, however as you notice here: $("#droppable").droppable({ accept: "#draggable, #draggable2", I have two draggable objects, which will both get the id "benchdropped" + c, how would you suggest I could have different id's for each type of draggable object so later I can use that in pug, to retrieve it. I mention everything else works, I am using NodeJS, PUG. Here is the code: ''' $("#droppable").droppable({ accept: "#draggable, #draggable2", drop: function(e, ui) { c++; var $obj = ui.helper.clone().attr('id', 'benchdropped' + c).draggable({ stop : function (event, ui) { positions[this.id] = ui.position; console.log('positions', positions); // console.log(Object.keys(positions)); //ids for benches - to be used in node. } }); '''
{ "language": "en", "url": "https://stackoverflow.com/questions/66299450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Shell script to create directory from any random directory I am currently in /Desktop on my ubuntu system and I want to create a directory named vip inside /Documents/subd. Please not that Documents and Desktop are at same level. But the crux of this question is that I have to write a shell script such that it can create the requied directory from any directory of the system, no matter where it is situated. I have tried concatenating $home with the required directory path!! But it is not working. mkdir $home."/Documents/subd/vip" I need to run this inside /Desktop or any other directory. Please guide me!! A: This should do the job: mkdir "$HOME/Documents/subd/vip" You just had some minor errors in your command.
{ "language": "en", "url": "https://stackoverflow.com/questions/60026382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: hadoop-streaming: reducer doesn't seem to be running when mapred.reduce.tasks=1 I am running a basic Map Reduce program via hadoop-streaming The Map looks like import sys index = int(sys.argv[1]) max = 0 for line in sys.stdin: fields = line.strip().split(",") if fields[index].isdigit(): val = int(fields[index]) if val > max: max = val else: print max I run it as hadoop jar /usr/local/Cellar/hadoop/1.0.3/libexec/contrib/streaming/hadoop-streaming-1.0.3.jar -D mapred.reduce.tasks=1 -input input -output output -mapper '/Users/hhimanshu/code/p/java/hadoop-programs/hadoop-programs/src/main/python_scripts/AttributeMax.py 8' -file /Users/me/code/p/java/hadoop-programs/hadoop-programs/src/main/python_scripts/AttributeMax.py I read in Hadoop in Action, mapred.reduce.tasks=1 is As we haven’t specified any particular reducer, it will use the default IdentityReducer. As its name implies, IdentityReducer passes its input straight to output. When I see my console, I see 12/07/30 16:01:33 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 12/07/30 16:01:33 WARN snappy.LoadSnappy: Snappy native library not loaded 12/07/30 16:01:33 INFO mapred.FileInputFormat: Total input paths to process : 1 12/07/30 16:01:34 INFO streaming.StreamJob: getLocalDirs(): [/Users/me/app/hadoop/tmp/mapred/local] 12/07/30 16:01:34 INFO streaming.StreamJob: Running job: job_201207291003_0037 12/07/30 16:01:34 INFO streaming.StreamJob: To kill this job, run: 12/07/30 16:01:34 INFO streaming.StreamJob: /usr/local/Cellar/hadoop/1.0.3/libexec/bin/../bin/hadoop job -Dmapred.job.tracker=localhost:9001 -kill job_201207291003_0037 12/07/30 16:01:34 INFO streaming.StreamJob: Tracking URL: http://localhost:50030/jobdetails.jsp?jobid=job_201207291003_0037 12/07/30 16:01:35 INFO streaming.StreamJob: map 0% reduce 0% 12/07/30 16:01:51 INFO streaming.StreamJob: map 100% reduce 0% It does't make any progress, just keeps on running. It seems it is not working, how do I fix this? UPDATE * *when D mapred.reduce.tasks=0 I see two files part-00000 and part-00001 both of the files has one line 0 *when D mapred.reduce.tasks=1 and -reduce 'cat' the behavior is same as if reduce is not doing anything *when I run cat file | python AttibuteMax.py 8 I get 868 which means D mapred.reduce.tasks=0 and cat file | python AttributeMax.py 8 are also not producing the same output(but they should , right?) What would be causing the difference in the behavior when input data is also same? UPDATE 1 * *when D mapred.reduce.tasks=0 I see 4 files part-00000, part-00001, part-00002 and part-00002 with single line 268, 706, 348, 868 respectively *and when I run $ cat ~/Downloads/hadoop/input/apat63_99.txt | python ../../../src/main/python_scripts/AttributeMax.py 8 | cat I do see desired output as 868 A: do you get the expected output when you set mapred.reduce.tasks=0? What if you specify -reducer 'cat' with mapred.reduce.tasks=1? One of the neat things about streaming is that you can test it pretty effectively from the command-line using pipes: cat input | python mapper.py | sort | python reducer.py but it seems like your app is not producing any output. A: Not sure about the exact answer, but for me, once I ran it on cluster with machines having better storage, it just worked fine :)
{ "language": "en", "url": "https://stackoverflow.com/questions/11730984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring Boot not returning username using CustomAuthenticationProvider I have been following Baeldung's Spring 2FA tutorial to implement 2FA. I have created a CustomAuthenticationProvider as instructed, however it's not behaving as expected. The odd thing is that after login, a username format that I'm not familiar with is displayed when using Principal.getName(): com.appname.models.User@69080b62 As parts of the application rely on this for fetching details, this isn't appropriate but I'm struggling to understand where I've gone wrong. I have done some research but without the correct nomenclature and the name of the format, I'm struggling to find the appropriate result. public Authentication authenticate(Authentication auth) throws AuthenticationException { User user = userRepository.findByUsername(auth.getName()); if(user == null) { throw new BadCredentialsException("Invalid username or password"); } if(user.getTwoFactor()) { //as per tutorial } //this returns the "correct" username System.out.println(user.getUsername()); final Authentication result = super.authenticate(auth); //I suspect it's here that the issue is occurring, though any pointers in the right direction would be appreciated return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities()); } I'm expecting the actual username rather than...however it is currently being returned - i.e. an email address of a user. A: I have "solved" the problem by changing the last few lines to: final Authentication result = super.authenticate(auth); UserDetails userDetails = userDetailsService.loadUserByUsername(auth.getName()); return new UsernamePasswordAuthenticationToken(userDetails, result.getCredentials(), userDetails.getAuthorities()); ...where userDetailsService points to a simple implementation of the Spring Security UserDetailsService which returns a Spring Security UserDetails object, like so: @Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) { User user = userRepository.findByUsername(username); if(user == null) throw new UsernameNotFoundException(username); Set<GrantedAuthority> grantedAuthorities = new HashSet<>(); for (Role role : user.getRoles()) { grantedAuthorities.add(new SimpleGrantedAuthority(role.getName())); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), user.getNonExpired(), user.getCredentialsNonExpired(), user.getNonLocked(), grantedAuthorities); } This works elsewhere in my application so I figured it might work here as well. I believe I could have left the final argument as result.getAuthorities(). I think I can also refactor so I'm not hitting the database twice, but for now I'm just glad that it works. I'm not 100% sure why my relatively simple User model would not return the username as the Principal name, it may be that there is some more work which should be done to my User object to explicitly mark the username String as the principal name. If anyone is interested in any further updates, or can provide any more information for anyone else experiencing uncertainty on this issue, please leave a comment or provide another (likely better) answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/56304926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use ocamlformat at the same time as ppxlib As seen here, I am trying to use ocamlformat as a library. However, I am also using ppxlib in the same project and when I try to include them both in the libraries section of my dune file, I get: dune build File "_none_", line 1: Error: Files <path_to_my_project>/_opam/lib/ocamlformat/ocaml_common/ocaml_common.cmxa and <path_to_my_project>/_opam/lib/ppxlib/astlib/astlib.cmxa make inconsistent assumptions over interface Ocaml_common
{ "language": "en", "url": "https://stackoverflow.com/questions/71999410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails.How to format Strings in bullet point I want the div to be dynamic.The string that i get might contain bullet point like this a :"Uses •This is a test: •This is a test •This is a test •This is a test •This is a test •This is a test •This is a test •This is a test •This is a test". I have a div that shows the output: <div class="ds-results-detail-a">${a}</div> How can i show that response in list like: Uses •This is a test: •This is a test •This is a test •This is a test •This is a test •This is a test •This is a test •This is a test The response might contain strings with those bullet point or may be simply String. The output simply shows like: Uses •This is a test: •This is a test •This is a test •This is a test •This is a test •This is a test •This is a test •This is a test •This is a test How to show in list?Thanks in advance :) A: If I understood it right, you need to have smth like: <ul> <g:each in="${yourString.split( '•' )}" var="s"> <li>${s}</li> </g:each> </ul> UPD: Another way: ${yourString.replaceAll( '•', '<br>•' )}
{ "language": "en", "url": "https://stackoverflow.com/questions/50212410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pytest not collecting tests in dependency order I'm using pytest to test my package and I'm facing problems with dependency of tests, cause pytest is collecting (and testing) the sequence in alphabetical order, while it should be in dependency order. How can I change it? More details: The sequence of test it should runis: * *materials: Needs nothing *onerodtraction, onerodtorsion, onerodbending: Needs (1) *onerodallcharges: Needs the three above (2) *examples: Needs the (3) When I run I receive: tests\test_examples.py ssssssssssss [ 22%] tests\test_material.py ... [ 27%] tests\test_onerodallcharges.py sss [ 33%] tests\test_onerodbending.py .................. [ 66%] tests\test_onerodtorsion.py ......... [ 83%] tests\test_onerodtraction.py ......... [100%] As we see, every test in the third file is skipped, and then the same happens for the first file. A: May be you can try this pytest_order pip install pytest-order After installing you can mark on your classes. https://pytest-dev.github.io/pytest-order/stable/usage.html#markers-on-class-level In the each python file on each class specify the order as said @pytest.mark.order(1) class test_onerodtraction: @pytest.mark.order(1) class test_onerodtorsion: @pytest.mark.order(1) class test_onerodbending: and now @pytest.mark.order(2) class test_onerodallcharges: and then @pytest.mark.order(3) class test_examples.py: A: I would recommend using pytest-dependency * *With order if you want to add a test case in middle, reordering will be required. *parallel execution wont be effective. https://pytest-dependency.readthedocs.io/en/stable/usage.html
{ "language": "en", "url": "https://stackoverflow.com/questions/73127835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: luainterface problems I have some problems with C# luainterface library: 1. So I load a script and extract its functions like that: LuaFunction function = lua.GetFunction("Update"); But what if I load two different scripts that contains functions with the same name. How to extract two different functions with the same name from script1 and script2? 2. If I load functions into memory, is it possible to dispose a specific one, not all functions? 3. When I use Lua.DoFile method I want to execute specific function from the file. Any ideas how to do that? Edit 2. I found, that I can do something like this string f = @" function hh() end"; var result = lua.DoString(f)[0] as LuaFunction; but for some reason I get null exception. Any ideas why? A: DoString will return what your script return. lua.DoString ("return 10+10")[0]; // <-- will return Double. 20 If you want to get your Lua function as LuaFunction object you need to return your function, or even better just use the [] operator to get the global value of hh. lua.DoString ("function hh() end"); var hh = lua["hh"] as LuaFunction; hh.Call (); Here is a example: https://github.com/codefoco/NLuaBox/blob/master/NLuaBox/AppDelegate.cs#L46 (but Using NLua instead LuaInterface) And remember to release your LuaFunction calling Dispose when you don't need the function anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/20015984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: table inner join not displaying expected results I am trying to get a query to display some results. I double checked the logic to make sure that it is correct and it looks like it should work to me but does not. I created a query with the logic I need to use, code is at the bottom. SELECT * FROM vendor v -- select table inner join product p -- join second table on v.V_CODE = p.V_CODE -- link table where p.P_QOH <= p.P_MIN; -- filter products where product quantity on hand is less than or equal to product minimum count -- TODO: Get results to actually display Expected results are: a list of products where the product quantity on hand is less than or equal to the minimum quantity. Actual results: No products return, its empty. This is what my table looks like: table A: From what I can see on your table, the condition is never met. Also it might be a performance issue if the table became very large and should be a self-join.
{ "language": "en", "url": "https://stackoverflow.com/questions/55680386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Expandable listview with checkbox and Select All Button I have expandable listview in my app.I have two groups in expandable listview,each groups have select all button,when i click select all button check all child checkboxes in the group.how can i achive this? Group_items.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="40dp" android:background="@color/white" android:layout_marginTop="5dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/filter_item_header" android:textSize="16sp" android:text="Header" android:layout_centerVertical="true" android:textColor="@color/black" android:fontFamily="sans-serif-light" android:layout_marginLeft="5dp" android:textAllCaps="true"/> <android.support.v7.widget.AppCompatCheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/filter_select_all" android:text="Select All" android:textSize="16sp" android:fontFamily="sans-serif" android:layout_alignParentRight="true" android:textAllCaps="false" android:layout_marginRight="10dp" android:visibility="visible" android:focusable="false"/> </RelativeLayout> </LinearLayout> Child items.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_marginTop="5dp"> <android.support.v7.widget.AppCompatCheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/type_checkbox" android:text="Type Name" android:textSize="14sp" android:fontFamily="sans-serif-light" android:layout_marginLeft="10dp" app:buttonTint="#A9A9A9" /> <android.support.v7.widget.AppCompatCheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/category_checkbox" android:text="Category Name" android:textSize="14sp" android:fontFamily="sans-serif-light" android:layout_marginLeft="10dp" android:visibility="visible" app:buttonTint="#A9A9A9" /> </LinearLayout> </LinearLayout> Expandable list Adapter class: package com.deemsysinc.cyberhealthapp.exercisediary; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Typeface; import android.support.v7.widget.AppCompatCheckBox; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.deemsysinc.cyberhealthapp.R; import com.deemsysinc.cyberhealthapp.fooddiary.FoodDiaryChild; import com.deemsysinc.cyberhealthapp.fooddiary.FoodDiaryGroup; import com.deemsysinc.cyberhealthapp.utils.AppController; import java.util.ArrayList; import java.util.HashMap; import de.hdodenhof.circleimageview.CircleImageView; public class FilterListAdapter extends BaseExpandableListAdapter { private Context context; private ArrayList<String> titleheader; private HashMap<String,ArrayList<FilterChild>> stringArrayListHashMap; ArrayList<Integer> categoryArray; ArrayList<Integer> typeArray; ArrayList<String> categoryString; ArrayList<String> typeStrings; //-----------------------------------------------------------------------------------------------------// //-------------------------------------------------ArrayList-------------------------------------------// private ArrayList<FilterGroup> filterGroups; //-----------------------------------------------------------------------------------------------------// //------------------------------------------------Image Loader-----------------------------------------// ImageLoader imageLoader; //-----------------------------------------------------------------------------------------------------// //----------------------------------------------Constructor--------------------------------------------// public FilterListAdapter(Context context, ArrayList<FilterGroup> filterGroups) { this.context=context; this.filterGroups=filterGroups; } public FilterListAdapter(Context context1,ArrayList<String> titleheader,HashMap<String,ArrayList<FilterChild>> stringFilterChildHashMap) { this.context=context1; this.titleheader=titleheader; this.stringArrayListHashMap=stringFilterChildHashMap; categoryArray=new ArrayList<Integer>(); typeArray=new ArrayList<Integer>(); categoryString=new ArrayList<String>(); typeStrings=new ArrayList<String>(); } //------------------------------------------------Ends-------------------------------------------------// //-----------------------------------------------Base Adapter implementation methods-------------------// @Override public int getGroupCount() { return titleheader.size(); } @Override public int getChildrenCount(int groupPosition) { return this.stringArrayListHashMap.get(this.titleheader.get(groupPosition)) .size(); } @Override public Object getGroup(int groupPosition) { return this.titleheader.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return this.stringArrayListHashMap.get(this.titleheader.get(groupPosition)) .get(childPosition); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return true; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String headerTitle = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.filtes_item_header, null); } TextView lblListHeader = (TextView) convertView .findViewById(R.id.filter_item_header); AppCompatCheckBox selectAll=(AppCompatCheckBox) convertView.findViewById(R.id.filter_select_all); lblListHeader.setText(headerTitle); return convertView; } @Override public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final FilterChild filterChild=(FilterChild) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.exercise_filter_list_item, null); } AppCompatCheckBox txtListChild = (AppCompatCheckBox) convertView .findViewById(R.id.type_checkbox); AppCompatCheckBox txtListChild1 = (AppCompatCheckBox) convertView .findViewById(R.id.category_checkbox); Log.d("GropPosition",""+groupPosition); if(groupPosition==0) { txtListChild1.setVisibility(View.VISIBLE); txtListChild.setVisibility(View.GONE); txtListChild1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked==true) { Log.d("CategorTheId", filterChild.getCategoryid()); categoryArray.add(Integer.parseInt(filterChild.getCategoryid())); String category=filterChild.getCategoryname().substring(0,Math.min(5,filterChild.getCategoryname().length())); Log.d("SubsCateg",category); categoryString.add(category); } else { if(categoryArray.size()>0) { categoryArray.remove(childPosition); notifyDataSetChanged(); } if(categoryString.size()>0) { categoryString.remove(childPosition); notifyDataSetChanged(); } } } }); } if(groupPosition==1) { txtListChild.setVisibility(View.VISIBLE); txtListChild1.setVisibility(View.GONE); txtListChild.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked==true) { Log.d("TheTypeid",filterChild.getTypeid()); typeArray.add(Integer.parseInt(filterChild.getTypeid())); String type=filterChild.getTypename().substring(0,Math.min(5,filterChild.getTypename().length())); typeStrings.add(type); } else { if(typeArray.size()>0) { typeArray.remove(childPosition); notifyDataSetChanged(); } if(typeStrings.size()>0) { typeStrings.remove(childPosition); notifyDataSetChanged(); } } } }); } txtListChild.setText(filterChild.getTypename()); txtListChild1.setText(filterChild.getCategoryname()); return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public ArrayList<Integer> getCategoryArray() { return categoryArray; } public ArrayList<Integer> getTypeArray() { return typeArray; } public ArrayList<String> getCategoryString() { return categoryString; } public ArrayList<String> getTypeStrings() { return typeStrings; } /**private CompoundButton.OnCheckedChangeListener groupchecklistener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int index = (Integer) buttonView.getTag(); for(int i = 0;i<filterGroups.get(index).getFilterChildCategories().size();i++){ filterGroups.get(index).getContacts().get(i).setCheck(isChecked); } filterGroups.get(index).setCheck(isChecked); notifyDataSetChanged(); } };*/ }
{ "language": "en", "url": "https://stackoverflow.com/questions/44173203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: phonegap single sign on I'm building a PhoneGap app where one of the requirements is to support SSO (Single Sign On). I have a web application which supports different types of authentication. Now I'm building a mobile application (using PhoneGap) for the same web application and want to use the same authentication method to log-in from mobile which I use for logging-in from the web application Basically the PhoneGap mobile app should use the same authentication method (say Customer Portal/SAML/NT Auth etc) which the user uses to log-in into the web application from a desktop The main problem I'm facing is, if the web application is configured to use Customer Portal for authentication, then the user should be redirected to the portal and after authentication he should be redirected back to the mobile (PhoneGap) application and should get a authentication token which can be used by the mobile app for further requests. I was trying to use the InAppBrowser/ChildBrowser plugin to open the external URL (customer portal) and post data (authentication token) from InAppBrowser to the PhoneGap mobile app but I'm not sure if this is the correct approach or even if it is feasible. Please can somebody help me in if the above approach is feasible or is there any other approach I have to take. Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/15409979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to show data in popup with server side processing in Django templates (popup) Here, I have a Django form and view. I am displaying the data from db using datatables in Django template. Now I want the view functionality when, I click on view button it should render corresponding row data in popup boxlike "https://datatables.net/extensions/responsive/examples/display-types/bootstrap4-modal.html" How can we achieve this with Django templates? service.html <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="id_veh" class="control-label"> Car </label> <div class="controls "> {{ervice.veh_id}} </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="id_service_date" class="control-label"> Service Dtae </label> <div class="controls "> {{service.service_date}} </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="id_kms" class="control-label"> Kms </label> <div class="controls "> {{service.kms}} </div> </div> </div> views.py def add_edit_servicing(request, id=None, service=None): # if id: service = Service.objects.get(pk=id) if request.method == 'POST': form = ServiceForm(request.POST, request=request) if form.is_valid(): ...... ..... service.save() context = { 'menu': 'active', 'submenu':'active', 'form': form, 'id':id, 'service':service, } return render(request, 'service.html', context=context) list.html <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-body"> <table id="service" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Veh</th> <th>Service Date</th> <th>KMS</th> <th>View</th> </tr> </thead> </table> </div> </div> </div> </div> </section> {% endblock %} {% block scripts %} <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.bootstrap4.min.js"></script> <script src="https://cdn.datatables.net/select/1.3.0/js/dataTables.select.min.js"></script> <script src="/static/plugins/datatables/dataTables.editor.js"></script> <script src="/static/plugins/datatables/editor.bootstrap4.min.js"></script> <script> $(document).ready(function () { $.extend(true, $.fn.dataTable.defaults, { columnDefs: [ { targets: '_all', defaultContent: '' } ] }); var table = $('#service').DataTable({ "pageLength": 100, "serverSide": true, "bSearchable":true, "dom": 'blfrtip', "ajax": "/maint/dt/car_service/?format=datatables", "columns": [ { "data": "c.number" }, { "data": "service_date" }, { "data": "kms" }, { "data": "id", "bSortable": false, "mRender": function (data, type, full) { return '<a class="btn btn-sm btn-primary" href="srv/service' + full.id + '/view">' + 'View' + '</a>'; } }] }); }); function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); </script> {% endblock %} Mentioned datatable ("https://datatables.net/extensions/responsive/examples/display-types/bootstrap4-modal.html") functionality is not working for me to populate the data. Thankyou
{ "language": "en", "url": "https://stackoverflow.com/questions/59967966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I remove extra space under contents using BS3 I was working with the official BS3 example http://getbootstrap.com/examples/navbar-static-top/ Which somehow leaves extra spaces below the content (Please click the link for see in action). How can I make it auto adjusted by the contents? Please consider me as learner. A: The body has: min-height: 2000px; that's why there is extra space..
{ "language": "en", "url": "https://stackoverflow.com/questions/24668859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What should I add to a custom class so it works with System.Windows.Forms.Listbox.Items.Contains()..? What should I add to a custom class so it works with System.Windows.Forms.Listbox.Items.Contains()..? I've created a class called "FileItem" for handling filenames in ListBoxes. It works as expected, but if I try to use ListBox.Items.Contains() to prevent duplicate items from being added, nothing happens. The Contains() function never returns True. Here's the code. Add it to a VB.Net form named frmTest with a ListBox1, Button1, and Button2. Run it and press Button1 multiple times. The duplicate warning message is never displayed. Public Class frmTest Private Sub frmTest_Load(sender As Object, e As EventArgs) Handles Me.Load With ListBox1 .DisplayMember = "ShortName" .ValueMember = "LongName" End With End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim f As FileItem = New FileItem("C:\Windows\Notepad.exe") If ListBox1.Items.Contains(f) Then MsgBox("The file is already added and will be skipped.") Else ListBox1.Items.Add(f) End If f = Nothing End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim msg As String = "" For Each item As FileItem In ListBox1.Items msg &= item.FullName & vbCr Next MsgBox(msg) End Sub Private Class FileItem Private ReadOnly _FullName As String Private ReadOnly _ShortName As String Public Sub New(ByVal FullName As String) _FullName = FullName If FullName.Contains("\") Then Dim pos As Integer = FullName.LastIndexOf("\") _ShortName = FullName.Substring(pos + 1) End If End Sub Public ReadOnly Property FullName() As String Get Return _FullName End Get End Property Public ReadOnly Property ShortName() As String Get Return _ShortName End Get End Property Public Overrides Function ToString() As String Return _FullName End Function End Class End Class
{ "language": "en", "url": "https://stackoverflow.com/questions/71301727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: load a new page when an html's selector changes without javascript How can I (if at all) load a new page when an html's selector changes if javascript is disabled in the browser. Can it be done? A: I guess you mean the html select box having some page titles displayed and as soon as the user selects one of them the new page showes up. This is not possible with out javascript - the only thing you could do is to add a submit button. <noscript><input type="submit" value="go!"></noscript> This button would only be displayed if javascript is not activated. A: No, you cannot reload a page when a select box changes (if that's your question) without using a scripting language or similar. A: Without a scripting language (that would be JavaScript if you want to be cross-browser), most form elements are "dumb", they hold their state and display user feedback. So if you want to select a new page after selecting it in a form (combo box, list, radio buttons...), you have to add a submit button to send the choice to a server, and have a server side script handling the choice and serving the right page. The good old Web 1.0 way... :-) A: You can't. With HTML only, changing the selected option makes the value of that option to be sent to the server upon submit (either via the Enter key or a submit/button element). You can eventually set up the receiving script to send back a HTTP Redirect based according to the selected option. You shouldn't. This kind of navigation widget implies the use of a mouse: somebody using the keyboard to navigate the page cannot even select the second option at all (as soon as the down arrow is pressed once the onchange() event activates). Do the right thing and add a submit button, with the page change activated by the onsubmit() event.
{ "language": "en", "url": "https://stackoverflow.com/questions/1353393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Export to Excel tool for asp.net Is there any tool that can export a dynamically generated html to excel in c sharp? A: why do u want to write functionality that already exists. mean excel has it, u can import any web page (just to note excel uses IE engine to render tags). here are steps how it can be achieved. Open excel; go to Data Tab; click From Web; New Web Query child window opens. write into Address Bar and go to the web page u wan to import. after page loads into the window click import button that's all. (i assumed u are using ms office 2007, if diff version, diff steps) just one more note. ms office uses IE rendering engine, so not all tags are supported, so if it looks ugly, do not blame me ;) A: see Create Excel (.XLS and .XLSX) file from C# A: I'm not sure how you want to export html to Excel. In Excel we are talking about rows and columns while html is a document. You would probably want to export html to Word or pdf. In any case, for creating Excel files in C# I've used the following 2 libraries: http://www.codeproject.com/KB/office/biffcsharp.aspx and http://code.google.com/p/excellibrary/
{ "language": "en", "url": "https://stackoverflow.com/questions/6608176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: Using button from a non-acitvity class in activity class I am wondering if it is possible to access a button from a non-activity class using an activity class? The button is in a different xml file than the one of the activity class. Also, is it possible to create options menu in the non-activity class? A: Whenever you need to access any UI element from a non-activity class, you need to pass the context to your class. A rough method is: in your activity's onCreate() method: myInstance.setContext(this); and in your Class, you have: Context mContext; public void setContext(Context c){ mContext = c; } A: I am wondering if it is possible to access a button from a non-activity class using an activity class? Yes, it's possible if the non-activity class can access the methods of an activity class. This can be done by passing the reference of an activity to that non-activity class in the onCreate() method. But remember to release that reference and any other reference to the activity Views when the Activity is destroyed, that is when it's onDestroy() method being called. The button is in a different xml file than the one of the activity class. A button that is not added to an Activity's View Tree can be accessed. You can inflate the layout that contains the button and add the inflated View root to your Activity's ViewGroup. Also, is it possible to create options menu in the non-activity class? Yes, it's possible if the non-activity class can access the methods of an activity class. A: Anyone can correct me if I'm wrong. But my assumption answer to your question and how I understand what you trying to achieve. Android has made it easy to access controls in other xml files. You have the < include> which you can include other non-activity(fragments) in your activity. Actually it's pretty easy to do this that is the first way to do it. I know they is another way still playing around with your xml files. There is resource to bring non-activity controls to activity layouts with having to do much programmatically. Look at resources available to you on your layout builder.
{ "language": "en", "url": "https://stackoverflow.com/questions/28491807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to install hbase in CDH-5.4.2 I am using hadoop 2.6.0/CDH-5.4.2. I am trying to install hbase. For that I have to start Hadoop. So I used this command "start-dfs.sh". But I get error message "Command not found". Do suggest me in this regard. A: You need to have Namenode and datanode services running: on master node: sudo service hadoop-hdfs-namenode start on datanodes: sudo service hadoop-hdfs-datanode start
{ "language": "en", "url": "https://stackoverflow.com/questions/32287629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: html2canvas not grabbing svg When I run this: html2canvas(document.body, { allowTaint: true, onrendered: function(canvas) { document.body.appendChild(canvas); } }); I have my whole page grabbed into a canvas, but the SVG isn't. Been looking around but I couldn't find anything helpful to solve it, any idea? A: I resolved it by telling leaflet to provide tiles as canvas and not as an svg jQuery("#print").on("click", function() { myCapture(); }); function myCapture() { html2canvas(document.body, { allowTaint: true, useCORS: true, onrendered: function(canvas) { document.body.appendChild(canvas); } }); } var map = L.map('map', { renderer: L.canvas() });
{ "language": "en", "url": "https://stackoverflow.com/questions/43379058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is rowID & rowNum (ROWID vs ROWNUM) I'd like to know difference between rowID and rowNUM And how to see both of these in our table. when I execute this: SELECT * FROM emp WHERE rownum=1 It returns one query but when I do the same for rowid it says inconsistent datatypes: expected ROWID got NUMBER And even in some of the tables, rownum returns null . Why so? Please clarify this: rowid vs rownum?(Demo query) Thank you EDIT: Require to use alias to display ROWID and ROWNUM(as they're pseudocolumn) like: SELECT rownum r1, rowid r2 FROM emp A: Rownum (numeric) = Generated Sequence Number of your output. Rowid (hexadecimal) = Generated automatically at the time of insertion of row. SELECT rowid,rownum fROM EMP ROWID ROWNUM ----- ---------------------- AAAR4AAAFAAGzg7AAA, 1 AAAR4AAAFAAGzg7AAB, 2 AAAR4AAAFAAGzg7AAC, 3 AAAR4AAAFAAGzg7AAD, 4 AAAR4AAAFAAGzg7AAE, 5 A: Both, ROWNUM and ROWID are pseudo columns. Rowid For each row in the database, the ROWID pseudo column returns the address of the row. An example query would be: SELECT ROWID, last_name FROM employees WHERE department_id = 20; More info on rowid here: https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns008.htm Rownum For each row returned by a query, the ROWNUM pseudo column returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on. You can limit the amount of results with rownum like this: SELECT * FROM employees WHERE ROWNUM < 10; More info on rownum here: https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm Difference The actual difference between rowid and rownum is, that rowid is a permanent unique identifier for that row. However, the rownum is temporary. If you change your query, the rownum number will refer to another row, the rowid won't. So the ROWNUM is a consecutive number which applicable for a specific SQL statement only. In contrary the ROWID, which is a unique ID for a row. A: * *Rowid gives the address of rows or records. Rownum gives a count of records *Rowid is permanently stored in the database. Rownum is not stored in the database permanently *Rowid is automatically assigned with every inserted into a table. Rownum is a dynamic value automatically retrieved along with select statement output. *It is only for display purpose. A: row id shows the unique identification for row rownum shows the unique default series of numbers. select * from emp where rownum<=5; (it will execute correctly and gives output first 5 rows in your table ) select * from emp where rowid<=5; (wrong because rowid helpful to identify the unique value)
{ "language": "en", "url": "https://stackoverflow.com/questions/34282583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: PHP syntax error although everything is correct? Im not sure why am I getting this syntax error. Parse error: syntax error, unexpected '{' in /var/www/test/db.php on line 13 The code seems fine to me... Can anyone give me a few tips? :) $server = 'host'; $username = 'username'; $password = 'password'; $database = 'database'; if(!mysql_connect($server, $username, $password)) { exit('Error: could not establish database connection'); } if(!mysql_select_db($database) { exit('Error: could not select the database'); } A: Is missing a close parenthesis if(!mysql_select_db($database) ) ^---Missing { exit('Error: could not select the database'); } A: if(!mysql_select_db($database)) you missed a ) A: You are missing a ) (closing bracket) in this line: if(!mysql_select_db($database)) A: You have missed a closing bracket in your second if statement. A: You missed a closing ) in your second if statement: if(!mysql_select_db($database) <<<<< A: You're missing a parenthesis: if(!mysql_select_db($database)) A: In case no one else told you. You missed a ) on the second if statement. That is a ")" or otherwise known as a closing parentheses.
{ "language": "en", "url": "https://stackoverflow.com/questions/20792196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: notification beeper like fb in php i'm new in php and i want to know if there is a way to make this script to read from db all events from users and trigger a popup notification something like "John is like your photo" or "Maria is following you" something like that,similar like facebook beeper. Any help apreciated! I have started with this codes: Fetch PHP code: <?php //fetch-popup-notification.php; include("connect.php"); $query = "SELECT * FROM notification_users WHERE status = 0 ORDER BY id DESC"; $result = mysqli_query($connect, $query); $output = ''; while($row = mysqli_fetch_array($result)) { $output .= ' <div class="alert alert_default"> <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> <p><strong>'.$row["subject"].'</strong> <small><em>'.$row["notification"].'</em></small> </p> </div> '; } echo $output; $update_query = "UPDATE notifications_users SET status = 1 WHERE status = 0"; mysqli_query($connect, $update_query); ?> Ajax code: <script type="text/javascript"> $(document).ready(function(){ setInterval(function(){ load_last_notification(); }, 6000); function load_last_notification() { $.ajax({ url:"notificari/fetch-popup-notification.php", method:"POST", success:function(data) { $('.notif-popup').html(data); } }) } }); </script> html: <div id='alert_popover'> <div class='wrapper'> <div class='notif-popup'> </div> </div> </div> in DB i have: id | subject | notification | status
{ "language": "en", "url": "https://stackoverflow.com/questions/46860019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i change the font family in phonegap I want to change font family in a phonegap project. Means that user be able to change font family in the setting by select the arbitrary font. How can i do it? Thanks in Advance Edit: Seems it doesn't work.this is my jquery code: $("#font-selector").change(function(){ $(".size").css("font-family",$("#font-selector").val()); }); And html code is: <select name="changeFont" id="font-selector" onchange='$("body").attr("data-font", $("#font-selector").val())'> <option value="my font">my font</option> <option value="my font">my font</option> And css code is: @font-face { font-family: 'my font'; src: url('my font.eot'); src: url('my font.eot?#iefix') format('embedded-opentype'), url('my font.woff2') format('woff2'), url('my font.woff') format('woff'), url('my font.ttf') format('truetype'), url('my font.svg#my font') format('svg'); font-weight: normal; font-style: normal; Where is the problem? A: You can use this plugin to get a list of all fonts of your device: cordova-plugin-fonts Then you can show to the user a list, let them select one and after that you change the css of your site by javascript. I'm not sure, but it could be, that you have to rerender the page after changing the font. A: Seems something you could easily do with javascript/css. Just ship your fonts in the app, to make sure they are available on any platform, and add a listener to your select which changes a css class to the body. This is the html code if you are using jQuery or Zepto syntax. <select name="changeFont" id="font-selector" onchange='$("body").attr("data-font", $("#font-selector").val())'> <option value="default">Default</option> <option value="arial">Arial</option> <option value="comic-sans">Comic Sans</option> </select> then in css .mytext { font-family: helvetica, sans-serif; } [data-font=arial] .mytext { font-family: arial, sans-serif; } [data-font=comic-sans] .mytext { font-family: "comic sans", sans-serif; } For this to work, just make sure that you have correctly added your fonts. To make this right you could use FontSquirrel webfont generator to convert any font to a web font and generate the needed css for you. I should add that I did not test this, so let me know if you find it's not working. Or, if your app is designed to work only when the user has internet connection then there's an even quicker way to add a lot of fonts. There's a jQuery plugin that will do exactly that.
{ "language": "en", "url": "https://stackoverflow.com/questions/33842859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OBIEE Charts do not show because of adobe flash player OBIEE uses flash player to render charts. After discontinuing support of adobe flash player, obiee charts do not display. Is there any way to render obiee charts without adobe flash player. A: OBIEE doesn't use flash anymore since many years because it's dead technology. You didn't upgrade and now get penalized. Any version that still uses flash is out of date and unsupported.
{ "language": "en", "url": "https://stackoverflow.com/questions/69185380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Tensorflow argmax give false indizes I am using tensorflow to train and use a small neural network (2d classification with two classes), but I have a really strange problem and fail to see what I am doing wrong: When I plot the predictions vs the true labels only for test batches for that the accuracy evals to 1., I clearly have some missclassified samples. It seems to me, that tf.argmax is responsible for the accuracy to mistakenly evaluate to 1, but obviously this can't really be the reason. Anyways, I came to this conclusion by calculating the accuracy from the last layer output: with tf.name_scope('accuracy'): plabel = tf.argmax(y, 1) # vector of predicted label, elem {0,1}^batch_size tlabel = tf.argmax(y_, 1) # similar vector of true labels correct_predictions = tf.cast(tf.equal(plabel, tlabel), tf.float32) ... with tf.Session() as sess: batchx, batchy = generate_batch() predictions, acc = sess.run([y, accuracy], feed_dict={x: batchx, y_: batchy}) mistakes = 0. for j in range(batch_size): if (predictions[j, 0] - predictions[j, 1])*(batchy[j, 0] - batchy[j, 1]) < 0: print("mistake: ", predictions[j], batchy[j]) mistakes += 1./batch_size print("Acc = {} / {} = 1-m/b".format(acc, 1. - mistakes)) x and y_ are the input tensors, y is the last layer and the model is trained already. It gives me the following output: Acc = 1.0 / 0.86 = 1-m/b These values should be the same. The plot also indicates that the true accuracy is not 1., or the evaluated accuracy tensor does not belong to the same run as the predictions (y). I found nothing that hints that tf.argmax really is the issue, and am quite desperate. So thanks in advance for any help A: It seems your accuracy function is correct since you didn't post whole your code, I would suggest you calculate accuracy inside the session, so each time you can print the content of predictions and true labels and trace the execution. Get predictions like predictions = sess.run(y, feed_dict={x: batchx, y_: batchy}) then print predictions by print predictions.eval(), then use plabel = tf.argmax(predictions, 1), again print plabel.eval(), also print batchy and print (tf.argmax(batchy)).eval() Now you should know what's going wrong with each print statement. A: For accuracy : def evaluate(X_data, y_data): num_examples = len(X_data) total_accuracy = 0 sess = tf.get_default_session() for offset in range(0, num_examples, BATCH_SIZE): batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE] accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y}) total_accuracy += (accuracy * len(batch_x)) return total_accuracy / num_examples for getting the prediction : prediction = sess.run(tf.argmax(logits, 1), feed_dict={x: train_data})
{ "language": "en", "url": "https://stackoverflow.com/questions/43815733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Safari Cache size for iPhone 3.0 Various sites on the internet claims that Safari cache on iPhone 2.2 is 25k and 19 objects. Does anyone know what is the cache size for Safari/webview on iPhone 3.0. A: specially if you use the client side storage or a cache manifest, you can store much more data Client application storage is different than the Safari's own cache, to which the original poster was referring. We know that in 2.2, Safari can store 19 objects each up to 25K in size. What are the new numbers for 3.0+? The posted link/pdf doesn't seem to have the answer. A: hmm... as far as i'm aware of, the cache size since version 2.2 is much larger. specially if you use the client side storage or a cache manifest, you can store much more data. how to store values clientside can be read here Apple developer Connection PDF version
{ "language": "en", "url": "https://stackoverflow.com/questions/805891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to increment only if cell is not empty on input with IFNA in Google Sheets? I found this prior answer to the issue here: How to increment only if cell is not empty But how to make it work on columns with IFNAs as blanks? Demo: https://i.imgur.com/7jYAZsw.gif Sample sheet: Table: 1 Test ONE and only. 1 ONE 1 ONE 2 2 2 Test TWO and only. 3 TWO 3 TWO 4 4 3 Test THREE and only. 5 THREE 5 THREE 6 6 4 Test FOUR and only. 7 FOUR 7 FOUR 8 8 9 9 10 10 5 Test FIVE and only. 11 FIVE 11 FIVE 12 12 Formulas: A1:B12: =arrayformula( iferror( countifs(row(B1:B), "<=" & row(B1:B), B1:B, "<>") / not(isblank(B1:B)) ) ) D1:D12: =arrayformula( iferror( countifs(row(E1:E), "<=" & row(E1:E), E1:E, "<>") / not(isblank(E1:E)) ) ) =IFNA(ArrayFormula(REGEXEXTRACT(B1:B,"\b([A-Z]{2,})+(?:\s+[A-Z]+)*\b")),"") I tried solution with IFNA as below but it's not working. G1:H12: =IFNA(arrayformula( iferror( countifs(row(H1:H), "<=" & row(H1:H), H1:H, "<>") / not(isblank(H1:H)) ) ),"") =IFNA(ArrayFormula(REGEXEXTRACT(E1:E,"\b([A-Z]{2,})+(?:\s+[A-Z]+)*\b")),"") Your solution is greatly appreciated. A: Try this out: =ARRAYFORMULA(IF(ISNA(E:E),,SCAN(,E:E,LAMBDA(a,c,a+NOT(ISNA(c)))))) Update =ARRAYFORMULA(IFNA(IF(D:D="",,SCAN(,D:D,LAMBDA(a,c,a+(IFNA(c)<>"")))))) A: You may try: =index(if(H:H="",,scan(,H:H,lambda(a,c,if(c="",a,a+1)))))
{ "language": "en", "url": "https://stackoverflow.com/questions/75449393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to move item from item list to favorite list in React I was able to fetch data from an API and list them. I did that by watching videos. Now I want to add a button that says "add to favorite" for each item and by clicking on them I want to move the item from that list to favorite list. How can I achieve that? Please explain this in details cause I'm new in programing. A: You can try something similar, function DummyComponent(){ const [fullList, setFullList] = useState(['item1', 'item2', 'item3', 'item4']) const [favList setFavList] = useState([]) const handleFavAddClick=(e)=>{ setFavList(preState=>[...preState, e]) setFullList(preState=> preState.filter(item => item !== e)) } return( <div> Full List (add to fav by clicking them) <ul> { fullList.map(e=> <li key={e} onClick={()=>handleFavAddClick(e)}>{e}</li>) } </ul> Fav List <ul> { favList.map(e=> <li key={e}>{e}</li>) } </ul> </div> ) } A: So, let's say you have two lists: const [items, setItems] = useState([]); const [favorites, setFavorites] = useState([]); You can use this function to achieve what you want. If you want to completely move an item from items list to favorites, pass false as the second argument or don't pass it at all. But if you want to just copy the item to favorites list, pass true. function moveToFavorites(id, copy) { setFavorites([...favorites, items.find(item => item.id === id)]); if(!copy) setItems(items.filter(item => item.id !== id)); } A: Your list you received from the api is in the form of a JSON object. Depending on how the data was structured you may have the list in an array or its still flat. Examples: A) List: { name: "john", }, { name: "jane"} } B) List: {list: ["john", "jane"]} Ideally you want option B. This means your list is in an Array. Look up documentation on how to convert JSON to an Array. There are great functions available to you in the lodash library which you can use. Once your list in in an array you should be ready for adding and removing favorites. example: let myList = ["john","jane"] What you will want to do is have another array called favorites. When the user clicks on an item in the list, it will be added to their favorites array. You are removing from one array and another. Here is an example function. let myList = ["john","jane"]; // list from api let favorites = [] // your new list //this function recieves the index (position) of the item the user clicked in the user interface const addFavorites = (index) => { favorites.push(myList[index]) // adds items to favorites array myList.splice(index, 1); // removes same item from myList } // call the function addFavorites(0) // will remove john console.log(favorites) console.log(myList) }
{ "language": "en", "url": "https://stackoverflow.com/questions/69515043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Qt QCursor::setPos() does nothing I've created a minimal class to demonstrate my problem. I'm trying to set the cursor position, but it shows no effect. In my example class I try to center the cursor to the widget. Here is my class: class testWidget : public QWidget { Q_OBJECT public: testWidget(); protected: virtual void mouseMoveEvent(QMouseEvent* event); }; And here is the implementation: testWidget::testWidget() { setMinimumSize(800,600); show(); } void testWidget::mouseMoveEvent(QMouseEvent *event) { QPoint before(mapFromGlobal(QCursor::pos())); QPoint center = mapToGlobal(QPoint(width()/2,height()/2)); QCursor::setPos(center); qDebug()<<"Before:"<<before<<"After:"<<mapFromGlobal(QCursor::pos()); } When moving the mouse cursor while pressing a mouse button I get the following output (exmaple): Before: QPoint(754,48) After: QPoint(400,300) This means before I called QCursor::setPos(center) the cursor is at the position 754;48 which is in the top-right corner of the widget. After I set the cursor-position with QCursor::setPosition(center) the cursor should be at the center of the widget, which it is not, the cursor stays in the top-right corner. And to my further confusion, QCursor::pos() returns the center of the widget, even though the cursor is not at the center. Any hints would be much appreciated. Thank you for your time... A: @Leiaz You are right, I've been working in a virtual machine. When running the program on my host system (which is also ubuntu) it works as expected. Thank you for your help. It even works in my VM now, after I've disabled the mouse integration. Thanks all.
{ "language": "en", "url": "https://stackoverflow.com/questions/26885507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Hide all spans that are close to cursor on mouseover? I am working on a project where I have several hundred spans next to each other, with a letter of the text in each span. When I hover over one of the spans, I want to hide it, as well as the other spans nearby. It makes an image like this: @@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@ My goal is to hide all of the spans in a given distance away from the mouse, like this: HTML <span id="overlay-1">@</span> <!-- ... --> <span id="overlay-142">@</span> <span id="overlay-143">@</span> I'm able to hide 1 of the spans by calling their ids on mouseover and changing the style to display=none, but I want to hide all that are in close proximity to the mouse. Any ideas on what I should do? A: I tried to solve this through JS. Here is my code: function paint() { let txt = ""; for (let j = 0; j < 100; j++) { txt += "<div>" for (let i = 0; i < 100; i++) { txt += `<span onmouseout="hoverOut()" onmouseover="hover(this)" onmouseuop id="overlay-${i}-${j}">@</span>` } txt += "</div>" } document.getElementById('painting').innerHTML += txt } function hover(x) { let id = x.id; let i = x.id.split('-')[1]; let j = x.id.split('-')[2]; for (let a = -2; a <= 2; a++) { for (let b = -1; b <= 1; b++) { const elem = document.getElementById(`overlay-${i-a}-${j-b}`); elem ? elem.style.opacity = 0 : null; } } x.style.opacity = '0'; } function hoverOut() { for (let i = 0; i < document.getElementsByTagName('span').length; i++) { document.getElementsByTagName('span')[i].style.opacity = 1; } } <body onload="paint()"> <div id="painting"> </div> </body> A: Another approach without using ids would be to use Element.getBoundingClientRect() to get the size and position of the hovered element and then use Document.elementFromPoint() inside a loop to access elements near the hovered one: const main = document.querySelector('main') for (let i = 0; i < 800; i++) main.innerHTML += '<span>@</span>' const spans = document.querySelectorAll('span') const areaWidth = 50 const areaHeight = 50 const hidden = [] function getElements(currentSpan, color) { const { top, right, bottom, left, width, height } = currentSpan.getBoundingClientRect() for (let col = left - areaWidth / 2; col < right + areaWidth / 2; col += width || 14) { for (let row = top - areaHeight / 2; row < bottom + areaHeight / 2; row += height || 14) { const el = document.elementFromPoint(col, row) if (el?.tagName === 'SPAN') { el.style.color = color hidden.push(el) } } } } spans.forEach(span => { span.addEventListener('mouseover', () => getElements(span, 'transparent')) span.addEventListener('mouseout', () => { hidden.forEach(el => (el.style.color = '')) hidden.length = 0 }) }) main { display: flex; flex-wrap: wrap; width: 640px; cursor: default; } <main></main> A: You could use a CSS solution - overwrite the adjacent characters with a pseudo element on the clicked character. This snippet uses a monospace font and it's set line height and letter spacing as CSS variables so you can alter them as required. function clicked(ev) { ev.target.classList.add('obscure'); } const container = document.querySelector('.container'); for (let i = 0; i < 200; i++) { const span = document.createElement('span'); span.innerHTML = '@'; if (i % 10 == 0) { container.innerHTML += '<br>'; } container.appendChild(span); } container.addEventListener('click', clicked); .container { width: 50vw; height: auto; font-family: Courier, monospace; --line-height: 20px; --letter-spacing: 5px; line-height: var(--line-height); letter-spacing: var(--letter-spacing); } .container span { position: relative; margin: 0; padding: 0; } .obscure::before { content: ''; width: calc(5ch + (6 * var(--letter-spacing))); height: calc(3 * var(--line-height)); background-color: white; position: absolute; top: 0; transform: translate(calc(-50% + 0.5ch), calc(-50% + (1ch))); left: 0; z-index: 1; display: inline-block; } <body> <div class="container"></div> </body> A: If I understand you right, you want the span to vanish, but you don't want its space to also vanish. display:none is the wrong solution. you need visibility:hidden. hiding the hovered element and elements before and after it is easy. the difficulty is in hiding element that are above or below it. to do that, you would need to do some math. assuming the answer doesn't need to be exact, you could do it something like this: * *calculate the centre positions of all spans and keep them in an array (so you don't need to recalculate every time) *when a span is mouse-entered, check the array and calculate all spans that are within radius r of that span's centre point - or just above/below/left/right - whatever works. *create a new array of spans that should be hidden *check all hidden spans - if any of them are not in that new array, unhide them (visibility:visible) *finally, go through the new array and set visibility:hidden on all spans in that array A: Here is a bit diffrent and custumisable aproch: // Variables const ROW = 10; // Total number of rows const COL = 35; // Total number of items in a row (i.e. columns) const RANGE = 2; // Total number of items to be selected in each direction const values = []; // To colect ids of items to be selected // Utility Function const push = (value) => { if (value > 0 && value <= ROW * COL && !values.includes(value)) values.push(value); }; // Add items in the root div const root = document.querySelector("#root"); for (let i = 0; i < ROW; i++) { root.innerHTML += `<div id="row-${i + 1}"></div>`; for (let j = 0; j < COL; j++) { document.querySelector(`#row-${i + 1}`).innerHTML += `<span id="item-${COL * i + (j + 1)}">@</span>`; } } // Add class to the items as per the RANGE root.addEventListener("mouseover", (e) => { values.length = 0; const id = e.target.id; if (!id.includes("item-")) return; const current = +id.replace("item-", ""); push(current); for (let i = -RANGE; i < RANGE; i++) { push(current + i); for (let j = -RANGE; j <= RANGE; j++) { push(current + COL * i + j); push(current - COL * i + j); } } for (let i = 0; i < values.length; i++) { const item = document.querySelector(`#item-${values[i]}`); item.classList.add("selected"); } }); // Remove class from the items as per the RANGE root.addEventListener("mouseout", () => { for (let i = 0; i < values.length; i++) { const item = document.querySelector(`#item-${values[i]}`); item.classList.remove("selected"); } }); /* Just for styling purposes */ body { background-color: #111; color: #fff; } #root [id*="item-"] { padding: 1px; } /* Styles for the selected item */ #root [id*="item-"].selected { /* color: transparent; */ /* Use this to get your intended effect */ color: #ffa600; } <div id="root"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/70418153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to count the frequency of a word in a file precisely using two buffers in C? I have a file of size 1GB. I want to find out how many times the word "sosowhat" is found in the file. I've written a code using fgetc() which reads one character at a time from the file which is way too slower when it comes for a file of size 1GB. So I made a buffer of size 1000(using mmalloc) to hold 1000 words at a time from the file and I used the strstr() function to count the occurrence of the word "sosowhat". The logic is fine. But the problem is that if the part "so" of "sosowhat" is located at the end of the buffer and the "sowhat" part in the new buffer, the word will not be counted. So I used two buffers old_buffer and current_buffer. At the beginning of each buffer I want to check from the last few characters of old buffer. Is this possible? How can I go back to the old buffer? Is it possible without memmove()? As a beginner, I will be more than happy for your help. A: Yes, it can be done. There are more possible approaches to this. The first one, which is the cleanest, is to keep a second buffer, as suggested, of the length of the searched word, where you keep the last chunk of the old buffer. (It needs to be exactly the length of the searched word because you store wordLength - 1 characters + NULL terminator). Then the quickest way is to append to this stored chunk from the old buffer the first wordLen - 1 characters from the new buffer and search your word here. Then continue with your search normally. - Of course you can create a buffer which can hold both chunks (the last bytes from the old buffer and the first bytes from the new one). Another approach (which I don't recommend, but can turn out to be a bit easier in terms of code) would be to fseek wordLen - 1 bytes backwards in the read file. This will "move" the chunk stored in previous approach to the next buffer. This is a bit dirtier as you will read some of the contents of the file twice. Although that's not something noticeable in terms of performance, I again recommend against it and use something like the first described approach. A: use the same algorithm as per fgetc only read from the buffers you created. It will be same efficient as strstr iterates thorough the string char by char as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/62895348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android - Firebase Database Structure I am developing an android application where older kids can pick up younger kids and walk to school. With the application the authenticated (email and password) younger kid can choose between three adresses to get picked up. As of right now my realtime database looks like this: Should I make a new node named "Adresses" and have a structure like this below? Adresses Sherman Street username: Jannie Because I want to retrieve the name of the street and all the users that have chosen the adress in a listview A: Your suggested method is good practice: you should try to flatten your data structure as much as possible. I'd suggest using the user's ID for the membership of each address so it's easy to identify though. This way you can obtain a list of the members of "Sherman Street" from /addresses/Sherman Street and then match the keys listed within there to the users at /users/ with ease. { "users": { "oXrJPVZsnMP3VKp9palSBfdnntk1": { ... }, "xQDx3ntavhV3c02KFRPS8lxYfC62": { ... } }, "addresses": { "Sherman Street": { "members": { "xQDx3ntavhV3c02KFRPS8lxYfC62": true } }, "Wallaby Way": { "members": { "oXrJPVZsnMP3VKp9palSBfdnntk1": true } } } } You can also add backwards linking too by adding an address field to the user which matches the address name: { "users": { "oXrJPVZsnMP3VKp9palSBfdnntk1": { ... }, "xQDx3ntavhV3c02KFRPS8lxYfC62": { "username": "Jannie", "address": "Sherman Street" } }, "addresses": { "Sherman Street": { ... } } } Using both together makes it easy to identify what users have selected which addresses, irrespective of which object you are currently handling within the app. See the Firebase documentation on database structure for further details on structuring your data like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/46712175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implement Adsense Matched Content with DFP I want to implement the Adsense Matched Content in a website using DFP, but I don't know which type of Ad Unit I need to create. The Matched Content tag is responsive, and I don't know which fixed size I need to create. Any ideas? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/39492036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set the read timeout for InputStream.read? If the server never send EOF, will InputStream.read hang? How to set the read timeout? A: How about setting a socket timeout. It sets the timeout on all the read operations on that socket
{ "language": "en", "url": "https://stackoverflow.com/questions/8845236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you put { and } in a format string I'm trying to generate some code at runtime where I put in some boiler-plate stuff and the user is allowed to enter the actual working code. My boiler-plate code looks something like this: using System; public class ClassName { public double TheFunction(double input) { // user entered code here } } Ideally, I think I want to use string.Format to insert the user code and create a unique class name, but I get an exception on the format string unless it looks like this: string formatString = @" using System; public class ClassName {0} public double TheFunction(double input) {0} {2} {1} {1}"; Then I call string.Format like this: string entireClass = string.Format(formatString, "{", "}", userInput); This is fine and I can deal with the ugliness of using {0} and {1} in the format string in place of my curly braces except that now my user input cannot use curly braces either. Is there a way to either escape the curly braces in my format string, or a good way to turn the curly braces in the user code into {0}'s and {1}'s? BTW, I know that this kind of thing is a security problem waiting to happen, but this is a Windows Forms app that's for internal use on systems that are not connected to the net so the risk is acceptable in this situation. A: "{{" and "}}" A: What I think you want is this... string formatString = @" using System; public class ClassName {{ public double TheFunction(double input) {{ {0} }} }}"; string entireClass = string.Format(formatString, userInput); A: Escape them by doubling them up: string s = String.Format("{{ hello to all }}"); Console.WriteLine(s); //prints '{ hello to all }' From http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1 A: Double the braces: string.Format("{{ {0} }}", "Hello, World"); would produce { Hello, World } A: Be extra extra cautious in who has access to the application. A better solution might be to create a simple parser that only expects a few, limited, commands.
{ "language": "en", "url": "https://stackoverflow.com/questions/160742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: calling javascript function of bool type I am trying to call a Page Method using AJAX. See the code <asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" Text="Upload" onclick="btn_upload_Click" OnClientClick="return Validate();" /> Validate method is supposed to return true/false. The code for Validate method is <script language="javascript"> function Validate() { var filename = $get('<%= txt_filename.ClientID %>').value; PageMethods.IsValidFile(filename,OnSuccess, OnFailure); // IsValidFile is a Page Method of bool return type } function OnSuccess(result) { if ( !result) { alert('File '+ $get('<%= txt_filename.ClientID %>').value + ' does not exist'); return false; } else { return true; } } function OnFailure(error) { } </script> My problem is that even after showing the alert 'File somefilename does not exist'. The whole page refrshes (i.e, postback happens) A: You are running an asyncronous operation and still expecting it to block your call and wait for the response, this is one workaround that i have seen in the past, you hide your submit button and create another button that calls your ajax request, in the success of this request you click you hidden button, something like this : <asp:Button ID="btn_upload_dummy" runat="server" CssClass="btnEffects" Text="Upload" OnClientClick="Validate();" /> <asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" style='display:none;' Text="Upload" onclick="btn_upload_Click" /> <script language="javascript"> function Validate() { var filename = $get('<%=txt_filename.ClientID %>').value; PageMethods.IsValidFile(filename,OnSuccess, OnFailure); // IsValidFile is a Page Method of bool return type } function OnSuccess(result) { if ( !result) { alert('File '+ $get('<%=txt_filename.ClientID %>').value + ' does not exist'); return false; } else { var btn = $get('<%btn_upload.ClientID'); var clicker = btn.click ? btn.click : btn.onclick; clicker(); } } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/4428444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django: problems with urlfields validation when overriding form validation I have some Form with two urlfields, both not required. The form is used to set the value of JSONField in a Model from these two urlfields (for user convenience), everything works fine. If a user enters something except an URL into url1 or url2, django shows validation error at the form "Enter a valid URL". Now I want to make a user to input URL in ANY of these urlfields. I'm overriding clean method for that: class MyForm(forms.ModelForm): url1 = forms.URLField(required=False) url2 = forms.URLField(required=False) def clean(self): cleaned_data = super(MyForm, self).clean() if not cleaned_data['url1'] and not cleaned_data['url2']: raise ValidationError( _("You should enter at least one URL"), code='no_urls' ) return cleaned_data It works, BUT there is a problem: if user enters some "non-URL" data into url1 or url2 and submits the form, Django raises KeyError with Exception Value: 'url1' (or 'url2') instead of showing a validation error at the form What's wrong? Thanks! A: As documented in quite a few places - notably the part about cross validation -, cleaned_data only contains valid data - the fields that didn't validate wont show up here. You have to account for this one way or another - by testing for key existence or, as shown in the cross-validation example snippet, using dict.get(): def clean(self): cleaned_data = super(MyForm, self).clean() # boolean algebra 101: "not A and not B" => "not (A or B)" if not (cleaned_data.get('url1') or cleaned_data.get('url2')): raise ValidationError( _("You should enter at least one URL"), code='no_urls' ) return cleaned_data
{ "language": "en", "url": "https://stackoverflow.com/questions/55024155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Anchor tag not appending within paragraph tag javascript I'm using the following code for (var i = 0; i < results.length; i++) { //console.log(results[i].vicinity); para = document.createElement('p'); aTag = document.createElement('a'); aTag.setAttribute('href',"/restaurants"); aTag.innerHTML = results[i].name; mypara = para.appendChild(aTag); console.log(mypara); nearby_places.appendChild(mypara); } console.log(mypara) in the second last line creates anchor tag but that is not wrapped in paragraph tag as it should be according to code logic . what i'm doing wrong A: appendChild returns the child back try consoling the the parent node para - console.log(para); to see the result of the append, The last line will look like this : nearby_places.appendChild(para); A: The appendChild() method modifies para directly, rather than leaving the original intact and returning a modified value. So, you should continue to use your para variable for the paragraph, rather than mypara. Your modified code would be: for (var i = 0; i < results.length; i++) { //console.log(results[i].vicinity); para = document.createElement('p'); aTag = document.createElement('a'); aTag.setAttribute('href',"/restaurants"); aTag.innerHTML = results[i].name; para.appendChild(aTag); nearby_places.appendChild(para); } More info: according to MDN, appendChild() returns the appended node. That's why your console.log() call was just showing the <a> tag. See: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild. A: Here is a sample fiddle that works: https://jsfiddle.net/fNPvf/22007/ para = document.createElement('p'); aTag = document.createElement('a'); aTag.setAttribute('href',"/restaurants"); aTag.innerHTML = "wendys"; para.appendChild(aTag); document.body.appendChild(para);
{ "language": "en", "url": "https://stackoverflow.com/questions/34005132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extract multiple date strings from a single varchar(MAX) column SQL Server I've inherited a report spec subsystem that needs to be tweaked. The mission is to add a date column to the tReports table, and populate it with the CreateDate that is (supposed to be) contained in the XML Code Spec. The problem is that some of the older reports don't have the CREATEDATE attribute, or as in one example below, the XML is valid but poorly formed, and the CREATEDATE cannot be retrieved using the xQuery that works for most of the other reports. Since I don't have an explicit creation date included in the spec, I'm using interpolation to estimate a reasonable date. One factor of the interpolation is to look at the date strings contained in the report spec--some will be useful, others not. There are too many reports (over 1,200) to visually skim each report spec for date strings. These date strings can appear in any location in the report spec, and there are a very large number of combinations of elements and attributes that can contain a date string. The ideal solution would be a listing of the reportID's and the date string ready to use in an UPDATE, but because date format varies (m/d/yy, mm/dd/yy, m/dd/yy ...) I'd be grateful to get a vew spurious characters surrounding the date string that I could clean up later. All the date strings will be from 2000 or later, so the search string I'v been using is '/20' which has provided good results. I've looked at many sites that discuss this kind of issue, and found only one solution by Mikael Eriksson that is something like what I'm describing, but I can't make it work after several hours of playing with it. How to extract multiple strings from single rows in SQL Server Is there a way, without using a cursor nor WHILE loop, to extract these embedded dates? -- Some representative data: (I'm using SQL Server 2008 R2) CREATE TABLE #ReportSpecs (ReportID INT, ReportSpec VARCHAR(MAX)) INSERT INTO #ReportSpecs ( ReportID, ReportSpec ) VALUES (136, '<ReportID>136</ReportID> <EmpIDCreator>23816</EmpIDCreator> <EmpName>Blanc, Melvin J</EmpName> <ReportType>0</ReportType> <ReportName>PSST Sys Spec</ReportName> <ReportData> <REPORT> <COLUMNS> <Column Name="JobNumber" Position="1" /> <Column Name="TaskType" Position="2" /> <Column Name="Assignees" Position="3" /> <Column NAME="JobDueDate" Position="4" /> <Column Name="ReferenceNumber" Position="5" /> <Column Name="Deliverable" Position="6" /> <Column Name="Priority" Position="7" /> </COLUMNS> <FILTERS> <FILTER NAME="TYPE" VALUE="To_Me" /> <FILTER NAME="Status" VALUE="All" /> <FILTER NAME="DateOptions" VALUE="DateRange" From="8/16/2002" To="8/23/2002" /> <FILTER NAME="FromDate" VALUE="8/16/2002" /> <FILTER NAME="ToDate" VALUE="8/23/2002" /> <FILTER NAME="Role" VALUE="All" /> </FILTERS> <parameters> <PARAMETER NAME="@Cascading" TYPE="integer" VALUE="0" /> <PARAMETER NAME="@EmpID" SYSTEM="true" TYPE="integer" VALUE="#Request.EmployeeIDAlias#" /> <PARAMETER NAME="@FromOrgs" TYPE="varchar(250)" VALUE="" /> <PARAMETER NAME="@ToOrgs" TYPE="varchar(250)" VALUE="" /> </parameters> <NAME>PSST Sys Spec</NAME> <OWNER> <ID>23816</ID> </OWNER> <source id="8" useinternalid="True" /> </REPORT> </ReportData>'), (311, '<ReportID>311</ReportID> <EmpIDCreator>7162</EmpIDCreator> <EmpName>Potter, Harry J</EmpName> <ReportType>0</ReportType> <ReportName>CPVC Synch Test</ReportName> <ReportData> <REPORT> <COLUMNS> <Column Name="JobNumber" Position="1" /> <Column Name="TaskType" Position="2" /> <Column Name="Subject" Position="3" /> <Column Name="CurrentAssignee" Position="4" /> <Column NAME="JobDueDate" Position="5" /> <Column Name="Deliverable" Position="6" /> <Column Name="Category" Position="7" /> <Column Name="Priority" Position="8" /> </COLUMNS> <FILTERS> <FILTER NAME="TYPE" VALUE="By_Orgs_6098,By_Orgs_6123" /> <FILTER NAME="Status" VALUE="Open" /> <FILTER NAME="DateOptions" VALUE="DateRange" From="3/25/2002" To="4/4/2002" /> <FILTER NAME="ReviewFromDate" VALUE="3/25/2002" /> <FILTER NAME="ReviewToDate" VALUE="4/4/2002" /> <FILTER NAME="Role" VALUE="All" /> </FILTERS> <parameters> <PARAMETER NAME="@Act" TYPE="integer" VALUE="0" /> <PARAMETER NAME="@MgrID" SYSTEM="true" TYPE="integer" VALUE="#Request.EmployeeIDAlias#" /> <PARAMETER NAME="@MgrIDActing" TYPE="integer" VALUE="" /> <PARAMETER NAME="@FromDept" TYPE="varchar(250)" VALUE="" /> <PARAMETER NAME="@FromEmp" TYPE="varchar(250)" VALUE="" /> <PARAMETER NAME="@ToDept" TYPE="varchar(250)" VALUE="" /> </parameters> <NAME>CPVC Synch Test</NAME> <OWNER> <ID>7162</ID> </OWNER> <source id="17" useinternalid="True" /> </REPORT> </ReportData>'), (1131, '<ReportID>1131</ReportID> <EmpIDCreator>13185</EmpIDCreator> <EmpName>Reed, Alan</EmpName> <ReportType>0</ReportType> <ReportName> ''"><script>alert(''hello'')</script> </ReportName> <ReportData> <Report NAME="''"> <script>alert(''hello'')</script>" CREATEDATE="12/7/2009"> <DESCRIPTION>sfasf</DESCRIPTION> <OWNER ID="13185"/> <SOURCE ID="1" USEINTERNALID="TRUE"/> <COLUMNS> <COLUMN NAME="JobNumber" POSITION="1" SORTORDER="asc"/> </COLUMNS> <FILTERS> <FILTER NAME="TYPE" VALUE="By_Me,To_Me" /> <FILTER NAME="ASGSTATUS" VALUE="Open" /> <FILTER NAME="DATEOPTIONS" VALUE="All" /> <FILTER NAME="STATUS" VALUE="Open" /> <FILTER NAME="ASGDATEOPTIONS" VALUE="All" /> <FILTER NAME="ROLE" VALUE="All" /> </FILTERS> <PARAMETERS> <PARAMETER NAME="@Me" TYPE="integer" VALUE="3" /> <PARAMETER NAME="@FromCost" TYPE="varchar(250)" VALUE=""/> <PARAMETER NAME="@ToCost" TYPE="varchar(250)" VALUE="" /> </PARAMETERS> <ADVANCEDSORT SortByA="JobNumber" SortOrderA="asc" SortByB="" SortOrderB="" SortByC="" SortOrderC="" /> </Report> </ReportData>'); /* Desired Output (A DISTINCT list would be better, but just getting this output would be GREAT.) ReportID DateString -------- ---------- 136 8/16/2002 136 8/23/2002 136 8/16/2002 136 8/23/2002 311 3/25/2002 311 4/4/2002 311 3/25/2002 311 4/4/2002 1131 12/7/2009 */ DROP TABLE #ReportSpecs Thanks for your time. A: select R.ReportID, D.V as DateString from #ReportSpecs as R cross apply (select cast(R.ReportSpec as xml)) as X(R) cross apply X.R.nodes('//@*, //*/text()') as T(X) cross apply (select T.X.value('.', 'varchar(max)')) as D(V) where charindex('/20', D.V) > 0 Result: ReportID DateString ----------- -------------------------- 136 8/16/2002 136 8/23/2002 136 8/16/2002 136 8/23/2002 311 3/25/2002 311 4/4/2002 311 3/25/2002 311 4/4/2002 1131 " CREATEDATE="12/7/2009">
{ "language": "en", "url": "https://stackoverflow.com/questions/21139578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When form has submit button with id='submit' value, form submit does not work While this jsfiddle works: <form method="post" id="myform1"> <input type="submit" value="submit" /> </form> document.getElementById("myform1").submit(); This jsfiddle does not work: <form method="post" id="myform2"> <input type="submit" id="submit" value="submit" /> </form> document.getElementById("myform2").submit(); Difference between them submit button has id in second code. Why? Note: while working this question, I encountered situation A: the difference is the type of the button not the id first example the type of the input is submit which submits forms. second example the type is button which doesn't submit forms after OP editted question: see that if you change the id of the submit button to basicly anything other than "submit" it works... A: This is noted on various sites such as this: http://www.joezimjs.com/javascript/dont-name-inputs-action-submit/ Having a button with id='submit' is also a known issue in jquery that hasn't been resolved http://bugs.jquery.com/ticket/1414 Presumably because the issue is outside of jquery's control and it'd require a hack. I'd be interested to know exactly why.
{ "language": "en", "url": "https://stackoverflow.com/questions/26544300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to do ajax on this scenario? javascript code function new_person_adder1() { var dataAjax = { 'entry_new_person_': $('#entry_new_person_1').val(), 'pop_new_person_identity_no': $('#pop_new_person_identity_no1').val(), 'identity_type_no': $('#select2_identity_type_bc_for_new_person_1').val() }; jQuery.ajax({ url: 'WalkReserve.aspx/quick_person_entry', type: 'POST', data: JSON.stringify(dataAjax), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (data) { console.log(data.d); if (data.d > 0) { alert('Successfully Added'); } else { alert('Failed to entry data!'); } }, error: function (result) { alert('Failed!'); console.log('Failed' + result.responseText); } }); } C# code [WebMethod] public static string quick_person_entry(dynamic entry_new_person_, dynamic identity_type_, dynamic pop_new_person_identity_no) { return Convert.ToString(BAL.pop_quick_person_entry(entry_new_person_, identity_type_, pop_new_person_identity_no)); } ajaxdata i am getting following error Failed{"Message":"Invalid web service call, missing value for parameter: \u0027identity_type_\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"} I want to send do ajax here but for some weird reason I am not able to do it. I am getting above error. can anybody point my mistake or help me? A: Look at the parameters the method expects: entry_new_person_ identity_type_ pop_new_person_identity_no And the parameters being sent: entry_new_person_ identity_type_no pop_new_person_identity_no The middle parameter is different. It's similar, but it's not the same thing. The model binder isn't smart enough (thankfully) to match things which are just similar. Changing the key in the JavaScript code should fix it: var dataAjax = { 'entry_new_person_': $('#entry_new_person_1').val(), 'pop_new_person_identity_no': $('#pop_new_person_identity_no1').val(), 'identity_type_': $('#select2_identity_type_bc_for_new_person_1').val() }; (Or changing the parameter name in the method would fix it too. Depends on which one is a bigger change. For example, if you have tons of JavaScript calls to this method then a single change to the method would be easier than many changes to the invocations of the method.) A: Try after removing dataType: 'json' then It will work. And define Web Type in web mthod as POST
{ "language": "en", "url": "https://stackoverflow.com/questions/24120728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot set headers after they are sent to the client using nodejs mysql What I am attempting to do is write a statement to check if email exists in my mysql database when a user registers. In postman it sends me the correct error message of "user already taken" however the server crashes after and displays "cannot set headers after they are sent to the client." I have read similar posts but did not help. //The following code is in my user.service.js file: const pool = require("../../config/database"); module.exports = { //Create new user createUser: (data, callBack) =>{ pool.query( `insert into registration(name, email, password, confirm_password) values(?,?,?,?)`, [ data.name, data.email, data.password, data.confirm_password ], (error, results, fields) =>{ if(error){ return callBack(error); } return callBack(null, results); } ); } } //The following code is in my user.controller.js file: const { createUser, } = require("./user.service"); const pool = require("../../config/database"); module.exports = { createUser: (req, res) =>{ const body = req.body; const salt = genSaltSync(10); pool.query('SELECT email FROM registration WHERE email = ?', [body.email], (error, results) =>{ if(error){ console.log(error); } if(results.length > 0){ return res.status(400).json({ message: 'User already taken' }) } }) createUser(body, (err, results) => { if(err){ console.log(err); return res.status(500).json({ success:0, message:"Error in database connection" }); } return res.status(200).json({ success: 1, message: `User ${results.insertId} signed up successfully`, data: results }); }); } } //The following code is from user.router.js file: const { createUser, } = require("./user.controller"); const router = require("express").Router(); router.post("/signup", createUser); module.exports = router; A: In your createUser function that is executed on the post request you are doing two things. First you check whether a user with the provided email exists and, second, you create a user. However, those functions are not executed consecutively, instead they are running simultaneously and thus create a race condition. So going off on your example, if the email check query SELECT email FROM registration WHERE email = ? is faster and the user already exists, it will respond with: return res.status(400).json({ message: 'User already taken' }) but the createUser function (below) is still running and once it is finished, it will try to also send a response. Therefore, you are presented with an application crash in the console even though in the postman you can see the response stating that the user already exists. In order to fix this error you should execute the createUser function only if the results.length is 0 inside the callback provided to the email check query, like so: createUser: (req, res) => { const body = req.body; const salt = genSaltSync(10); pool.query('SELECT email FROM registration WHERE email = ?', [body.email], (error, results) =>{ if(error){ console.log(error); } if(results.length > 0){ return res.status(400).json({ message: 'User already taken' }) } createUser(body, (err, results) => { if(err){ console.log(err); return res.status(500).json({ success:0, message:"Error in database connection" }); } return res.status(200).json({ success: 1, message: `User ${results.insertId} signed up successfully`, data: results }); }); }) } Now you execute the createUser function only if a user with the provided email doesn't exist, which effectively removes the race condition between the two functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/63892004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript quiz not transitioning I am trying to make a quiz where I display one question at a time and when you answer it, you move to the next question. I have some basic markup like so <div id="quizzie"> <div class="col-md-12 quiz-container current"> <div class="col-md-6"> <img src="../images/image.jpg"> </div> <div class="col-md-6 extra"> <ul class="quiz-step step1"> <li class="question"> <div class="question-wrap"> <h3 class="question-title">Some Question:</h3> </div> </li> <li class="quiz-answer low-value" data-quizIndex="2" data-number="1"> <div class="col-md-12 add-border add-spacing"> <div class="answer-wrap"> <p class="answer-text">This Thing</p> </div> </div> </li> <li class="quiz-answer high-value" data-quizIndex="4" data-number="1"> <div class="col-md-12 add-border add-spacing"> <div class="answer-wrap"> <p class="answer-text">That Thing</p> </div> </div> </li> </ul> </div> </div> <div class="col-md-12 quiz-container"> <div class="col-md-6"> <img src="../images/image.jpg"> </div> <div class="col-md-6 extra"> <ul class="quiz-step step2"> <li class="question"> <div class="question-wrap"> <h3 class="question-title">Some Question:</h3> </div> </li> <li class="quiz-answer low-value" data-quizIndex="2" data-number="2"> <div class="col-md-12 add-border add-spacing"> <div class="answer-wrap"> <p class="answer-text">This Thing</p> </div> </div> </li> <li class="quiz-answer high-value" data-quizIndex="4" data-number="2"> <div class="col-md-12 add-border add-spacing"> <div class="answer-wrap"> <p class="answer-text">That Thing</p> </div> </div> </li> </ul> </div> </div> </div> I then make sure the first question is displayed, and the next questions are hidden #quizzie .quiz-container { display: none; padding:0; } #quizzie .current { display: block; } Now the Javascript code I have at the moment is like so var quizSteps = $('#quizzie .quiz-step'); quizSteps.each(function () { var currentStep = $(this), ansOpts = currentStep.children('.quiz-answer'); ansOpts.each(function () { var eachOpt = $(this); eachOpt[0].addEventListener('click', check, false); function check() { var $this = $(this), value = $this.attr('data-quizIndex'), answerScore = parseInt(value); if (currentStep.children('.active').length > 0) { var wasActive = currentStep.children('.active'), oldScoreValue = wasActive.attr('data-quizIndex'), oldScore = parseInt(oldScoreValue); currentStep.children('.active').removeClass('active'); $this.addClass('active'); } else { $this.addClass('active'); updateStep(currentStep); } } }); }); function updateStep(currentStep) { if(currentStep.hasClass('current')){ currentStep.removeClass('current'); currentStep.next().addClass('current'); } } Now it seems to set the active class correctly, but it does not set the current class correctly which means I am always stuck on question one. How can I get it moving onto the next question? Thanks A: you should switch current class on ".quiz-container" element not on ".quiz-step" element. Js fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/32873372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "__aeabi_ldivmod" undefined when compiling kernel module I'm trying to compile a kernel module (which I wrote myself) on a raspberry pi. I am compiling it in the target environment. I get the following output: make -C /lib/modules/3.12.23-1.20140626git25673c3.rpfr20.armv6hl.bcm2708/build M=/home/harmic/horus/ppminput modules make[1]: Entering directory `/usr/src/kernels/3.12.23-1.20140626git25673c3.rpfr20.armv6hl.bcm2708' CC [M] /home/harmic/horus/ppminput/ppminput.o Building modules, stage 2. MODPOST 1 modules WARNING: "__aeabi_ldivmod" [/home/harmic/horus/ppminput/ppminput.ko] undefined! CC /home/harmic/horus/ppminput/ppminput.mod.o LD [M] /home/harmic/horus/ppminput/ppminput.ko make[1]: Leaving directory `/usr/src/kernels/3.12.23-1.20140626git25673c3.rpfr20.armv6hl.bcm2708' Sure enough, if I try to insert the module, I get: insmod: ERROR: could not insert module ./ppminput.ko: Unknown symbol in module and in syslog: Sep 2 22:44:26 pidora kernel: [ 7589.354709] ppminput: Unknown symbol __aeabi_ldivmod (err 0) In my module, I have identified the line causing the problem: unsigned int chan_abs_val = tdiff / CHAN_SCALE; (where tdiff is an s64, and CHAN_SCALE is an integer literal). If I comment the division out, the problem goes away. That is the only line using division in my module. A bit of googling turned up a few references to this issue, but none I could find in the context of compiling kernel modules. My makefile looks like this: obj-m += ppminput.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean Environment Details: * *The Pi is running Pidora 2014 (Fedora 20). *The kernel is 3.12.23-1.20140626git25673c3.rpfr20.armv6hl.bcm2708. *gcc is 4.8.2. Update I obviously did not search using the correct terms. Another search has bought up many references, but no solutions as such. Reading them I am getting the opinion that one should not do any 64bit divisions inside the kernel if one wants to compile for ARM? A: On most 32-bit CPUs, 64-bit division must be implemented with a slow library function. To prevent the compiler from generating unobviously slow code, Linux does not implement these functions. If you want to do 64-bit divisions, you have to do them explicitly. Use do_div() from <asm/div64.h>.
{ "language": "en", "url": "https://stackoverflow.com/questions/25623956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: (#12) singular published story API is deprecated for versions v2.4 and higher I am trying to share photos on Instagram using Graph API. Does anyone know how to fix the error I'm getting? It gives an error even though I share it as in the document, I gave all permissions for the user. Using Request 1 https://graph.facebook.com/v10.0/ig-userid/media?image_url=https://as2.ftcdn.net/jpg/00/53/45/31/500_F_53453175_hVgYVz0WmvOXPd9CNzaUcwcibiGao3CL.jpg&caption=%test&access_token={access_token} Using Request 2 https://graph.facebook.com/v10.0/ig-userid/media?image_url=https://as2.ftcdn.net/jpg/00/53/45/31/500_F_53453175_hVgYVz0WmvOXPd9CNzaUcwcibiGao3CL.jpg&caption=%test Facebook Example Request graph.facebook.com/17841400008460056/media ?image_url=https//www.example.com/images/bronzed-fonzes.jpg &caption=#BronzedFonzes!
{ "language": "en", "url": "https://stackoverflow.com/questions/67918516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redux Saga: Await Promise I have a promise that is already invoked and has to be awaited. Basically: const foo = () => Promise.resolve('foo'); // The real promise takes time to resolve. const result = foo(); await result; // This line has to happen in the saga How can I await the pending promise? If I wrap it in call Redux Saga tries to invoke it and crashes. A: If you're in a saga, simply yield the promise. Redux saga will wait for it to resolve and then resume the saga, much like await would do in an async function: const foo = () => Promise.resolve('foo'); const resultingPromise = foo(); function* exampleSaga() { const result = yield resultingPromise; console.log(result); // 'foo' } If the promise might reject, you can wrap it in a try catch: try { const result = yield resultingPromise; console.log(result); } catch(err) { console.log('promise rejected', err); } A: const myFunc = async () => { const result = await foo(); return result; // or just return foo() without await, as it is last statememnt in async func } Otherwise you can always do foo() .then((result) => console.log('result', result)) .catch((err) => console.error(err));
{ "language": "en", "url": "https://stackoverflow.com/questions/59141316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Casting 'findViewById(R.id.)' to 'Button' is redundant So I'm trying to build a scanner and generator for QR Code. Here's my code for the scanner: private Button scan_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reader); scan_btn = (Button) findViewById(R.id.scan_btn); final Activity activity = this; scan_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { IntentIntegrator integrator = new IntentIntegrator(activity); integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES); integrator.setPrompt("Scan"); integrator.setCameraId(0); integrator.setBeepEnabled(false); integrator.setBarcodeImageEnabled(false); integrator.initiateScan(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if(result != null){ if(result.getContents()==null){ Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, result.getContents(),Toast.LENGTH_LONG).show(); } } else { super.onActivityResult(requestCode, resultCode, data); } }} I got a warning like this: Casting 'findViewById(R.id.scan_btn)' to 'Button' is redundant Is gonna affect my app? cause when I tried to open my app, it suddenly crash. UPDATE: Here's my Generator code: public class GeneratorActivity extends AppCompatActivity { EditText text; Button gen_btn; ImageView image; String text2Qr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_generator); text = findViewById(R.id.text); gen_btn = findViewById(R.id.gen_btn); image = findViewById(R.id.image); gen_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { text2Qr = text.getText().toString().trim(); MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); try{ BitMatrix bitMatrix = multiFormatWriter.encode(text2Qr, BarcodeFormat.QR_CODE,200,200); BarcodeEncoder barcodeEncoder = new BarcodeEncoder(); Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix); image.setImageBitmap(bitmap); } catch (WriterException e){ e.printStackTrace(); } } }); }} My MainActivity for the 'buttons' code: public class MainActivity extends AppCompatActivity { Button gen, scan; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gen = findViewById(R.id.gen); scan = findViewById(R.id.scan); gen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent gIntent = new Intent(MainActivity.this, GeneratorActivity.class); startActivity(gIntent); } }); scan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent rIntent = new Intent(MainActivity.this, ReaderActivity.class); startActivity(rIntent); } }); }} UPDATE: There's nothing wrong with the redundant problem. This case is solved on xml code typo mistake. So its already answered on one of my questions. Thanks. Please looking forward on my others questions. I really need it to get done for my project soon. A: Try out this, Change your code as below : scan_btn = findViewById(R.id.scan_btn); A: It does not affect your code. This is a new feature of Android studio that directly maps the widget from your XML to Java code. Your app may crash for any other reason A: Starting with API 26, findViewById uses inference for its return type, so you no longer have to cast. Old definition: Button btn = (Button) findViewById(R.id.btn) New definition: <T extends View> T findViewById(R.id.value) So if your compile Sdk is at least 26, it means that you can make use of this. No need casting.
{ "language": "en", "url": "https://stackoverflow.com/questions/48587320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Adding fade in/out to grid row selection In this StackBlitz I have a Kendo for Angular grid. When you click on the button, the second row will be selected after half second, and unselected automatically after two seconds. What I need is the selected row to fade-in on selection and fade-out after two seconds, is this possible? @Component({ selector: 'my-app', template: ` <button type="button" (click)="select()">Select</button> <kendo-grid [data]="gridData" [height]="410" kendoGridSelectBy="ProductID" [(selectedKeys)]="selection"> <kendo-grid-column field="ProductID" title="ID" width="40"> </kendo-grid-column> <kendo-grid-column field="ProductName" title="Name" width="250"> </kendo-grid-column> </kendo-grid> ` }) export class AppComponent { selection: number[] = []; public gridData: any[] = products; select(){ setTimeout(() => { this.selection = [2]; setTimeout(() => { this.selection = []; }, 2000); }, 500); } } A: Not sure if this is the most optimized solution, but you can use: * *rowClass (https://www.telerik.com/kendo-angular-ui/components/grid/api/GridComponent/#toc-rowclass) *selectionChange (https://www.telerik.com/kendo-angular-ui/components/grid/api/GridComponent/#toc-selectionchange) With that function and event, you can add a custom class to your selected rows and use CSS for the fade animation. Your code would be something like this: import { Component } from '@angular/core'; import { products } from './products'; import { Component, ViewEncapsulation } from '@angular/core'; import { RowClassArgs } from '@progress/kendo-angular-grid'; @Component({ selector: 'my-app', encapsulation: ViewEncapsulation.None, styles: [` .k-grid tr.isSelected { background-color: #41f4df; transition: background-color 1s linear; } .k-grid tr.isNotSelected { background-color: transparent; transition: background-color 2s linear; } `], template: ` <kendo-grid [data]="gridData" [height]="410" kendoGridSelectBy="ProductID" [rowClass]="rowCallback" (selectionChange)="onSelect($event)"> <kendo-grid-column field="ProductID" title="ID" width="40"> </kendo-grid-column> <kendo-grid-column field="ProductName" title="Name" width="250"> </kendo-grid-column> </kendo-grid> ` }) export class AppComponent { public gridData: any[] = products; public onSelect(e){ setTimeout(() => { e.selectedRows[0].dataItem.isSelected = true; setTimeout(() => { e.selectedRows[0].dataItem.isSelected = false; }, 2000); }, 500); } public rowCallback(context: RowClassArgs) { if (context.dataItem.isSelected){ return { isSelected: true, }; } else { return {isNotSelected: true}; } } } -- EDIT -- Just noticed that you want to do that only with the second row. In that case, you can replace line e.selectedRows[0].dataItem.isSelected = true; with: products[1].isSelected = true;. And use your button to call the onSelect function.
{ "language": "en", "url": "https://stackoverflow.com/questions/52353921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mx:button fillColors not working I work with FB4.6 and I try to apply a fillColor on my button. package fr.int.component.customNavTab { import mx.controls.Button; import mx.controls.ToggleButtonBar; import mx.core.IFlexDisplayObject; import mx.states.OverrideBase; public class IconToggleButtonBar extends ToggleButtonBar { public function IconToggleButtonBar() { super(); } [Inspectable (enumeration='left,right,top,bottom', defaultValue='left')]   public var labelPlacement:String = 'left';   public var color:uint; override protected function createNavItem(label:String, icon:Class=null):IFlexDisplayObject { var b:Button = Button (super.createNavItem(label,icon)); b.labelPlacement = labelPlacement; b.setStyle('fillColors', [0x86C543, 0xE6E6E6]); return b; } } } But this has no effect on my button. Can you help me? Thanks A: You're passing in a string '[0x86C543, 0xE6E6E6]' where you need an array. The [] brackets denote an Array but by placing this in quotes it is read in as a string. Change this to b.setStyle('fillColors', [0x86C543, 0xE6E6E6]); A: fillColors on mx:Button works only in Halo theme. So you need to use Flex 3 SDK or try something like this in Flex 4 http://blog.flexexamples.com/2009/07/14/using-the-halo-theme-in-flex-4/ EDIT: Here's an example. Try to create project with Flex 4 SDK and put this code to application: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> <fx:Style> @namespace s "library://ns.adobe.com/flex/spark"; @namespace mx "library://ns.adobe.com/flex/mx"; mx|Button{ fillColors: #FF0000, #00FF00 } </fx:Style> <mx:Button /> </s:Application> There will be a warning The style 'fillColors' is only supported by type 'mx.controls.Button' with the theme(s) 'halo'. And it doesn't matter that you are using mx:Button, the fact that you need to use halo theme matters. So if you want change fillColors of mx:Button you have 2 choices that I've posted before
{ "language": "en", "url": "https://stackoverflow.com/questions/10195221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SpriteKit: 'String' is not convertible to 'DictionaryIndex' whilst programming a SKAction.animateWithTextures(...) I came across this error ('String'is not convertible to 'DictionaryIndex') when I used the String keys of my 'states' to retrieve the SKTexture relevant. Can someone explain what might be the cause of the error? import SpriteKit class Player { let states: Dictionary<String, SKTexture> = [ "standing": SKTexture(imageNamed: "standing"), "right1": SKTexture(imageNamed: "right1"), "right2": SKTexture(imageNamed: "right2"), "right3": SKTexture(imageNamed: "right3"), "left1": SKTexture(imageNamed: "left1"), "left2": SKTexture(imageNamed: "left2"), "left3": SKTexture(imageNamed: "left3") ] let LEFT: UInt32 = 1 << 0 let FRONT: UInt32 = 1 << 1 let RIGHT: UInt32 = 1 << 2 var node: SKSpriteNode! var status: UInt32! let delay = SKAction.waitForDuration(NSTimeInterval(0.1)) var runLeft: SKAction! var runRight: SKAction! init(){ for state in states { state.1.filteringMode = .Nearest } node = SKSpriteNode(texture: states["standing"]) node.physicsBody = SKPhysicsBody(rectangleOfSize: node.size) node.physicsBody.dynamic = false status = FRONT runLeft = SKAction.animateWithTextures([states["left1"], states["left2"], states["left1"], states["left3"]]!, timePerFrame: 0.1) runRight = SKAction.animateWithTextures([states["right1"], states["right2"], states["right1"], states["right3"]]!, timePerFrame: 0.1) } } A: Dictionary lookups return optionals because the key might not exist. You need to unwrap each of the lookups since they are type SKTexture!: runLeft = SKAction.animateWithTextures([states["left1"]!, states["left2"]!, states["left1"]!, states["left3"]!], timePerFrame: 0.1) runRight = SKAction.animateWithTextures([states["right1"]!, states["right2"]!, states["right1"]!, states["right3"]!], timePerFrame: 0.1)
{ "language": "en", "url": "https://stackoverflow.com/questions/25647978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prosody provide etc/prosody location in Windows I am using prosody in windows and from the documentation (https://prosody.im/doc), it is shown that it takes the location to find a file through etc/prosody/. Unfortunately, I am using windows and I want to provide the location of a file. The right location of file: C:\Users\vika\.jitsi-meet-cfg\prosody\config\prosody.cfg.lua When I enter the command using docker through git bash: $ winpty docker-compose exec prosody prosodyctl --config /config/prosody.cfg.lua register vika meet.jitsi pass I get this message: ************************** Prosody was unable to find the configuration file. We looked for: /etc/prosody/C:/Program Files/Git/config/prosody.cfg.lua A sample config file is included in the Prosody download called prosody.cfg.lua.dist Copy or rename it to prosody.cfg.lua and edit as necessary. More help on configuring Prosody can be found at https://prosody.im/doc/configure Good luck! ************************** As you see, the location is completely wrong. How do I provide the right location in my command?
{ "language": "en", "url": "https://stackoverflow.com/questions/72714580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error: could not find implicit value for parameter gen: shapeless.Generic Wrote this simple code for shapeless which does not work import shapeless._ import shapeless.ops.hlist._ case class Person(name: String, age: Int) val genPerson = Generic[Person] But get compile error <console>:21: error: could not find implicit value for parameter gen: shapeless.Generic[Person] val genPerson = Generic[Person]
{ "language": "en", "url": "https://stackoverflow.com/questions/37694509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Neo4j Best way to export database to CSV I have tried the Cypher export csv, but the query itself takes too long, and it didn't seem practical since i needed to export a whole database which ranges upwards to a few gigabytes in size. Is there a tool that lets me export a huge database in fairly good time? A: You should take a look at the APOC procedures. This is straightforward to install within your Neo4j environment and provide many additional functionalities, e.g. to export your results or data to .csv file.
{ "language": "en", "url": "https://stackoverflow.com/questions/50726439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Windows Powershell Reading Tab Delimited File Problem OK so what I'm trying to accomplish should in theory be very easy but I can't figure out what's going wrong. I am trying to use the import-csv cmdlet to read in a .tsv file. My syntax is: import-csv -path "myfile" -delimiter "`t" The problem is that this only displays the first column from my file. Why are the other data columns not being displayed? I checked the file in notepad to verify that the data is in fact separated by a tab and it is. Any help would be appreciated. A: Pls edit your question and put the right data. Here is what I see based on your comment PS C:\Scripts\Scratch> Import-Csv -Path .\test.csv -Delimiter "`t" Col1 Col2 Col3 Col4 ---- ---- ---- ---- Data1 Data2 Data3 Data4 Data5 Data6 Data7 Data8
{ "language": "en", "url": "https://stackoverflow.com/questions/4839786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nested entities are not supported in r2dbcEntityTemplate.insert I have 2 entities as batch & batchDetailEntity. I try to insert records to my database postgresql using spring boot reactor r2dbcEntityTemplate.insert() & I am getting error like Nested entities are not supported. My code Error A: Instead of insert(Mono.just(batchDetailEntity)) put insert(batchDetailEntity) It may work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/69691409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails Spring Security Core Plugin - adding flash message to login page I am using the Grails Spring Security Core Plugin to secure a certain action using the following annotation. @Secured(['IS_AUTHENTICATED_REMEMBERED']) This causes the action to redirect to my login page if the user is not logged in. Once they are logged in they are then redirected to the original action. How can I add a flash message to the login page in this scenario, i.e. flash.message = "You must be logged in to submit a news story" To clarify, I would only want the message to be displayed if the user was redirected to the login page after attempting to access this specific action. Other actions would not trigger the message. A: I have solved this as follows. * *Remote the annotation from the action. *Add the following code at the beginning of the action (news and submit being the relevant controller and action respectively). if (!springSecurityService.isLoggedIn()) { flash.message = "You must be logged in to submit a news story." redirect(controller:"login", action: "auth", params:["spring-security-redirect" : "/news/submit"]) } *Add the following to the login form. <input type='hidden' name='spring-security-redirect' value='${params['spring-security-redirect']}'/> A: Add, for example, this to your login view: <sec:noAccess url="/admin/listUsers"> You must be logged in to view the list of users. </sec:noAccess> See the security taglib's documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/4185261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python - scraping data with similar format my first time writing here, although i am spending enough time looking for answers. A rather simple question where i hope someone can help! I want to scrape some data from below url: https://tracker.icon.foundation/addresses/1?count=100 https://tracker.icon.foundation/block/1 The website is dynamically updated, thus i had to use beautiful soup with Selenium. I am trying to use the same code to scrape info (addresses in both cases), as it seems to me the structure is exactly the same in the two url's. I can scrape from the first one, but the second returns an empty list.. I have 2 questions: a) Any idea why? :) b) Performance is rather slow - any better way to do that? Thanks! The code I am using for the first url is the following. from bs4 import BeautifulSoup import requests from selenium import webdriver driver = webdriver.Chrome(executable_path="MYPATHFORWEBDRIVER") driver.get('https://tracker.icon.foundation/addresses/1?count=100') res = driver.execute_script('return document.documentElement.outerHTML') driver.quit() soup = BeautifulSoup(res, 'lxml') box = soup.find('div', {'class': 'table-box'}) all_addresses = box.find_all('span', {'class': 'ellipsis'}) AddressList = [] for address in all_addresses: a_type = address.find('a', {'class': 'on'}).text AddressList.append(a_type) print(AddressList) A: As you mentioned the page is loaded dynamically. Issue here is that you get the html prior the html tree you are looking for being part of the DOM. driver = webdriver.Chrome() driver.get('https://tracker.icon.foundation/addresses/1?count=100') # Wait until the element is loaded (found) WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.table-box'))) #Parse the page_source soup = BeautifulSoup(driver.page_source, 'lxml') driver.quit() box = soup.find('div', {'class': 'table-box'}) all_addresses = box.find_all('span', {'class': 'ellipsis'}) AddressList = [] for address in all_addresses: a_type = address.find('a', {'class': 'on'}).text AddressList.append(a_type) print(AddressList) Output: ['hxcd6f04b2a5184715ca89e523b6c823ceef2f9c3d', 'hx9f0c84a113881f0617172df6fc61a8278eb540f5', 'hx1729b35b690d51e9944b2e94075acff986ea0675', 'hx562dc1e2c7897432c298115bc7fbcc3b9d5df294', 'hx68646780e14ee9097085f7280ab137c3633b4b5f', 'hx0cc3a3d55ed55df7c8eee926a4fafb5412d0cca4', 'hx9d9ad1bc19319bd5cdb5516773c0e376db83b644', 'hxa9c54005bfa47bb8c3ff0d8adb5ddaac141556a3', 'hxc1481b2459afdbbde302ab528665b8603f7014dc', 'hx3f945d146a87552487ad70a050eebfa2564e8e5c', 'hx6b38701ddc411e6f4e84a04f6abade7661a207e2', 'hx7062a97bed64624846f3134fdab3fb856dce7075', 'hx8913f49afe7f01ff0d7318b98f7b4ae9d3cd0d61', 'hx980ab0c7473013f656339795a1c63bf44898ce95', 'hxbc2f530a7cb6170daae5876fd24d5d81170b93fe', 'hxc17ff524858dd51722367c5b04770936a78818de', 'hxfc7888bf63d45df125cf567fd8753c05facb3d12', 'hxd3b53e10d8c4c755879be09ff9ba975069664b7a', 'hxdf6bd350edae21f84e0a12392c17eac7e04817e7', 'hx9e19d60c9d6a0ecc2bcace688eff9053622c0c4c', 'hxa527f96d8b988a31083167f368105fc0f2ab1143', 'hx1000000000000000000000000000000000000000', 'hx294c5d0699615fc8d92abfe464a2601612d11bf7', 'hxd42f6e3abfb7f5b14dbdafa34f03ffecf2a53a92', 'hxe322ab9b11b63c89b85b9bc7b23350b1d6604595', 'hx87b6da94535754c2baee9d69010eb1b91eaa4c37', 'hx58b2592941f61f97c7a8bed9f84c543f12099239', 'hx8d6aa6dce658688c76341b7f70a56dce5361e7ef', 'hx930bb66751f476babc2d49901cf77429c5cf05c1', 'hx39f2636582cee00b72586a2f74dc6028c0f0213f', 'hxd9fb974459fe46eb9d5a7c438f17ae6e75c0f2d1', 'hx49c5c7eead084999342dd6b0656bc98fa103b185', 'hx76dcc464a27d74ca7798dd789d2e1da8193219b4', 'hxc05ec08b6446a2a16b64eb19b96ea02225b840ab', 'hxe295a8dc5d6c29109bc402e59394d94cf600562e', 'hxf6f5f2583a0821f281fe7d35b013b9389daf2aaa', 'hxb6a65d0e7d5c1c0150310287e97c612a8ac825eb', 'hx6d14b2b77a9e73c5d5804d43c7e3c3416648ae3d', 'hxeb00139ddd1fa4507d3158e46e22c4ab7e8b9202', 'hx538de7e0fc0d312aa82549aa9e4daecc7fabcce9', 'hx6eb81220f547087b82e5a3de175a5dc0d854a3cd', 'hxc4193cda4a75526bf50896ec242d6713bb6b02a3', 'hx266c053380ad84224ea64ab4fa05541dccc56f5f', 'hx476455c56c64fea4f425bd62f0d2d3ab8cdcace0', 'hx85532472e789802a943bd34a8aeb86668bc23265', 'hx56ef2fa4ebd736c5565967197194da14d3af88ca', 'hx5d0409cabaacd0f1ef22d32f41a30649ee990103', 'hxbf90314546bbc3ed980454c9e2a9766160389302', 'hxe07878b53679ba1278d0aab1dac7646d8898d344', 'hx96505aac67c4f9033e4bac47397d760f121bcc44', 'hx18d14ad97ab2903dfc246ccc4e5631a3a1e13141', 'hx39f24d1d23b710b9d6ef6f56acfb3022deed8f4d', 'hxc574629fa3d1cc846611f1ab91d504ad7fc35413', 'hxd7a34c15c2345d9f0891545350181c7b162d9e08', 'hx314348ecbaf01ff6c65c2877a6c593a5facecb35', 'hx23cb1d823ef96ac22ae30c986a78bdbf3da976df', 'hx307c01535bfd1fb86b3b309925ae6970680eb30d', 'hx206846faa5ba46a3717e7349bff9c20d6fe1bba3', 'hx161665fb51075d37cee2c98c2eacbc94d207a58b', 'hxaf3a561e3888a2b497941e464f82fd4456db3ebf', 'hxa55446e81997c03ee856a58ee18432325a4ef924', 'hx6607ef84572ac9bdb1ebbcf49bd0cddaf8903b8e', 'hx37f86d0a4e1e2fada3ca724a401037c83e0a670e', 'hxc4bb0a9c4b3e9e5953262aa7cb940dbecb568ff6', 'hxc39a4c8438abbcb6b49de4691f07ee9b24968a1b', 'hxc35567f68c43bd98b020e5f0fab69ca21edb2726', 'hxc0fc3fca32bddba77f372c69c5998c1da81d531d', 'hx25c5dace83bceae42c11360a07c9e42a3b5c6122', 'hx387f3016ee2e5fb95f2feb5ba36b0578d5a4b8cf', 'hx94a7cd360a40cbf39e92ac91195c2ee3c81940a6', 'hx748717b9f846120033ba44e986722d82ef710afb', 'hxebfc6198ce53846b2e5d4ef31d6d13d0fa951c01', 'hx4602589eb91cf99b27296e5bd712387a23dd8ce5', 'hxa67e30ec59e73b9e15c7f2c4ddc42a13b44b2097', 'hx558b4cd8cd7c25fa25e3109414bb385e3c369660', 'hxad2bc6446ee3ae23228889d21f1871ed182ca2ca', 'hx777ee46b7b9d90a26388fbcdeafc742f5f217af7', 'hx10ed7a7065d920e146c86d3915491f5a67248647', 'hx33fc29d457e7815fe6c7cec4304500d5214fdac1', 'hx1494e29d38aea1a8e39fb40663c37f714bffb9df', 'hx9db3998119addefc2b34eaf408f27ab8103edaef', 'hxa91a8cd8141d192f78540d092d912456fb81d281', 'hx0b047c751658f7ce1b2595da34d57a0e7dad357d', 'hxc0b37fc42b52bf467720cf362c87c650ae3a7915', 'hx1216aa95cf2aea0a387b7c243412022f3d7cf29f', 'hx4c7c152410d4defd66da1d6c399c01de0bc295a5', 'hx4d83813703f81cdb85f952a1d1ee736faf732655', 'hx6d2240f9c5fd0db5df6977ee586c3d74e1b1e4aa', 'hxaafc8af9559d5d320745345ec006b0b2170194aa', 'hxabdde23cda5b425e71907515940a8f23e29a3134', 'hx6c22cdba886614d3173e3d2499dc1597bdb57f2c', 'hxd8ba6317da2eec0d9d7d1feed4c9c1f3cf358ae1', 'hxdd4bc4937923dc140adba57916e3559d039f4203', 'hx27664cffd284b8cf488eefb7880f55ce82f42297', 'hx8243caf740598c2b8d57c177adc999da68ea46bf', 'hx230fdd2eb239d5f590c7ff2d94a32b8899fc0628', 'hxd3f062437b70ab6d6a5f21b208ede64973f70567', 'hxc41d0b098fe9b86b241dfbfa9741f00975db2847', 'hxed97cf0deba62ffe843262f7f4596e155e8ea0b9', 'hx8d45deb8de633ca9d5de5fc5a64c51bccd8e9960'] Note you will need the following additional imports: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By For your other question about performance, you might use an headless browser which will speed things up a bit. options = webdriver.ChromeOptions() options.add_argument('--headless') driver = webdriver.Chrome(options=options) A: The data is loaded dynamically, therefore requests won't support it. However, we can get the data via sending a GET requests to https://tracker.icon.foundation/v3/address/list?page=<PAGE NUM>&count=100 To get all the data from pages 1-100, we can use the range() function import requests url = "https://tracker.icon.foundation/v3/address/list?page={}&count=100" for page in range(1, 101): print("URL: ", url.format(page)) response = requests.get(url.format(page)).json() print([data["address"] for data in response["data"]], "\n") Output (partial): URL: https://tracker.icon.foundation/v3/address/list?page=1&count=100 ['hxcd6f04b2a5184715ca89e523b6c823ceef2f9c3d', .... 'hx8d45deb8de633ca9d5de5fc5a64c51bccd8e9960'] ... ...
{ "language": "en", "url": "https://stackoverflow.com/questions/65461468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I assign a input number as a variable in Android Studio? I want to make an random player picker app so first I need to take the number of players playing the game from the user which will be my variable and then my app will choose a random number out of 1 to that number, but I don't know how to use that input number as a variable. Here is my code: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="97dp" android:layout_marginTop="556dp" android:onClick="onbuttonClicked" android:text="@string/start" android:textSize="55sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.497" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/enter_number_of_players01" android:textColor="#2CB5F3" android:textSize="35sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.571" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.179" /> <EditText android:id="@+id/number" android:layout_width="351dp" android:layout_height="86dp" android:autofillHints="" android:inputType="number" android:labelFor="@id/number" android:textSize="30sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.491" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.453" /> </androidx.constraintlayout.widget.ConstraintLayout> A: Does this works? Button button = (Button) findViewById(R.id.button); button .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText et = findViewById(R.id.number); int num = Integer.parseInt(et.getText().toString()); // num now have the number user given as input } }); A: Create a static variable for the input number. static int userInputNumber = 0; Initialized your Element like EditText and Button in your onCreate method. Button button = findViewById(R.id.button); EditText editText = findViewById(R.id.number); Then here, set the onClickListener on the Button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Set the userInputNumber, use the Integer.parseInt because what the userinput //is always a String unless you manually set the userinput type userInputNumber = Integer.parseInt(editText.getText().toString()); //Then do what you want when button is clicked } }); Then after that, you can use the userInputNumber in any function you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/64540526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }